douchun1859 2019-04-28 05:11
浏览 665
已采纳

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

I want to call a specific function from my database.php file, and get the returned value. Here I am trying to do this:

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 function executes, and the console log prints <br /> when console.log("RESPONSE" + response) is called. But I want it to print the value of $count

EDIT:

There is a problem with connect() function. If I call die('test') just before calling connect(), it returns a response! It says "hello world" in the console. If I call it directly AFTER calling connect(), it prints this:

<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

and the response is <br />

Connect function:

 $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
". $GLOBALS[conn] -> error);
 }
  • 写回答

3条回答 默认 最新

  • dongshijiao2363 2019-04-28 15:32
    关注

    When referencing array keys, you must enclose them in quotes, change your function to the following:

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

    Also, in general, this is a strange way of storing global variables, you should look into using the $_ENV array instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • douzi4724 2019-04-28 05:19
    关注

    Change your jQuery to the following:

    $.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);
        }
    });
    

    Then change your PHP to the following:

     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
     }
    

    What kind of stuff do you see in your console.log(response); output? Once you start developing your environment, you will probably start to send back an array of responses instead of just a value.

    评论
  • doqrjrc95405 2019-04-28 06:12
    关注

    just echo $count

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

    If you encode the count, on the receiving end, you will have to decode the json first.

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 arcgis制做交通拥堵时变图
  • ¥15 AD20 PCB板步线 这个要怎么步啊
  • ¥50 关于《奇迹世界》1.5版本,数据修改
  • ¥15 请问这个问题如何解决(关键词-File)
  • ¥50 visual studio 2022和EasyX图形化界面
  • ¥15 找一下报错原因,纠正一下
  • ¥50 Cox回归模型Nomogram图制作报错
  • ¥20 SQL如何查询多级用户的数据
  • ¥15 给车牌识别代码加一个识别轮廓长宽比的代码
  • ¥30 商品价格预测的transformer模型优化