如何使用AJAX调用PHP函数并获取返回值?

时间:2019-04-28 05:11:48

标签: php ajax

我想从我的database.php文件中调用特定的函数,并获取返回的值。在这里,我正在尝试这样做:

js:

function submit_verification_code(){
$.ajax({
url: "database.php",
type: "post",
data: ({
    'code': code_entered,
}),
dataType:"text",
context: this,
success : function(response) {
    console.log('RESPONSE: ' + response);
    //OPTIONAL_FUNCTION_TO_DO_SOMETHING_WITH_THE_RESPONSE(response);
},
error: function(jqXHR,textStatus,errorThrown){
    //OPTIONAL_FUNCTION_TO_DO_SOMETHING_WITH_THE_ERROR(jqXHR);
    console.log(errorThrown);
}
});
}

database.php

 if(isset($_POST['code'])){
    does_code_match($_POST['code']);
 }
 function does_code_match($code){

    connect();
            die('test');
    $sql = 'select * from emailstobeverified where email=';
    $sql .= "'" . $_SESSION['email'] . "'";
    $sql .= ' and verification_code=';
    $sql .= $code;
    $sql .= ';';
    $count = query($sql)->num_rows;

    die(strval($count));
    disconnect();
    echo strval($count);
    exit;
    //Once you've outputted, make sure nothing else happens
 }

does_code_match函数将执行,并且在调用<br />时,控制台日志将显示console.log("RESPONSE" + response)。但我希望它显示$count

的值

编辑:

connect()函数存在问题。如果在致电die('test')之前致电connect(),它将返回一个响应!它在控制台中显示“ hello world”。如果在调用connect()之后直接调用它,它将显示以下内容:

<b>Warning</b>:  Use of undefined constant conn - assumed 'conn' (this will throw an Error in a future version of PHP) in <b>C:\xampp2\htdocs\database.php</b> on line <b>72</b><br />
<br />
<b>Warning</b>:  Use of undefined constant dbhost - assumed 'dbhost' (this will throw an Error in a future version of PHP) in <b>C:\xampp2\htdocs\database.php</b> on line <b>72</b><br />
<br />
<b>Warning</b>:  Use of undefined constant dbuser - assumed 'dbuser' (this will throw an Error in a future version of PHP) in <b>C:\xampp2\htdocs\database.php</b> on line <b>72</b><br />
<br />
<b>Warning</b>:  Use of undefined constant dbpass - assumed 'dbpass' (this will throw an Error in a future version of PHP) in <b>C:\xampp2\htdocs\database.php</b> on line <b>72</b><br />
<br />
<b>Warning</b>:  Use of undefined constant db - assumed 'db' (this will throw an Error in a future version of PHP) in <b>C:\xampp2\htdocs\database.php</b> on line <b>72</b><br />
test

,响应为<br />

连接功能:

 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "";
 $db = "example";
 $conn;
 function connect(){
    $GLOBALS[conn] = new mysqli($GLOBALS[dbhost], $GLOBALS[dbuser], $GLOBALS[dbpass],$GLOBALS[db]) or die("Connect failed: %s\n". $GLOBALS[conn] -> error);
 }

3 个答案:

答案 0 :(得分:0)

将jQuery更改为以下内容:

$.ajax({
    url: "database.php",
    type: "post",
    dataType: "json",
    data: ({
        code: code_entered,
    }),
    context: this,
    success : function(response) {
        console.log(response);
        //OPTIONAL_FUNCTION_TO_DO_SOMETHING_WITH_THE_RESPONSE(response);
    },
    error: function(jqXHR,textStatus,errorThrown){
        console.log(jqXHR);
        //OPTIONAL_FUNCTION_TO_DO_SOMETHING_WITH_THE_ERROR(jqXHR);
    }
});

然后将您的PHP更改为以下内容:

 if(isset($_POST['code'])){
    does_code_match($_POST['code']);
    //no need to call echo again
 }

 function does_code_match($code){
     connect();
    $sql = 'select * from emailstobeverified where email=';
    $sql .= "'" . $_SESSION['email'] . "'";
    $sql .= ' and verification_code=';
    $sql .= $code;
    $sql .= ';';
    error_log('Adding code to be verified with query: ' . $sql);
    $count = query($sql)->num_rows;
    disconnect();
    //I can't speak for the above code, I'm assuming it works.

    error_log("CODE MATCHES? "  . $count);
    error_log(json_encode($count));
    //Not sure why you're doing this, but I assume it's for testing only

    echo json_encode($count);
    exit;
    //Once you've outputted, make sure nothing else happens
 }

您在console.log(response);输出中看到什么样的东西?一旦开始开发环境,您可能会开始发回响应的 array 而不是仅仅返回值。

答案 1 :(得分:0)

echo $count

$count = query($sql)->num_rows;
disconnect();
echo $count;

如果对计数进行编码,则必须在接收端首先对json进行解码。

答案 2 :(得分:0)

引用数组键时,必须 将其括在引号中,然后将函数更改为以下内容:

function connect(){
    $GLOBALS['conn'] = new mysqli($GLOBALS['dbhost'], $GLOBALS['dbuser'], $GLOBALS['dbpass'],$GLOBALS['db']) or die("Connect failed: %s\n". $GLOBALS['conn'] -> error);
 }

此外,通常,这是一种存储全局变量的奇怪方法,您应该研究使用$_ENV数组。

相关问题