how to pass JSON data to php using ajax post - php

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).

Related

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.

Unexpected token 'a'

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

SyntaxError: syntax error in ajaxFileUpload jquery plugin

i want to pass other parameters with file to save in database.when i put code to get those variables and save in database it give me alert "SyntaxError: syntax error"...
here is my code
$.ajaxFileUpload
({
url:'popup/doc_mydeal.php',
secureuri:false,
fileElementId:'deals_documents',
dataType: 'json',
data:{rand_key: $('#rand_key').val(), document_name: $('#document_name').val()},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}
}
},
error: function (data, status, e)
{
alert(e);
}
})
Now on doc_mydeal.php
$tempFile = $_FILES['deals_documents']['tmp_name'];
$targetFile=$path.$_REQUEST['rand_key'].basename($_FILES['deals_documents']['name']);
move_uploaded_file($tempFile,$targetFile);
and here is mysql query to save in database
When you specify a dataType of json in the options for the jQuery AJAX call you're telling the code that the server will be returning valid JSON. Based on this information jQuery will implicitly parse the response text as JSON, passing the resulting object as the argument of the callback function.
In the case that the response text isn't valid JSON the parse will fail and the error callback will be executed instead. As has been pointed out in the comments, what you're returning from your PHP script is invalid JSON.

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);
}
});
});

Sending JSON to server, using jQuery

I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.

Categories