Sorry, no doubt a really basic question... but I haven't found a possible duplicate.
If at the end of a php script called using $.getJSON() I have a line like this:
return json_encode( $paras_of_interest );
... everything works fine ... until there is some php output (inadvertently by an echo command, or perhaps due to a warning or error being generated by the php code)... this then completely disables/stops/messes up the return of the JSON object. What's the best way of dealing with this situation? How can one find out what code was output (i.e. where does it "go"?) ... and is there a way of configuring where output goes in this situation?
later apologies to Dezigo and Salman A: all 3 were excellent answers but I had to choose one
Make sure there will be no output before this line:
display_errors
directive to 0 and/or use a custom error handlerob_start
and ob_get_clean
)If you captured any unexpected output/errors, don't send it, but add an error parameter to your JSON response:
echo json_encode(array(
'result' => /* your original result here */,
'error' => /* error message here */
);
Your response should always be structured like this, error being null or false if no error occurred. On the client side you will evaluate error first, then result. Additionally you could send a HTTP 500 status code if an error occurred, then you should be able to use the error callback function of JQuery to handle errors:
$statusCode = $error ? 500 : 200;
header('content-type: application/json', true, $statusCode);
You can save your output buffer (end clean it)
<?php
ob_start();
echo "Hello ";
$out1 = ob_get_contents();
ob_end_clean();
var_dump($out1);
?>
How can one find out what code was output (i.e. where does it "go"?)
Open your browser's developer tools, then open the page and monitor the network tab. You should find all XHR logged there. This includes broken JSON responses.
Also, JavaScript libraries do not process broken JSON. jQuery for example will ignore such response and fire the error handler (if configured). Depending on the JavaScript library, the success/error handlers might give you access to the raw responseText
.