Varun
Varun

Reputation: 159

AJAX call to php not returning value when using post method

PHP Code

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "ngram";

    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $uid =$_REQUEST["username"];
    $sql = 'select * from user_db where username like '.'"'.$uid.'"';
    $result = $conn->query($sql);
    //echo $sql;
    if ($result->num_rows > 0) 
    {
        $conn->close();
        echo (0);
    }
    else 
    {   
        $conn->query("insert into user_db values('".$_REQUEST["name"]."','".$_REQUEST["username"]."','".$_REQUEST["email"]."','".$_REQUEST["pass"]."')");
        $conn->close();
        echo (1);
    } 

?>

function connectDb(formElement)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","signup.php",true);
    xmlhttp.onreadystatechange=function() 
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            myFunction(xmlhttp.responseText);
        }
    }
    xmlhttp.send(new FormData (formElement));
}
function myFunction(response)
{   
    if(response != 1)
    {
        window.open("error.html","_self");
    }
    else
    {
        window.open("login.html","_self");
    }
}

Here javascript is able to send request but php is not returning any value. The values gets added to the database but the page does not changes. Only returned value gets displayed in screen.

Upvotes: 1

Views: 122

Answers (1)

Abasaheb Gaware
Abasaheb Gaware

Reputation: 547

you write return $r but not write a function for access it.write a function or either write echo $r;.

Upvotes: 1

Related Questions