trouble706 trouble706 - 4 months ago 7x
Javascript Question

Why is my JSON not being returned from PHP correctly?

I am making an Ajax call from JS file to a PHP function in another file. Though the Ajax call is successful, in that it saves the record, I am not getting back the correct data for processing. Instead I get the html from the page. I need to be able to check the status so that I can then move forward if successful or notify the user if there was any kind of error that didn't save the record. Here is my JS code.

type: "POST",
url: "utils.php?do=saveTick",
data: {'dtData': JSON.stringify(sendData)},
success: function (data) {
if (data.status != "SUCCESS") {
$("#btnPrint").attr('disabled', false);
return false;
} else {
}, 'json'

And after processing through PHP, this is where I am trying to return my JSON so I can check it. In I try/catch I have this

try {
$data = json_decode($_REQUEST['dtData']);
$values = $data[0];
$ordNbr = $values->ordnbr;
$saveTick = Do something and save the ticket
// if ($saveTick->status === "SUCCESS") {
$this->getSalesData($values, $ordNbr);
echo json_encode($saveTick);

} catch (Exception $e) {
$saveTick = array('status' => 'FAILED');
echo json_encode($saveTick);

And this is what is returned to the console from my console.log above



TR.main_header {
TR.main_footer {
div.error {
color: red;
font-weight: bold;

<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr class="main_header">
<td align="left" width="25%"></td>
<td align="right" width="25%">Tuesday May 31,2016</td>

[{"shipdate":"2016-05-31","ordnbr":"BR549","custid":"CUST","deltcktno":"D333423","siteid":"Some Site","dttype":"REG","IsExport":true,"slsperid":"","slsname":"Some Sales","slsemail":""}]{"status":"SUCCESS","message":"Successfully called","data":null,"count":0}


Get rid of the auto_prepend_file and auto_append_file settings in php.ini. These would be safe if they just defined variables and functions, but if they output HTML they'll interfere with scripts that are supposed to return other types of output, such as JSON or XML.

You'll have to recode all your other scripts to require their headers and footers explicitly instead of relying on this PHP setting.