Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using an Ajax post to submit form data to the server, be validated and then return a message based on whether or not the data was valid and could be stored. My success function in my ajax post doesn't run though. Here is the ajax post and the displaying of the success message:

jQuery.ajax({           
    type:"post",
    dataType:"json",
    url: myAjax.ajaxurl,
    data: {action: 'submit_data', info: info},
    success: function(data) {
        successmessage = 'Data was succesfully captured';
    }
});

$("label#successmessage").text(successmessage);
$(":input").val('');
return false;

No message gets displayed on the label though. I tried setting the successmessage variable to a set value in the code and it displayed fine, so there must be something wrong with my success function, I just can't see what? I also tried setting the error callback like this:

error: function(data) {             
    successmessage = 'Error';
},

But still no message gets displayed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...