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

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.

Related

jquery won't accept json_encode() data

I'm using the following piece of code to send data from a form to a php script that will do some calculations using a class:
$.ajax({
type: "POST",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
My PHP script creates an array which I encode with JSON and then echo
$jsonString = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
echo json_encode($jsonString);
So far so good. But I'm not very keen on displaying the raw JSON. I'd like to format the text before it's written to the document. I've tried $.parseJSON() and $.getJSON() but none of them work.
The jQuery docs says it needs a string but isn't json_encode() making my array to a string? Isn't echo making it a string? Why am I getting the error Uncaught SyntaxError: Unexpected token { in my jQuery-file? My theory is that it doesn't have single quotes around it.
I've tried using header('Content-type: application/json') in my PHP script and I've also tried dataType: json in my AJAX POST but nothing is working.
What am I doing wrong?
From the comments it sounds like you are using json_encode wrong. Store each piece of data into an array and then encode the array.
$data = array();
for($i=0;$i<$something;$++) {
$data[] = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
}
echo json_encode($data);
Then your Javascript would need to be
$.ajax({
type: "POST",
url: "test2.php",
dataType:"json",
data: values,
success: function(returnedData) {
//returnedData will now be an array Object
for( var i=0; i<returnedData.length; i++ ) {
$("#result").html(returnedData[i].monthText);
}
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
for parsing, use jQuery.parseJSON(returnedData);
Add dataType in your ajax call like this.
$.ajax({
type: "POST",
dataType:"json",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});

return json from php and handle

I get this from ajax call
{"id":"381120774951940096","time":"Posted 0 minutes and 51 seconds ago.",....
How can I add each of these into variable, id, time etc? data.id won't work, it says undef.
<script>
$(function() {
$.ajax({
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
});
</script>
This is what I return from start.php
$return = array('id' => $info['id_str'] ,'time' => timeDiff(new DateTime($info['created_at'])), 'name' => $info['user']['name'], 'text' => $info['text'], 'image' => $picture, 'url' => "http://twitter.com/{$info['user']['screen_name']}");
print_r(json_encode($return));
EDIT
I had that print_r inside foreach loop and that was the issue. So I added another array and used echo json_decode($array,true) at the end of file.Writing this just in case, might help someone.
Cheers
First, in your PHP, change your line to:
echo json_encode($return, true);
That second parameter ensures that the JSON is interpretable as an associative array. Also, you should use echo instead of print_r when returning JSON; print_r can alter the formatting.
Next, use the following AJAX call:
$.ajax({
type: "POST",
url: "start.php",
dataType: "json", // Add this option.
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
The dataType: "json" option ensures that data will be parsed as a JSON object as soon as it's retrieved. So, data.id should be immediately available in your success callback function.
Hope this helps!
Firstly, you should use echo in the server script. print_r is mainly for debugging arrays.
Secondly, you should declare a dataType option for the ajax call:
$.ajax({
dataType: "json", // <-- here
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
});
The way you have it now, I think you are getting a string response as data.
You can verify that with console.log(JSON.stringify(data));
You have to set dataType: 'json' in your ajax. This means that jQuery will parse the result as JSON for you.
Then parse the data,
data = $.parseJSON(data);
Then read var id = data.id;
Also, in your PHP, No need to use print_r(). Just use echo instead print_r().like:
echo json_encode($return);
You'll need to parse the JSON string into an object. You can use JSON.parse to do this.
// Your JSON string
var json_str = "{'id': 'foo', 'time': 'bar'}";
// We need to parse it, converting it into a JS object
var json_obj = JSON.parse(json_str);
// We can now interact with it
console.log(json_obj.id);
console.log(json_obj.time);
Alternatively, you can parse JSON using a built in jQuery function parseJSON().
jQuery also has a built in function for fetching JSON called getJSON(). If memory serves, this is just a shorthand for doing an .ajax() call and specifying a datatype of json. This will handle the above (parsing JSON) for you, and is the recommended solution.

ajax call with a return json never catch in success

I'm trying to get a variable from my ajax call:
$.ajax({
type: "POST",
url: "insert",
data: { title:title, start:dstart, end:dend },
contentType: "application/json",
dataType : 'json',
success : function(data) {
data = JSON.parse(data);
console.log('data = '); // is showing the data with double quotes
console.log(data);
}
});
and there is my PHP:
$id = $calendar->getId();
$json = array ( 'id' => $id );
var_dump(json_encode($json));
json_encode($json);
And with my var_dump I can see my json_encore, like that for example:
string '{"id":156}' (length=10)
but in my ajax() success, console.log() don't show anything in my console.
Where can I see if my success: function(data) is empty or not ? I would just catch the id in my ajax success.
UPDATE : issue fixed. in fact i'm working with symfony, and I haven't seen that on my action insert where is my PHP, the page called by symfony (indexSuccess.php) was not empty which was why its not working at all.)
If you take a look at your PHP code, you're basically doing nothing with the output of json_encode() ...
Please update the last line of your PHP code to:
echo json_encode($json);
Now you should get the data you want as response.
EDIT: #1nsan3, you asked in the comment if echo not does the same as var_dump() ... I think you get an answer here: What's the difference between echo, print, and print_r in PHP?
EDIT2:
Please remove the JSON.parse() call. The response of your AJAX request is already parsed by jQuery when using dataType : 'json',
as explained in http://api.jquery.com/jQuery.ajax
Are you sure your php returns valid json data ?
php
$id = $calendar->getId();
$json = array('id' => $id);
echo json_encode($json); <-- your php code must echo only this valid json,
return; make sure no other values are echoed
above or below this which will break json.
js
success : function(data) {
if($.trim(data) != '') {
console.log(data);
} else {
console.log('no data');
}
}

Posting form data with .serialize() PHP error

I'm posting form data that includes some checkboxes and other input to a PHP script with jQuery's .serialize().
post.js:
$(function(){
$("#button").click(function(){
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
success: function(data){
$.getJSON('post.php', function(data) {
$.each(data, function(key, val) {
})
})
}
})
})
})
post.php:
$tags = array();
foreach($_POST['checkboxes'] as $key => $value){
$tags[] = "$value";
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
If I point the getJSON to post.php I get a PHP warning in my error log that says "PHP Warning: Invalid argument supplied for foreach()" and this causes the data from the input form to not be properly passed (i.e. a fwrite after the foreach doesn't write anything). If I reference another file for the getJSON, say data.php, or if I don't include it at all, the post works fine. Why is this happening? I could just store the data and make a second script to return the JSON data but it would be easier to do it all in one script.
Here's the deal:
success: function(data){
In the above piece, the data you are recieving is the returned json_encoded string containing key:value pairs of $tags, as you defined.
$.getJSON('post.php', function(data) {
Now, in your getJSON request you are passing over no values, and your foreach statement expects you to post the values of checkboxes so they can be parsed, and the tags be made. I'm not really sure I understand why you would want to do this, as the success: function(data) will natively parse the JSON being returned from the server and will be ready for you.
$.each(data, function(key, val) {
If you just simply lose the $.getJSON request, and use the each function, you will be iterating over the tags that you return from the server. I believe this is the intended functionality you want.
your code is breaking when checkboxes are not posted
$tags = array();
if( array_key_exists('checkboxes', $_POST) && is_array($_POST['checkboxes']) ) {
$tags = array_values($_POST['checkboxes']);
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
You're getting Invalid argument supplied for foreach because it expects a value in $_POST['checkboxes'] which you're not sending in your $.getJSON call.
$.getJSON sends another AJAX call, a GET request to get a JSON file. You already sent a POST request to post.php, you don't need to send another call.
Add dataType: 'json' to your 1st call, and the JSON response will be parsed for you.
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
// code here
});
}
});
you don't have to invoke "getJSON" because you already have what you want. Everything you need is in data. So your "success" callback should look something like this:
function(data){
var jsonData = $.parseJSON(data);
$.each(jsonData, function(key, val) {
})
}

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