I have a problem with the JSON response I'm returning from my PHP code.
THe PHP on the backend
case 'deleteMySale':
$id = $_GET['product_id'];
$dataNoSer = "you want to delete sale where id= " . $id . "?";
$data = json_encode($dataNoSer, true);
echo $data;
break;
The JavaScript on the front-end that is calling the PHP
$('.deleteProduct').click(function () {
var id = $(this).data('id');
$.getJSON("http://localhost/myProject/deleteMySale?product_id=20", function (data) {
console.log("success");
})
.done(function () {
console.log("second success");
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
})
Response
error
complete
The PHP function is called when I click the button, but I consistently get an error in the console.
Why does jQuery not receive the JSON data? I've read similar problems and their solutions, but I canott see where I'm going wrong.
That's a malformed JSON response. The issue is that you've passed a flat string to the encode function. The encode function does not encode strings, it encodes arrays and objects. Let's make it an array so we can get a real response.
$dataNoSer = array("question" => "you want to delete sale where id= " . $id . "?");
Also, if necessary, modify the headers before sending the response so that you're sure it's an application/json
content-type on the response.
header('Content-Type: application/json');
Access it like so.
console.log(data.question);
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.