Unexpected token 'a' - php

Using jQuery I have made the following JSON data:
[{"name":"date","value":"24-05-2013"},{"name":"omschrijving","value":""}]
This is all valid JSON, but when I try to fire the data using jQuery it is giving me the following error:
Unexpected token A
Here you can see the AJAX call:
$.ajax({
type: "POST",
url: "modules/rma/ajaxhandler.php",
contentType:"application/json; charset=utf-8",
data: goededata,
dataType: 'json',
succes: function(data) { alert(data); },
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert( textStatus + " " + errorThrown); }
}).done(function() {
});
ajaxhandler.php contains the following lines:
<?php
error_reporting(E_ALL);
session_start();
/**
* Ajaxhandler
*
*/
print_r($_POST);
echo json_decode($_POST['data']);
?>
The data that needs to be sent is made the following way:
var allFields = $( [] ).add( date ).add( omschrijving ).add( klachtomschrijving ).add(status).add(artikelnummer).add(klantid).add(meldidrepro).add(meldidaankoop).add(leverancier).add(inkoopregelid).add(serienummer);`
var goededata = JSON.stringify(allFields.serializeArray());
How can I correct this error?

You can not use print_r because you are requesting json. The Server-Response is not valid. Comment out the print_r call and it should work.
The unexpected token 'a' comes from the output of print_r:
array(
...
)
You could use an extra key for debugging:
echo json_decode(array(
'data' => $_POST['data'],
'debug' => print_r($_POST, true), // note the second parameter for print_r
));
on the client side you work with response.data and your debug output is in `response.debug'.
But, why not simply log debug output on the server side into a file?
The error_reporting(E_ALL); will be a problem too.
It's always a good idea to set the response type:
header('Content-type: application/json');

Chances are your print_r is breaking the expected return call from your AJAX request. Also I don't see where any post data was getting thrown. What I would expect to have happen here is an empty alert box. comment our the print_r

Related

Empty PHP response object in AJAX but only on success

To receive my response object from my PHP server I have the code down below.
First of all, it works. What does not work is that if my first PHP condition is met, the success function in my Ajax responds correctly but only without using the data object.
This is my AJAX function:
$.ajax({
type: "PUT",
url: "http://server/register",
contentType: "application/json",
data: '{"username":"' + username + '", "password":"' + password + '"}',
success: function(data) {
console.log(data) // The output in my dev tools under Firefox is just a blank line, no error message or even "undefined".
console.log("Success") // Works!
if(data.status == 200){
console.log("Test 1") // Doesn't work. Although status code 200 is shown to me.
}
},
error: function(data) {
console.log(data) // This works! I can see the content of the object. The correct status code (409) is shown to me.
if(data.status == 409){
console.log("Test 2") // Works
}
}
});
This is my PHP function:
public function register($request, $response)
{
...
if(condition-1) {
echo("Condition 1 works!"); // Works.
return $response->withStatus(200);
} elseif(condition-2) {
echo("Condition 2 works!"); // Works too.
return $response->withStatus(409);
}
}
I don't see why there is no data object. I'm using the Slim 3 Framework and could probably return a JSON object like this:
$content = ["foo" => 'bar', ...] ; //Any data you wish to return
return $response->withJson($content);
But so far my whole code works without using JSON objects. Even if I var_dump the $response object, I can see that on the server side it is there.
if(condition-1) {
var_dump($response->withStatus(200)); // Works. I can see it.
}
There's a lot wrong here, so I've done my best to point out what I see wrong, and hopefully with the changes I'm going to suggest you will have success.
If you are trying to use data.status in your ajax success function, then it looks like you think you are returning json, but you aren't. Even if you are, you are corrupting it by echoing "Condition 1 works!".
So think about it, if you have a json response like this:
{'a':'1'}
And you echo something out before it, your response is corrupted, and looks like this:
Condition 1 works!{'a':'1'}
Same corruption occurs if PHP throws an error your way, so be aware of that.
You should also be declaring a dataType for your ajax request, so:
$.ajax({
type: "PUT",
url: "http://server/register",
contentType: "application/json",
data: JSON.stringify({
"username": username,
"password": password
}),
dataType: 'json', // <-- THIS LINE IS IMPORTANT
success: function(data, textStatus, jqXHR) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
// ...
}
});
Note: you were single quoting your data object, so you were doing it the hard way. Just use JSON.stringify on a JS object like I did!
Since my code expects a json response, make sure to look at the other answer here, as it shows how to send back a proper json response with slim.
Finally, in your ajax success function, data.status is not ever going to be available. Docs for jQuery show that there are three parameters, (data, textStatus, jqXHR) and data is specifically for the data, not the HTTP status code or any headers.
I put together a full working example of a mini Slim app. It's fully tested and works (it's just not awesome, so don't laugh):
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('<!doctype html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$("p").on("click", function(){
var username = "kookoopapa";
var password = "gr3atp4ssWerd";
$.ajax({
type: "PUT",
url: "/register",
data: JSON.stringify({
"username": username,
"password": password
}),
contentType: "application/json",
dataType: "json", // <-- THIS LINE IS IMPORTANT
success: function(data, textStatus, jqXHR) {
alert( data.a );
alert( data.b );
},
error: function(jqXHR, textStatus, errorThrown) {
// ...
}
});
});
});
</script>
</head>
<body>
<p>Click</p>
</body>
</html>');
return $response;
});
$app->put('/register', function (Request $request, Response $response) {
$php_input = file_get_contents('php://input');
$vars = json_decode( $php_input, TRUE );
$content = [
'a' => $vars['username'],
'b' => $vars['password']
];
return $response->withStatus(200)->withJson($content);
});
$app->run();
Try to use the following return:
$content = ["foo" => 'bar', ...] ; //Any data you wish to return
return $response->withStatus(200)->withJson($content);

JSON.parse Error after decoding JSON.stringify-ed Array

I want to submit an array of arrays through JSON. So I create an object, apply JSON.stringify() on it and set it to a formData...
var sources = new Array();
$('.source-instance').each(function(){
var auxObject = {};
auxObject["sourceTitle"] = $(this).find(".source-title").val();
sources.push(auxObject);
console.log('sources: ' + JSON.stringify(sources));
});
formData.set('sources', JSON.stringify(sources));
When I check the data
console.log(formData.get('sources'))
I get
[{"sourceTitle":"SomeTitle"},{"sourceTitle":"AnotherTitle"}]
... which I then proceed via AJAX to the server.
On server side in php I loop over the array and let it print:
foreach (json_decode($request['sources'], true) as $sourceInstance) {
print_r($sourceInstance);
}
I get
Array
(
[sourceTitle] => SomeTitle
)
Array
(
[sourceTitle] => AnotherTitle
)
which looks pretty fine. But I also get
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
How come that? And how can I repair this? I don't see, where it is coming from.
EDIT
the ajax looks like this:
$.ajax({
url: '/piece/store',
type: 'POST',
processData: false,
contentType: false,
dataType: 'JSON',
data: formData,
success: function(response){
if (response.status == 'error'){
// show the erors
}
if (response.status == 'success'){ // "redirect" to success page
window.location.replace('/succes');
}
},
error: function(response){
$(".optional.errors").show();
$('ul.errors').empty();
$.each(response.errors, function (index, error) {
$('ul.errors').append('<li>' + error + '</li>');
});
}
});
the php responds:
$response = [
'status' => 'success',
];
return response()->json($response);
That error message happens when jQuery is trying to parse the response from the ajax call.
In your ajax request, you have set: dataType: 'json', which tells jQuery to expect the response to be a json-string. jQuery will then try to parse that json-string into a json-object (using JSON.parse()).
However, since you have print_r($sourceInstance) in your PHP-code, the response won't be a valid json-string and will make JSON.parse() fail.
Any output on the server side (echo, var_dump, print_r etc) will be a part of the response.

how to pass JSON data to php using ajax post

Here is the code: (the #debug div text is shown below)
$("#debug").text(JSON.stringify(data));
// Try to save to a file
$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json',
data: JSON.stringify(data),
success: function(xhr, status, errorMessage) {
if( xhr.responseText == "Success" ) {
alert("Success!");
} else {
alert("response was "+xhr.responseText);
}
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});
The JSON.php page is:
<?php
openlog("scriptLog.txt", LOG_PID | LOG_PERROR, LOG_LOCAL0);
$json = $_POST['json'];
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
syslog(LOG_DEBUG, "Received Data");
if (json_decode($json) != null) { /* sanity check */
$file = fopen('./data.json','w+');
fwrite($file, json_decode($json));
fclose($file);
} else {
syslog(LOG_DEBUG,"Failure");
return "Failure, json decode is null";
}
closelog();
return "Success";
?>
In the log I get:
Mar 14 14:50:54 scriptLog.txt[21902] : Received Data
Mar 14 14:50:54 scriptLog.txt[21902] : Failure
In the debug div text I get:
{"1457981454959":{"id":1457981454959,"code":"1","title":"Test","date":"22/03/2016","description":"a Task"}}RESPONSE: , error: SyntaxError: JSON Parse error: Unexpected EOF
1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.
2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?
1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.
As I understand you are debugging the code, so syslog can be not the best idea.
I would simply use the browser network console to see the content of requests and a simple php file like this to see the content of $_POST:
<?php
echo json_encode($_POST);
In more complex cases - use the actual debugger.
2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?
You are trying to use the json key in your $_POST, but you didn't instruct jQuery to add it, so you are receiving not what you expected.
There are few issues with your $.ajax call, here is the commented version:
$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json', // Note: dataType is only important for the response
// jQuery now expects that your server code
// will return json
// here you need to add the 'json' key
data: {'json': JSON.stringify(data)},
// the success method has different order of parameters
//success: function(xhr, status, errorMessage) {
success: function(data, status, xhr) {
alert("response was "+data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});
Now on the server you will have $_POST['json'] with serialized string and you can json_decode it.
Alternatively you can send the JSON data without serialization:
var data = {'test': 'abc'};
$.ajax({
type: 'POST',
url: './json.php',
// No 'JSON.stringify()', just send your data
data: data,
...
});
And on the server you will have $_POST['test'] with abc value (so you have your json already converted into array).

jQuery success function not executing

the first success function works, the second doesnt... it works if I change datatype to text... but if i change datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...
var turl = "getForum.php";
var turl = "getForum.php";
var wurl = "getDiscussions.php";
$.ajax({
url:turl,
type:"POST",
dataType:"json",
success:function(data){
forumid = data[0]; // this works ...
dataString = 'forumid='+ forumid;
$.ajax({
url:wurl,
type:"POST",
dataType:"json",
data:dataString,
success:function(data){
alert(data); // this works if I change datatype to text... but if i type datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...
}
});
}
});
php file return json object
$query1 = " select * from discussforum where forumId= '$forumid'; ";
$result1 = mysql_query($query1);
while($info1 = mysql_fetch_array( $result1 )){
echo json_encode($info1);
}
Are you sure about your PHP is returning only one JSON object? If not:
$ret = array();
while($info1 = mysql_fetch_array( $result1 )){
$ret[] = $info1;
}
print json_encode($ret);
I think the solution is delineated in the comments, but here it goes in a bit more detail. First take a look at the fine documentation for jQuery.ajax(). You need to add an error callback to all your Ajax calls. with the following signature:
error(jqXHR, textStatus, errorThrown)
You can just add a parameter to .ajax() like this:
error: function(jqXHR, textStatus, errorThrown) {
console.error(textStatus);
},
This way you will see in the console every error that happens during the Ajax call and also during the processing of the message. You can define a generic ajaxError callback in some common .js file and use it everywhere.
In this case you are explaining very well the cause of the error: what getDiscussions.phpis returning is not a JSON, and thus the jQuery parser cannot understand it when you set dataType:"json": it would call the error callback if there was one. It works however when the dataType is set to text. So the POST request is probably failing.
To see what it is sending you can just extract it in the error callback, like this:
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error in response: ' + jqXHR.responseText
},
so you can diagnose the problem in the server.

JQuery AJAX Issue without error

So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});

Categories