SyntaxError: JSON.parse? - php

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.

Related

Remote serve not sending response to ajax post

I am using WAMP 3.0.8 PHP 7.0.10 Apache 2.4.23 and trying to build my first JSON API.
The ajax call does send the data to the server. I can see it stored in the text file.
My AJAX looks like this.
$(document).ready(function(){
$('#order').click(function(){
var send = {"name":"Jo Moe", "age":39, "city":"Meridian"};
var prescription = JSON.stringify(send);
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'https://apa.superserver.com/receive.php',
data: {"scripts": prescription},
success: function(data){
console.log(data);
alert(data);
$('#success').html('<p>Finished</p>');
}
});
});
});
Server side looks like this:
if(isset($_POST["scripts"]) && !empty($_POST["scripts"])){
$sent = filter_input(INPUT_POST, "scripts", FILTER_SANITIZE_SPECIAL_CHARS);
$scripts = html_entity_decode($sent);
file_put_contents("jsonScript.txt", $scripts);
$finish = "Message Received!";
echo json_encode($finish);
}
Now this all worked when it was on the same server. When I separated the receive.php and put it on the remote server. It no longer shows the response.
Thanks!
UPDATE:
Get json ajax php form to work remotely
The link above fixed my issue and gave me more information in the console to figure out what was happening. (I should not have been given a -1) The problem with searching the index here that if you don't use the exact terms in the post it is nearly impossible to find. (my two cents)
Adding the error function and changing from "data" to "response" made the difference along with the xhr. I can see everything.
This my return to the console:
Object {readyState: 4, responseText: "↵↵hello!"Message Received!"", status: 200, statusText: "OK"}
ajax.php:56 parsererror
ajax.php:57 SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at parseJSON (jquery-1.6.4.min.js:2)
at b$ (jquery-1.6.4.min.js:2)
at w (jquery-1.6.4.min.js:4)
at XMLHttpRequest.d (jquery-1.6.4.min.js:4)
As you can see the response text is what the server is sending back.
I did have to modify my httpd.conf to turn on the mod_headers.c and added an .htaccess .
UPDATE 2:
Figured out what was causing the parse error. I had a print "hello!" line in my server side file that I had there for other troubleshooting. Once I removed it and had only the posted server side code. Everything is peachy now. Onward!!
If I understand correctly You want to make ajax request to another domain. It's blocked because of Same origin policy. To achieve your goal You can implement JSONP

JQuery can't parse properly formed JSON data sent from 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!

How to diagnose AJAX error which is not throwing any error messages?

I have following part of ajax code:
$(document).ready(function(){
$("form input#dodaj").click(function(){
var s = $("form input#zad").val();
var str = "<li>"+s+"</li>";
$.ajax( {
type: "GET",
url: "http://lesni.org/kss/dodaj_zadanie.php",
data: {
pid: ($(this).attr('alt')),
zad: encodeURI(s)},
error: function( err ){ alert(err); }
}
).done(function(){
$("ul#zadania").append(str);
$("form input#zad").val(" ");
});
});
});
Note: The page loading the code above is from a URL like http://lesni.org/some/page, and so the Same Origin Policy isn't an issue.
But it does not seem to work and I don't know why.
The PHP file it is calling is correct. When I type manually in browser:
http://lesni.org/kss/dodaj_zadanie.php?pid=1&zad=abc
it works correctly (adds record to database). But the ajax code is not working. And it throws no error or I don't know if it throws any error...
So the question is: how can I diagnose this part of AJAX code to know what's wrong. I also tried the POST version, with no effect.
You're specifying data like this:
data: {
pid: ($(this).attr('alt')),
zad: encodeURI(s)
}
When you pass an object to jQuery via data, you don't need (or want) to encode it. (You only do that with a string.) jQuery does that for you. (If you did want to encode it, you'd want encodeURIComponent, not encodeURI). So you'll end up with entities that are double-encoded, and thus won't work corerctly.
That should be:
data: {
pid: ($(this).attr('alt')),
zad: s
}
(You also don't need the parens around the value of the pid, but they're harmless so I've left them.)
But answering the question
How to diagnose AJAX error which is not throwing any error messages?
...you do that by
Looking at the Network tab in any decent browser's development tools, which shows you exactly what it sent to the server and what it got back.
Using server-side debugging (either proper debugging, or by dumping out things to a log) to look at exactly what got received by the server.
Looking at server-side logs to ensure that the correct resource got requested.
...and so on.

Running a PHP file using AJAX and sending parameters

I am trying to edit a file on my server when a user clicks a button on my web page. I generate a table of buttons using php. STRING1, STRING2 and BOOL are variables I pass to my function. The editPlist() function I made is called and the test alert() shows. The problem is that the php file is to run. I am not getting any errors either. I can't seem to figure out what is wrong.
Sample HTML button:
1 : Round 1
The button click runs this script: (the PHP in the url line generates the address of the file I want to run.)
<script type='text/javascript'>
function editPlist(stage, dance, oldValue)
{
alert('test ' + stage + dance + oldValue);
$.ajax({
type: "POST",
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>,
data: {"var1" : stage , "var2" : dance , "var3" : oldValue},
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
In the external php file PlistEditorFunction.php, I try to log a fake error and load the variables, but the error never shows. this is the beginning of the php file:
$msg = 'test error message';
error_log('['.date("F j, Y, g:i a e O").']'.$msg."<br /> \n", 3, $phperrorPath);
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$stage = trim($_POST['var1']);
$dance = trim($_POST['var2'])
$oldValue = trim($_POST['var3']);
}
I know that the php script will only be run if the domain name matches file where the ajax is being run from. The two files are next to each other so I know that this isn't the problem.
What can I do to fix this?
change this line
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>
to
url: 'PlistEditorFunction.php'
and see if it works
Several things look strange.
Please verify that the url you call is in fact what you think it is. In order to do that, use a console / inspector. I recommend firebug. When you make the ajax call, it will display the url of the page you're requesting with ajax.
If it is correct, then your url param is not the problem. Next I would look at the php file itself. Try throwing an echo statement in the php file so that way your ajax response can verify that its being run. whatever you echo in the file PlistEditorFunction.php will be the response param in the success function
success: function( response ) {
console.log(response); //should be the echo'd statement of PlistEditorFunction.php
}
After mwotton's comment, I figured out that ajax was undefined. jQuery was imported, so that wan't the problem. I found the answer was I had to change $.ajax to jquery.ajax.
Some hosts don't use "$" to denote jQuery. My web host uses "jquery" instead.

JSON error(s) with php backend

I've never worked with JSON before and it's not going well...
I have a PHP script that returns a JSON array(is that the correct term?)
The script returns:
{"items":1000,"mitems":0,"donations":0,"total":1000}
NOTE: The script also sets the Content-Type to application/json
Here is my front-end javascript to handle that response:
function ajax(){
$.ajax({
url: '../ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function( data ){
// data.responseText is what you want to display, that's your error.
alert(data.responseText);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
When that function is called I get an alert with the following message:
{"items":1000,"mitems":0,"donations":0,"total":1000}
If everything was successful, I should get an alert that says success, right?
Can someone please tell me what is going on here?
Thank you!
This is the least documented thing in jquery what you need to do is alert the actual error in order to debug it. so do the following:
function my_ajax(){
$.ajax({
url: '/ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function(jqXHR, textStatus, errorThrown){
// data.responseText is what you want to display, that's your error.
alert(jqXHR+","+textStatus+","+errorThrown);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
So two things I've done:
Change the name of the function (ajax is kinda a bad name :S) and improved the error reporting.
You should be getting the alert "success" yes. So something is going wrong.
EDIT:
Just noticed another thing, I dont think "../" would be a great way to reference the url, usually its either "/foo/ajax" which will allow you to use this function on any page.
It could be that your PHP script returns an error status code and even though it prints out the correct result, it still fails. I tested your scripts on my system and I got the 'success' alert. Then I changed my PHP script to the following:
<?php
header('Content-type: application/json', true, 401);
echo '{"items":1000,"mitems":0,"donations":0,"total":1000}';
?>
Note that the third parameter of the header function sets the http response code to 401 - Even though the correct output is sent back to the client; officially, the request has failed because of that status code. After running this code, I got the exact same problem as you.
So in summary, there might be something in your script which is causing a non-fatal error which doesn't show in the output of the script.
Are you defining the MIME type in your HTTP response?
Try adding a Content-type header to the output of your script.
<?php
...
$output = json_encode(...);
header('Content-type: application/json');
echo $output;
...
?>
You can also try using the mimeType parameter in your $.ajax() call to override the response type.
http://api.jquery.com/jQuery.ajax
Are you running your PHP scripts under Apache or on their own (chmod u+x on the script)? You probably need to use a PHP framework such as Zend, CodeIgniter or CakePHP and define a controller action that handles your AJAX request to have a proper HTTP response.
As the guy above me said, you should be using the json_encode(); function in PHP then echo'ing that output.
Make sure you encode an array though:
<?
$send = array(
'items' => '1000',
'mitems' => '0',
'donations' => '0',
'total' => '1000',
);
echo json_encode($send);
?>

Categories