Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  147] [ 1]  / answers: 1 / hits: 166684  / 10 Years ago, sun, april 6, 2014, 12:00:00

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.


More From » php

 Answers
3

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;

[#71594] Friday, April 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
acaciac

Total Points: 317
Total Questions: 117
Total Answers: 128

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;