JQuery can't parse properly formed JSON data sent from PHP - php

I'm trying to use JQuery to send AJAX data from a web browser to a PHP script in a web server and then getting a response back from the server. The request is received and processed correctly by the PHP script, but there seems to be something in the server's response that JQuery can't parse. Using Firefox, I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
And using Chromium I get something like this:
SyntaxError: Unexpected token in JSON at position 0
I'm not sure if that's a blank space or some other character, as Chromium won't let me copy the alert text.
Anyway, here's the PHP script that resides in the server, processes the AJAX request and generates the response. I previously used json_encode() to return dynamically generated data, but right now I'm using a static string just to try to make it work:
<?php
echo '[{"id":1,"label":"sinetiqueta","value":"nada","url":"nadicaDeUrl"}]';
?>
And here's my JQuery AJAX code:
$.ajax({
url: 'www.siteurl.com/server_script.php',
method: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
dataFilter: function ( recieved_data, data_type ) {
//I added this function just to check the JSON data before it gets parsed by JQuery
alert('DATAFILTER --- recieved_data: ' + recieved_data + ' * data_type: ' + data_type);
var filtered_data = recieved_data;
return (filtered_data);
},
success: function (json) {
alert('SUCCESS --- json: ' + json);
response($.map(json, function () {
return json;
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error - ' + textStatus + ': ' + errorThrown + ' * Server Response:_' + XMLHttpRequest.responseText + '_')
}
});
So the PHP script gets JQuery's message without a problem, returns a static string of (as far as I can tell) properly formed JSON that gets back to the browser without a problem (that alert command in the dataFilter function shows the same string that PHP sends back) but JQuery can't parse it.
The funny thing is: If I insert that very same static string directly in the dataFilter function instead of passing it from the PHP script, JQuery parses it properly and everything else works without a hitch!
dataFilter: function ( recieved_data, data_type ) {
alert('DATAFILTER --- recieved_data: ' + recieved_data + ' * data_type: ' + data_type);
/*var filtered_data = recieved_data;*/
//instead of using the data I got from PHP, I use a string literal value
var filtered_data = '[{"id":1,"label":"sinetiqueta","value":"nada","url":"nadicaDeUrl"}]';
return (filtered_data);
},
This works, but it obviously doesn't suit my needs, as I need to use the JSON data that gets sent back from the server. Right now, I'm using the very same JSON string, only JQuery can't parse when it gets it from PHP, even when it seems to be receive it complete and properly encoded, as far as I can tell.
I'm at a loss to figure out what may be happening with the data that I get from PHP. When displayed with the alert command in the dataFilter() function, it looks perfectly ok! What am I missing here? Any help will be greatly appreciated. Thanks in advance!

Thanks to user JAAulde, I found the cause of my problems. The server side PHP script returned properly formatted JSON data, and checking it with the browser's network inspector and in the JQuery script after reception, I couldn't see any extraneous characters that could stop the parser from processing it.
The cause of my problems was a little configuration file I included in the PHP script, that some text editor had codified as UTF8 with BOM (byte order mark), the mere inclusion of which, apparently produces some kind of undisplayable output that gets added to the beginning of the data and messes JSON parsing in the client script. Be careful with the BOM in your UTF-8 encoded files when you need to send data for another script to process, kids!
Many thanks to users Nitin and charlietfl for their helpful and reasonable answers, too!

Related

SyntaxError: JSON.parse?

So i'm making a simple web application to test out Ajax and for some reason i'm getting JSON.parse error although i'm returning my results as JSON using json_encode($results).
The application lets me pick a client and it pulls out that client's orders
JS file :
function getOrders(clientId) {
$.ajax(
{
type: 'POST',
url: "AjaxRequests.php",
data : {
action: 'showOrders',
clientId: clientId
},
dataType : 'json',
success: function(results){
alert(results);
},
error: function(request, status, error){
console.log(clientId);
console.log(request.responseText);
console.log('error : ' + error);
console.log('status' + status);
},
}
)
};
AjaxRequests.php file
<?php
header('Content-Type: application/json; charset=UTF-8');
require_once './GestionClients.php';
if (isset($_POST['action'])) {
if ($_POST['action'] == 'showOrders') {
$clientId = $_POST['clientId'];
$gc = new GestionClients();
$results = $gc->getCmdsByClient($clientId);
echo json_encode($results);
}
}
?>
and this is the results i get in the console after i pick a client (first client in this example with an ID = 1 in the DB) from the selection list:
1 script.js:16:25
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}] script.js:17:25
error : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js:18:25
statusparsererror
I tried putting that JSON result on an online JSON parser and it looks just fine.
Thank you for your time.
As I so often advise, this problem could have been avoided, or at least quickly identified, by breaking the problem down: you were trying to debug the JS, but that wasn't the part that was broken.
In this case, you have two key pieces:
A PHP script that, when requested with the right parameters, outputs something. You can open this in your browser, and see it for yourself.
Some JS code which requests that PHP script, and parses its content as JSON. You can test this with a PHP script that just echoes {"hello": "world"}, or even a text file uploaded to your server.
Once you know that the JS code works if the JSON is valid, you can basically ignore #2, and look for problems in #1.
If you open the PHP script you wrote in a browser, it will show:
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]
Now, we know that the JS is going to try to parse this as JSON, so we can do a quick test in our browser's console:
JSON.parse('Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');
We get a syntax error! Well, of course we do: that "Connection successfull!" wasn't supposed to be part of the JSON.
So we dig into the PHP code, work out where that's coming from, and stop it happening. Now we run the PHP again, and it looks like this:
[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]
Now we can do our JS test again:
JSON.parse('[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');
Now the error's gone away, and it gives us an array. While we're here, we can look at the structure of the array in the console and make sure it looks right.
Only now do we go back and run the original AJAX call, and see if it's all working. If it's not, we look for other steps we can break out, and repeat the process.

Cross Origin Resource Sharing using AJAX methods and PHP

I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.
here is my calling method:
$.ajax({
type: "GET",
url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
datatype: "jsonp",
data: dataInput,
jsonp:'jsoncallback',
crossDomain:true,
success: function(data)
{
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found")
{
var paginate=setPager(0);
$("#pgn").html(paginate);
}
},
error: function() {
$("#rtrn").html("Data not retrieved successfully");
}
});
Here is my PHP code snippet:
<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>
I am trying to accomplish this by using JSONP. Should I have any headers?
Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data
The CORS way
You need to put the appropriate header in your php script and output only the JSON:
<?php
header('Access-Control-Allow-Origin: *');
// rest of the code
// output JSON only
echo $rsltjson;
?>
Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.
Mozilla has plenty to read about it
The JSONP way
Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.
JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:
<script>
function myDataFunc(data) {
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found") {
var paginate=setPager(0);
$("#pgn").html(paginate);
}
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>
The JSONP url will return something that looks like this:
myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});
Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.
Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.
Finally, you use jQuery.parseJSON(), which produces this error from your code:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The reason can be found in the jQuery docs:
jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.
Your php script feeds your callback with a JSON object
{"a":"fhsfg","b":"qfdgers","c":"difgij"}
rather than a string representing a JSON object
'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'
Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:
echo $_GET['jsoncallback']."('".$rsltjson."');";
Obviously if your JSON data contains single quotes, you will have to escape them.

Error - Passing an array from PhP to jQuery using JSON

I apologise, since I know this has been asked before, more than once.
I've been struggling with this little bugger for quite a few hours now, and I cannot seem to find my mistake.
The problem is simple - I have a PhP array which I want to pass over, from the server side to the client side, using jQuery AJAX with the data in JSON format.
The code for my Client-side Ajax call is
$.ajax({
url: 'php/test/pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
And the code for my server-side pass_array.php script is
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name"=>"Johnny")); //Build JSON object from the array
As you can see, this is pretty basic, but it's not working. On the client side, the AJAX response is never received.
When I check the browser console log, I get
Error: SyntaxError: Unexpected token parsererror [object Object]
What the devil am I doing wrong?
All my files are in UTF-8 encoding. This also works if I remove the dataType: 'json' and the heading() on the PhP side. In that case, I get the following string:
{"Name":"Johnny"}
UPDATE
Commenting out the header() code in the PhP side makes the console show the following error:
Uncaught SyntaxError: Unexpected token o
How can there by syntax errors? I create a PhP array and encode it using json_encode.
UPDATE #2
Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
It looks like including that db_io.php file added a Byte Order Mark character (\ufeff) to the JSON string.
The complete string being sent to the Client side was
\ufeff{"Name":"Johnny"}
It seems this db_io.php file was encoded with BOM. Changing its encoding (using notepad++) fixed that.
Amazing how a simple include instruction can mess up an AJAX call.
Try checking out if your ajax function is being triggered and if any request is even being sent to your php code. For example maybe there is some syntax in your ajax script or you have not provided the url of your php file.
Make sure your PHP script starts with <?php
Update 1:
I made two files on my localhost - index.html
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: 'pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
</script>
</body>
</html>
pass_array.php
<?php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name" => "Johnny"));
The result of the AJAX call in the console is:
Object {Name: "Johnny"}
Make sure the url is correctly accessing the right php file.
You can check any "XHR" requests (AJAX) in Chrome's inspector under the "Network" tab.
Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
I still don't understand tho - I'm not using that file in any way - other than include it. Why should it interfere?
Thanks for the ideas. Peace!
Error: SyntaxError: Unexpected token
U have problems with 'token' variable. Mb u use CMS or Framework?
Try
console.log(arguments);
And also, u can try send
header('Content-type: application/json');

javascript unexpected token < , is there any way I can escape the errors(or atleast skip those useless characters)

In php, I have an array like this :
$arr['a'] = "some big data so may contain some chars that bring us headache"
$arr['b'] = "some big data same as above"
$data = json_encode($arr)
echo $data
My javascript code containing a jquery ajax call, $.ajax . It calls the file containing the above php code so, on success, the json_encoded(by php) is returned to my javascript variable . In my javascript file, I am doing like this :
jsdata = JSON.parse(data); //Getting error here
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp'
}).done(function(d) {
print("success");
});
From the above code, in the line jsdata = JSON.parse(data), I am getting errors something like
Error : UNEXPECTED TOKEN <
As the data contains lot of different content, its normal to get those errors . They need to be escaped properly . Can anyone tell me how to do that correctly . Whatever the data may be , I shouldnot get error regarding the data .
Thanks
Well, a couple of things you should probably know jsdata = JSON.parse(data); tries to parse whatever json string you assigned to data, and return it as a JS object. I think you want to do the opposite: jsdata = JSON.stringify(data);
Besides, since you are using jQuery, you could just leave that line out: jQuery will convert the data to the appropriate format before sending the request anyway, no need to bother with parsing or stringify-ing it yourself.
Yeah you forgot the ; at the end of two lines, so PHP is outputing an error, which is no JSON-compliant.
Always do this :
Catch errors and output them in a way that is understable by your application (a 5xx status can be enough)
Next time you have this, use Chrome Developper tool or Firebug to see what your app really returns
Also, you're outputing json, not jsonp which is different and what your app expects
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp',
success: function(d) {
print("success");
}
})
try it this way
This is much more simple than it might seem.
Call urlencode($arr['a']) and urlencode($arr['b']) (for each data value in $arr) before encoding the JSON and echoing $data to the JavaScript. This will URL-Encode the data in the array so that it will cause you no problems.
When you are done parsing the JSON, you will have to call the JavaScript function unescape(string) on each of the large data values. This will return them to the way they originally were. It's a sort of superhero-team-up of PHP and JavaScript!

Jquery AJAX PHP data return

I'm using the ajax function in Jquery to return some values from a PHP script with the json_encode function. The returned data seems to be full of slashes, quotes and \r\n. I understand that there must be something going wrong with stripslashes or magic_quotes (which is turned on) but can't seem to manage to get a clean output
Make sure on your ajax call from jQuery, you tell it to expect a json response. It sounds like you're returning plaintext and trying to parse it manually.
$.ajax({
url: "myscript.php",
dataType: "json",
success: function(data){
console.log( data ); //this line only works with chrome (stock) or FireFox (with FireBug plugin)
}
});
That code will echo in your console (if you don't have chrome or FF with FireBug, go get one of them :P) the json encoded output. Remember when you output from PHP, all you should be doing is this:
header('Content-type: application/json');
echo json_encode( $myAssociativeArrayOfData );
exit; //make sure nothing else happens to output something
You don't need to use any special formatting or slashes. Just make sure the json code gets output as json code with the proper headers and jQuery's ajax function should convert it for you. The result will be the data variable in the success function being your json object (php array). So if you pass in an array like this: array('foo'=>'bar') in PHP, then in your success function in jquery, you could type: alert( data.foo ); and get a dialog box that says "bar".

Categories