简体   繁体   中英

ajax request not posting form data

I have a problem where the values entered (email and password) into my login form are not being parsed to my server php script.

My ajax request:

function signin(){
var loginEmail = gebi("loginEmail").value;
var loginPass = gebi("loginPass").value;

if(loginEmail == "" || loginPass == ""){
    gebi("loginEmail").style.borderColor = "red";
    gebi("loginPass").style.borderColor = "red";
} else {
    gebi("signinBtn").style.display = "none";

            //Declare ajax request variables
    hr = new XMLHttpRequest();
    url = "main.php";
    vars = "email="+loginEmail+"&pass="+loginPass;

    //Open the PHP file that is receiving the request
    hr.open("POST", url, true);

    //Set content type header info for sending url ecncoded variable in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    //Trim string data before sending it
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    //Access the onreadystatechange event for the XMLHttpRequest
    hr.onreadystatechange = function() {
        if (hr.readyState == 4 && hr.status == 200) {
            var responseText = hr.responseText.trim();
            if (responseText != "signin_failed") { 
                console.log(responseText);
            } else {
                console.log(responseText);
                gebi("signinBtn").style.display = "block";
                gebi("loginEmail").style.borderColor = "red";
                gebi("loginPass").style.borderColor = "red";
            }
        }
    }
    //Send the data to the PHP file for processing and wait for responseText
    hr.send(vars);
}
}

and when the php script returns a value using this code:

if (isset($_POST["email"])) {
    echo 'email = '+$_POST["email"];
}

the return value that is logged to the console is '0' even tho there is data present in the forms fields.

What is going wrong?

The problem is in your PHP script. If you are trying to concatenate string in PHP use dot . . + is used to concatenate string in languages like javascript.

echo 'email = ' . $_POST["email"];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM