-2

How to return value for form validation using callback function? This is not working for me..

<form action="loggedin.php" onsubmit="return test(valid)" method="post">

function test(callback) {
    var k = "";
    var httpRequest = new XMLHttpRequest();
    httpRequest.onload = function(){
        k = callback(httpRequest.responseText);
        return k;
    };
    httpRequest.open("POST", "check.php",true);
    var a = document.getElementById("email").value;
    var b = document.getElementById("pwd").value;
    httpRequest.send("email=" + a + "&passwd=" + b);
}

function valid(resp){
    alert(resp);    // resp is correctly defined here
        if(resp == "Correct"){
            return true;
        }
        else{
            return false;
        }
} 

I need to validate the form data using ajax response.. I want to return true or false to form onsubmit method.. Can callback functions return value?

1 Answers1

0

AJAX sends an asynchronous request out to the desired location, meaning it runs independently from the program there after. The purpose of the callback function from AJAX is to apply what is returned to the page when it gets returned, so it cannot return a value to the original form it was called from.

Something you can do to cut down on the php files is combine the check and loggedin files, and either clear the onsubmit and keep it a regular HTML form submission, or continue using ajax.

Either way, an update to your code that will fire the loggedin.php after the first ajax is returned

<form action="loggedin.php" onsubmit="return test(valid)" method="post">

function test(callback) {
    var k = "";
    var httpRequest = new XMLHttpRequest();
    httpRequest.onload = function(){
        k = callback(httpRequest.responseText);
        return k;
    };
    httpRequest.open("POST", "check.php",true);
    var a = document.getElementById("email").value;
    var b = document.getElementById("pwd").value;
    httpRequest.send("email=" + a + "&passwd=" + b);
}

function valid(resp){
    alert(resp);    // resp is correctly defined here
        if(resp == "Correct"){
            var httpRequest = new XMLHttpRequest();
            httpRequest.onload = function(){
                // do what needs to be done to the page, like reload
            }
            httpRequest.open("POST", "loggedin.php", true);

            // this is just using the variables from earlier
            var a = document.getElementById("email").value;
            var b = document.getElementById("pwd").value;
            httpRequest.send("email="+ a +"&passwd="+ b);
        }
        else{
            return false;
        }
}