I would like to know how to retrieve a return true or return false from a PHP script using jQuery AJAX. This is my current ajax call code which works just fine aside from always directing to the profile page of the entered username even if the login wasn't actually successful...
$("#signInForm").submit(function() {
$(document).ajaxStart(function() {
$("#loading" ).show();
});
$.ajax({
url: "/ajax/signIn.php", // Action of the form
data: $("#signInForm").serialize(), // Send forms data to server
dataType: "JSON", // Take response as JSON
type : "POST", // Send form by post or get
complete: function(result) {
$(document).ajaxStop(function() {
$("#loading" ).hide();
});
$("#ajaxResponse").html(result.responseText);
$("#ajaxResponse").slideDown("slow");
var username = $("#usernameSignIn").val();
setTimeout(function() {
window.location.href = "/profile.php?username=" + username;
}, 3000);
}
});
return false; // Default submit return false
});
complete
fires when the call is complete --- reguardless of the result - I suppose as long as it takes the response
- it's perfectly acceptable.
Otherwise, you may want to use success
instead, but in this case, what you need to do is determine what to do based on that response
ie:
if(response === true){ //proceed }else{ alert("error!"); }
You have to put that logic in, yourself -- as complete
& success
are only concerned with the actual transmission of the data, and not the content of it.
Thus, in your code:
$("#signInForm").submit(function() {
$(document).ajaxStart(function() {
$("#loading" ).show();
});
$.ajax({
url: "/ajax/signIn.php", // Action of the form
data: $("#signInForm").serialize(), // Send forms data to server
dataType: "JSON", // Take response as JSON
type : "POST", // Send form by post or get
complete: function(result) {
$(document).ajaxStop(function() {
$("#loading" ).hide();
});
$("#ajaxResponse").html(result.responseText);
$("#ajaxResponse").slideDown("slow");
if(result.success === true){
var username = $("#usernameSignIn").val();
setTimeout(function() {
window.location.href = "/profile.php?username=" + username;
}, 3000);}
else { //the result.responseText is probably suitable here, eh? so you could just:
$("#ajaxResponse").slideUp(5000); }
}
});
return false; // Default submit return false
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.