19

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.

Mikey
  • 345
  • 5
  • 9
  • 15
  • 1
    possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Apr 06 '14 at 10:21
  • "My success function in my ajax post doesn't run though" So check in your network tab for error – A. Wolff Apr 06 '14 at 10:21
  • Checked the network tab, it says the post ran OK – Mikey Apr 06 '14 at 10:32

2 Answers2

30

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;
Serge K.
  • 5,303
  • 1
  • 20
  • 27
4

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });
zhao
  • 1,094
  • 9
  • 9