Sunday, 13 November 2016

javascript - Post Ajax function to return true or false

use callback


function validateLogin(uid, pass, i, callback) {
var uvalue = uid.value;
var pvalue = pass.value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "validateCheck.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.responseText == "Error")
callback(false);
else if (xmlhttp.responseText == "Yes")
callback(a);
else if (xmlhttp.responseText >= 1 && xmlhttp.responseText <= 5)
callback(true);
else
callback(true);
}
};
xmlhttp.send("uid=" + uvalue + "&pass=" + pvalue);
}

and call your function this way


function validateForm(i){
var uid = document.myform1.username;
var pass = document.myform1.password;
validateLogin(uid, pass, i, function (resp) {
if (resp) {
alert(resp);
}
});
}

using Jquery Deffered Object


function validateLogin(uid, pass, i) {
var result = jQuery.Deferred();
...
if (xmlhttp.responseText == "Error")
result.value = false;
else if (xmlhttp.responseText == "Yes")
result.value = a;
...
xmlhttp.send("uid=" + uvalue + "&pass=" + pvalue);
return result.value;
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...