jquery to php (wait for php script until result/finish)
I am executing a php call from javascript(jQuery), php sript is sending result back. The problem is that these php scripts are taking some time (milliseconds), and java script is not waiting for them to finish, thus variables are开发者_StackOverflow not getting initialized with correct values. The code is simple:
$.get("php/validation.php",{'email':email},function(data){
// valid_email now contains true/false
alert(data);
if(data=="true"){
var valid_email = true;}
});
The "alert" is printing true but value of valid_mail is recognized as "false" in the code below. Is there any other better way to call php scripts and wait for until they are not finished?
Prashant
That function(data)
is called asynchronously; it waits until after the PHP script has finished. Any code below that $.get()
chunk, however, is executed immediately. If you want the code below to wait as well, you have to move it up into that function, or put it into a new function and just call it.
You must react to the response when it is there, not sooner. Of course JavaScript keeps running and does not wait for the response (otherwise the user would notice the thread blocking during the wait). Either you solve it by using a separate callback function, like this:
function checkValidity(email, callback) {
$.get("php/validation.php",{'email':email},function(data){
// execute callback with true or false as the argument
callback(data=="true");
}
}
function showValidity(valid) {
$("#someId").css("color", valid ? "green" : "red");
// probably more
}
checkValidity($("#someField").text(), showValidity);
or by acting right in the success callback of $.get()
itself:
function checkValidity(email, callback) {
$.get("php/validation.php",{'email':email},function(data){
$("#someId").css("color", (data=="true") ? "green" : "red");
}
}
You should use a callback to a function to handle the result, you can't use it directly after running the $.get.
See: How can I return a value from an AJAX request?
Thanks for the tip. It has solved most of the problem but one is still giving same problem. The function below is sending the mail but still "false" condition is getting executed.
$.post("php/send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
}
});
精彩评论