I have an AJAX Request, that essentially queries a database then posts the data back to the JS, however I can't print individual bits of data.
My code is as follows:
$.ajax({
type: 'POST',
url: '_process/offerrespres.php',
dataType: 'json',
data: {
msgid: msgid,
usrid: usrid
},
success: function(){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}
});
The PHP:
<?php
include_once 'connect.php';
if ($_POST) {
$msgid = mysql_escape_string($_POST['msgid']);
$usrid = mysql_escape_string($_POST['usrid']);
$getmsgq = mysql_query("SELECT * FROM booking_requests WHERE receiver_id = '$usrid' AND msg_id = '$msgid'");
$getmsg_info = mysql_fetch_array($getmsgq);
$data['success'] = true;
$data['date_sent'] = $getmsg_info['date_sent'];
$data['pro_name'] = $getmsg_info['pro_name'];
$data['accept_decline'] = $getmsg_info['accept_decline'];
}
header("Content-Type: application/json", true);
echo json_encode($data);
mysql_close();
?>
As you can see I've tried this:
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
the error in the console says "data not defined". The output from the PHP file is correct and how it should be, I just can't print one single piece of data.
Your callback function isn't accepting the return data as an argument
The line that reads success: function(){
should be success: function(data){
Also, the true
isn't needed in your call to header("Content-Type: application/json", true);
. The default action of this function is to replace headers, so true
is already implied. That argument is only necessary if you don't want to replace the previous Content-Type
. Makes no difference to your code, just a tip.
You didn't specify the data variable in the success function. It should be:
success: function(data){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}