Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax success function

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.

like image 802
Mikey Avatar asked Apr 06 '14 10:04

Mikey


People also ask

What is AJAX success function?

What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.

How can I get success response in AJAX?

In most cases, you will need to specify the success and error callbacks. The success callback will be called after the successful completion of the AJAX call. The response returned by the server will be passed along to the success callback.

How check AJAX request is successful jQuery?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

How do you attach a function to be executed whenever AJAX request completes successfully using jQuery?

Used Methods :ajaxSuccess() : Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.


1 Answers

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;
like image 115
Serge K. Avatar answered Sep 29 '22 09:09

Serge K.