简体   繁体   中英

Echo'ing php as “return value” to ajax call

My jquery code:

    var value = $.ajax({
            type: "POST",
            url: "to_submit.php",
            data: $('#submit').serialize(),
            cache: false,
            async: true
        }).success(function(response){
            console.log(response);
            console.log("data received");
            console.log(response.data);
            $("#appended").append(response);});
        }).error(function() {});
        });

and PHP

include("../header.php");
$to_return = "test";
echo "\ndata: " . json_encode($to_return);
flush();

How the console.logs in the javascript part behaves:

first console.log: (a lot of code information (head, body, etc) related to my website header!)

still first console.log: data: "test"

console.log("data received");

second console.log: undefined

So, data is being recognized as undefined and a lot of code is being flushed, and I can't figure out why...

Two things: first, you shouldn't need to use flush() - simply echo your data and end your script.

Second, the results of your echo statement: data: ["insert your data here"] is not valid JSON and you're not going to be able to decode it on the client.

Change

echo "\ndata: " . json_encode($to_return); 

To

echo json_encode($to_return); 

Cause this string can't be parsed properly by js decoding function (it is not a valid json string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM