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.
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.
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.
$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });
Used Methods :ajaxSuccess() : Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With