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