PHP function not returning any data to JQuery ajax method

。_饼干妹妹 提交于 2019-12-13 07:41:46

问题


I am using jquery's ajax method to post some data to the server and get back the response. Though the server side php code is returning a json encoded string/array, the response is coming back as null.

Could someone point out the mistake that I am making. Below if my jquery ajax method using which I am hitting the postData.php page.

        $.ajax({
            url:'postData.php',
            type:'POST',
            data:data,
            dataType: "json",
            success: function(response){
                console.log(response);
            }
        });

The content in postData.php is pretty straight forward as I am still developing it.

    $data = array();
//inside postData.php
    $data['test']=1;
    return json_encode($data);

It should return a json string, but it is returning null. I also tried echoing a string just after $data array declaration, it does echo it in the firebug, but the response is when I do a console.log on the success callback, it comes back as null.


回答1:


Is that all that is in postData.php? You need to write it out to the buffer (echo json_encode($data);) at some point.




回答2:


For getting the result back in your ajax function, you must echo it, not return, like:

$data = array();
$data['test']=1;
echo json_encode($data);



回答3:


Like morgar pointed it out, you should echo the data back and not use return.

$data = array();
$data['test']=1;
echo json_encode($data); //echo instead of return

At the same time, in your ajax on success function, you should access the response like an array.

**Incorrect**
console.log(response); //--> would return an error

**Should Be**
console.log(response[0]); //--> read the returned first array element


来源:https://stackoverflow.com/questions/6091851/php-function-not-returning-any-data-to-jquery-ajax-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!