2016-10-25 31 views
0

PHP代碼AJAX調用PHP中使用POST方法時

<?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"); 
    } 
} 

這裏JavaScript是能夠發送請求,但PHP是不返回任何值不返回值。值會被添加到數據庫中,但頁面不會更改。只有返回值顯示在屏幕上。

+1

您在JavaScript中使用了「xmlhttp」和「xhttp」。我相信你需要到處使用「xmlhttp」。 –

回答

0

你寫的return $r但是不寫一個函數來訪問它。寫一個函數或者寫echo $r;

+0

我嘗試過'echo $ r',但它只是將它打印在新頁面中。 – Varun

+0

在一個函數中寫入所有的數據庫代碼。 –