Parsing PHP response: Uncaught SyntaxError: Unexpected token < - javascript

I'm using AJAX to make a call to a PHP script. The only thing I need to parse from the response is a random ID generated by the script. The problem is that the PHP script throws a number of errors. The errors are actually fine and don't get in the way of the program functionality. The only issue is that when I run
$.parseJSON(response)
I get:
Uncaught SyntaxError: Unexpected token <
Since the PHP response starts with an error:
<br />
<b>Warning</b>:
I'm wondering how to change the PHP or JS such that it can parse out the ID despite the errors.
PHP:
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
...
JS:
function returnReport(response) {
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
I know that the warnings should be resolved, but the warnings are not functionality critical for now and more importantly
1) Even if these warnings are resolved new ones may come up down the line and the JSON should still be properly parsed and
2) In addition to the warnings there are 'notices' that cause the same issue.

Why not deal with and eliminate the warning so that the result from the server is actually JSON?

There are several ways this could be solved (any one of which would work):
1. Fix your warnings. : PHP is saying something for a reason.
2. Turn off error reporting & error display:
At the top of your file place the following
error_reporting(false);
ini_set('display_errors', false);<br/>
3. Use the output buffer:
At the top of your file place
ob_start();
When you have your data array and your ready to echo to browser clear the buffer of all notices warnings etc.
ob_clean();
echo json_encode($returnData);
ob_flush();
4. Set a custom error handler:
set_error_handler("myCustomErrorHandler");
function myCustomErrorHandler($errno, $errstr, $errfile, $errline){
//handle error via log-to-file etc.
return true; //Don't execute PHP internal error handler
}
5. Optionally in JavaScript:
Sanitse your response to be a JSON array:
function returnReport(response) {
response = response.substring(response.indexOf("{") - 1); //pull out all data before the start of the json array
response = response.substring(0, response.lastIndexOf("}") + 1); //pull out all data after the end of the json array
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}

Like everybody else has said, you SHOULD really fix your errors and handle them accordingly.
This is something more to have under circumstances that you will not control and yet want to handle errors accordingly:
<?php
//Change it to 'production' or something like that
//so that you don't send debug data on production
define('ENVIRONMENT', 'testing');
//Set your error handler globally
set_error_handler('handle_error');
function handle_error($errno, $errstr, $errfile, $errline, array $errcontext )
{
//Set your headers to send a different than 200 so you can
//catch it on error on jQuery
header($_SERVER["SERVER_PROTOCOL"].' 500 Internal Server Error');
//Set output as json
header('Content-Type: application/json');
//Create some sort of response object
$response = new stdClass;
$response->message = "Application error details";
//You dont want to give debug details unless you are not on prod
if(ENVIRONMENT == 'testing') {
$severity = get_err_severity($errno);
$response->error_detail = "({$severity}) [{$errfile}#L{$errline}]: {$errstr}";
$response->context_vars = $errcontext;
}
//Return the json encoded error detail and exit script
$json = json_encode($response);
exit($json);
}
function get_err_severity($severity)
{
switch($severity) {
case E_ERROR:
return 'E_ERROR';
case E_WARNING:
return 'E_WARNING';
case E_PARSE:
return 'E_PARSE';
case E_NOTICE:
return 'E_NOTICE';
case E_CORE_ERROR:
return 'E_CORE_ERROR';
case E_CORE_WARNING:
return 'E_CORE_WARNING';
case E_COMPILE_ERROR:
return 'E_COMPILE_ERROR';
case E_COMPILE_WARNING:
return 'E_COMPILE_WARNING';
case E_USER_ERROR:
return 'E_USER_ERROR';
case E_USER_WARNING:
return 'E_USER_WARNING';
case E_USER_NOTICE:
return 'E_USER_NOTICE';
case E_STRICT:
return 'E_STRICT';
case E_RECOVERABLE_ERROR:
return 'E_RECOVERABLE_ERROR';
case E_DEPRECATED:
return 'E_DEPRECATED';
case E_USER_DEPRECATED:
return 'E_USER_DEPRECATED';
}
}
function test_error()
{
$test = array('foo'=>'bar');
$baz = $test['baz'];
echo $baz;
}
test_error();

While this doesn't solve the broader issue of warnings, I used this hack to parse the response:
function returnReport(response) {
var pdfID = parseID(response);
...
}
function parseID(response) {
var responseIndex = response.indexOf('{"id');
var start = responseIndex + 7;
var pdfID = response.slice(start, start + 6);
return pdfID;
}

I know everybody has recommended you fix the errors, I would agree, but if you do not want to then there is another a solution.
If you are getting a number of warnings and expect new warnings could appear, simply disable reporting of warnings and notices:
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

If ob is enabled
ob_end_clean();
ob_start();
echo json_encode($returnData);
Or, in top of your file
error_reporting(0);

I am sure that there would be some mistakes in your PHP code due to that error is coming please check few things:
Make sure that there should not be more than one echo or print in your php code for printing response.
jQuery must be included properly.
And check the other php code in your function/page that should not produce any run time errors/warnings because it will also create same problem.
I am saying this because I have tried your code and it working fine for me you can check that also:
PHP File: myContentPage.php
<?php
$returnData = array();
$returnData['id'] = 123;
echo json_encode($returnData);
?>
HTML File:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
<h1>Demo Example</h1>
<script>
function loadResponse() {
var dataString={};
$.ajax({
url:"myContentPage.php",
type: 'POST',
cache:false,
data: dataString,
beforeSend: function() {},
timeout:10000000,
error: function() { },
success: function(response) {
var parsedResponse = $.parseJSON(response);
pdfID = parsedResponse['id'];
console.log(pdfID);
alert(pdfID);
}
});
}
loadResponse();
</script>
</body>
</html>
And for handling the warnings you can do these this:
To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
or simply add the # sign before the each line of php code on that you think warning can come
Happy Coding!!

Script used in Ajax call just must have perfect constrution, shall not thrown any warnings just by convenience, for production you should have erros disabled, so fix it into development, edit the question with the warning that's phps givin to we help you with directly on the point.

1st alternative:
Solve the problem causing the warning. A good PHP system should never show a PHP Notice, Warning or Error. This may expose some critical information.
2nd alternative:
Just disable error reporting by setting
error_reporting(0);
This will work, but will hide even to you any errors.
3rd alternative:
Set a error handler function that treat the error and show a JSON friendly error message that does not cause any trouble.
Also I recommend you to log this exceptions. It will allow you to debug any system trouble.
My recomendation?
Use 1st and 3rd alternatives together, and be HAPPY!

You can use Try..Catch construct in the javascript function code as shown below.
function returnReport(response) {
try
{
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
catch(err)
{
//Do something with the err
}
}
This will work even if your php code generates debug info in response.

If you want to see the error in JavaScript, you should handle the error on PHP with a "try catch" and the "catch" to do something like "echo json_enconde ($ error);" on this way you can parse from JavaScript.
Example:
try{
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
}catch (Exception $e) {
echo json_encode($e);
}
I hope this helps :)!

Related

JSON.parse not working when I use "success" as a key

I am working on a project where I use a lot of http requests. Most of the time the server will respond as a json with either:
{"error": "Request invalid"}
or
{"success": "Request successful"}
The server side page that returns the response looks like this:
<?php
header('Content-type: application/json');
$data = [];
if (isset($_POST['action']) {
if ($_POST['action'] == 'function_one') {
/* Arbitary Function... */
$data['success'] = 'This works...';
} elseif ($_POST['action'] == 'function_two') {
/* Arbitary Function... */
$data['error'] = 'Example error';
} elseif ($_POST['action'] == 'function_that_is_not_working') {
$data['success'] = 'This unexpectedly does not interpret correctly...';
}
}
$post_data = json_encode($data);
print_r($post_data);
?>
The javascript file does the http request and handles the data similar to:
if (xml_http.readyState == 4 && xml_http.status == 200) {
try {
console.log(JSON.parse(xml_http.responseText));
return JSON.parse(xml_http.responseText);
} catch (e) {
console.log(xml_http.responseText);
return xml_http.responseText;
}
}
So this all works absolutely fine, I have multiple functions all using the same code without an issue. The problem I have is that I have one specific action that does a request, if I set $data['success'] it does not interperet as a JSON object, but a string. If I set the key as anything else, it works fine.
I have tried commenting out the function in case there is some unexpected echo's etc.
The JSON string is a valid JSON string, it's just this one action when using the success key that the JSON.parse doesn't see it as valid JSON so just outputs the string.
Am I missing something obvious? Are there other ways that I could test this?
Edit After a little more playing around I found out there was nothing wrong with the response, nor the JSON.parse.
I had an issue with some of the script after causing an error.
Solution: Always look at the bigger picture, and the subsequent processes.

JSON.parse reads "{\"number\":\"7\"}

Hi I have troubles to generate JSON with json_encode() PHP function.
I have a .php file that is doing only following:
<?php
// include_once for a few files here
$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;
result is following:
{"number":"7"}
Then there is jQuery in another file, retrieving this by following code:
$(document).ready(function e() {
let file_path = 'myJson.php';
let json = $.getJSON(file_path);
console.log(json);
let json_obj = JSON.parse(json);
However $.getJSON reads this string as "{\"number\":\"7\"}, therefore JSON.parse ends with following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I'm sorry, I'm almost 100% sure this is beginner's mistake, however I have failed with my search for correct answer. Anyone having idea what might be the problem?
I have found plenty of articles taking into account input into jason_encode, but right now I have more feeling real trouble is in fact input to jQuery function, however I'm still unable to resolve.
If your web server sends JSON, it's good practice to set the Content-Type accordingly:
header("Content-Type: application/json; charset=utf-8");
On the client, you need to do:
$(document).ready(function() {
$.getJSON('myJson.php', function(response) {
// the response is already parsed by jQuery
alert(response.number);
});
}
$.getJSON() is asynchronous, so you need to pass a handler function to process the response.

fetch in JS is not receiving the appropriate JSON format from json_encode in php

I have a function in JS that fetches data from a php page.
JS code:
fetch("print.php)
.then(function (r) {
return r.json()
})
.then(function (values) {
......
......
})
}
PHP print.php code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$num = $_GET['num'];
$datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);
$result;
foreach ($datas as $index => $data) {
if ($data[0] == $num) {
$result = $data;
}
}
echo json_encode($result);
}
When I run my code, I am getting the error below:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Can anyone help me debug this.
I have tried echo-ing json_encode([$result]); but it didn't work.
I have been trying to fix it for the past 3 hours, but i am hopeless. I have no clue in which direction to go.
UPDATE:
First of all, you have extra closing braces at the end of PHP file if that is not just a typo while pasting in code here.
About the code, well as it is unclear what is in the file myFile.txt, let me show you an example of how it works.
You can follow these steps on your local computer to replicate the example and see it working on your end.
let's say I have this simple PHP filename fetch.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(['Message'=>'you successfully received the response.']);
}
?>
Create an HTML page sample.htmland add the following inside the body tag.
<ul>
<li class="print"></li>
</ul>
Now add the following script in the bottom of HTML page before the </body> tag.
<script type="text/javascript">
$(document).ready(function(){
var resultContainer = document.querySelector('ul li.print');
fetch('fetch.php')
.then(function (response) {
return response.json();
})
.then(function (response) {
resultDiv.innerHTML = response.success;
}).catch(function(err){
resultDiv.innerHTML='There was an error reading the JSON response see here '+err;
});
});
</script>
Since we are fetching a PHP file which is returning json, we return response.json() on the response to give it the proper MIME type so it will be handled properly, then display it in the <li> element. Additionally, i am using the .fail to show the error message if the Promise is rejected
This is as simple as it gets and it should show you the text you successfully received the response. inside the li once the Promise resolves. If it does then it means you need to troubleshoot your PHP file first to see what is in the myFile.txt and what is printed in response when it reaches that last line echo json_encode($result);.
Also, your PHP file states that you are sending the query parameter num to the PHP file whereas your script does not contain any query string parameter with the name num.
secondly what is the $result; doing after the line $datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);, most of your code makes no sense, you should work on your assignment and provide actual sensible code that others can understand and help you out.
Hope that helps you out

Tried to get value from javascript and get error

I have tried to get value from file.js and got error:
file.js: this is how i send it:
$.post("site.php",{
whatever: ec
});
site.php: And this is how I tried to get that value:
<button onclick="justdoit();">Click my</button>
<script>
function justdoit() {
var whatever = "<?php echo $_POST['whatever']?>";
alert(whatever);
}
</script>
Got error in console: Uncaught SyntaxError: Invalid or unexpected token on site.php
Edit2: (on comment)
If you have everything in your one page, you never need $.post to go to server
and get back it at from same requesting page. However if you need some server processing and need to fetch the processed data from server then use $.post i.e. ajax request like i answered in edit1
Edit1: (on comment)Changed answer
your site.php (a file just for server side processing) should contain just
$someparam = echo $_POST['whatever'];
Now you should know about $.post
your client side file index.php (a file which you are opening in browser and which shows you your page) should contain following
<button onclick="justdoit();">Click my</button>
<script>
function justdoit()
{
$.post("site.php",{whatever: 'Hi I am a string'; }).done(function(data){
alert(data);
});
}
</script>
Previous answer
site.php
<?php
$someparam = echo $_POST['whatever'];
?>
//off-course above code should not have any error
If it still gives youy problem then there could be somewhere else => In that code which you have not shared. If it works on removing this code. Then you should edit your question and tell the single line which gives error
try this
<button onclick="justdoit();">Click my</button>
<script>
function justdoit() {
var prize = "<?php echo $_POST['prize'];?>";
alert(prize);
}
</script>
u forgot token behind php :P ';'

JSON unable to accept json_encode() arrays

I am sending a simple array from my PHP file,
//example.php
if(0){
return json_encode(['status'=>false, 'message'=>'Please enter a username']);
}
and in my ajax.js I have everything working, including the XHR object, and event handlers. All is find, except this line.
// ...
var x = JSON.parse(xmlhttp.responseText);
console.log(x);
// ...
But, I am getting the following error.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I don't understand this. All the code is correct. Before using JSON, I used to pass from values from PHP using echo 'ok' and just do if(xmlhttp.responseText) == 'ok and it worked fine, but not with json
Two problems:
you use return which does not print anything to the output wheras echo actually prints text. Try using:
if(0) will always fail, so you will never print anything. You should use if(1) as trivial test. It is possible that you're PHP code can fail, but in that case you better also return an JSON formatted error message.
Something like:
if(test) { //test means you can do the action
//do action
echo json_encode(['return' => 'ok','result' => 'foobar']);
} else {
echo json_encode(['return' => 'error']);
}

Categories