Can't decode JSON from Javascript to PHP - javascript

i'm passing a JSON from javascript to PHP inside an ajax question.
Json is this (printed from PHP, without json_decode):
[{"id":"440","step":"1","pass_rules":{"manual":false,"check_percent":true,"quiz":false,"list_element":["id1"]}},{"id":"438","step":"2","pass_rules":{"manual":false,"check_percent":true,"quiz":true,"list_element":["id1"]}}]
Is passed though an ajax:
var formData = new FormData(this);
formData.append('array', JSON.stringify(fullArray));
$.ajax({
type: "POST",
url: URL_API + "/call_to_api",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (json) {
//code
}
})
If get array in this way from PHP, i can print the json like the json on top of the post
$array = mysql_real_escape_string($_POST['array']);
json_decode is not working on the element, and print empty.
I don't undestand why!
UPDATE: array is passed inside the form in this way:
array: [{"id":"441","step":"1","pass_rules":{"manual":false,"check_percent":true,"quiz":false,"list_video":[]}},{"id":"438","step":"3","pass_rules":{"manual":false,"check_percent":true,"quiz":true,"list_video":[]}}]
json_last_error() called here:
$array= json_decode($_POST['array']);
json_last_error();
json_last_error returns 4 so JSON_ERROR_SYNTAX...but JSON seems good :/
UPDATE2: var_dump output:
string(388) "[{"id":"441","step":"1","pass_rules":{"manual":false,"check_percent":true,"quiz":false,"list_video":[]}},{"id":"438","step":"3","pass_rules":{"manual":false,"check_percent":true,"quiz":true,"list_video":[]}}]"

Related

How to loop through JSON object with an array with backslashes inside in Jquery/Javascript from AJAX call

I have an array where I want to loop through the array inside the JSON and show the data in the table based on the nationalities in the array. The problem is that the array data contains backslashes and I can't loop through it. I retrieve the data with an AJAX call from my PHP file.
PHP:
$arr
if (!empty($arr)) {
echo json_encode($arr);
// print_r($arr);
} else{
$errors = 'No data available.';
}
exit;
If I print_r() I see: Array ( [0] => stdClass Object ( [company] => John Comp [pro_countries] => ["BR","ES","FR"])
If I use echo json_encode my echo looks like but I can print company in my Jquery: [{"company":"John Comp","nationality":"[\"BR\",\"ES\",\"FR\"]"}]
But if I use print_r($arr) the slashes disappear but I can't seem to print the company in Jquery: [{"company":"John Comp","nationality":"["BR","ES","FR"]"}]
If I use Print_r() Then my AJAX call in JQuery goes straight to the error response.
JQuery:
$.ajax({
type: 'GET',
url: 'testurl',
dataType: 'json',
processData: false,
cache: false,
success: function (response){
response.nationality.forEach((item)=>{
});
I also tried:
$.ajax({
type: 'GET',
url: 'testurl',
dataType: 'json',
processData: false,
cache: false,
success: function (response){
var data = JSON.parse(response);
data.nationality.forEach((item)=>{
});
What I want after the loop:
nationality is a JSON string, you need to parse it so you can loop over it.
JSON.parse(response.nationality).forEach(item => ...)
I'm not sure why you encoded nationality in the first place. You should just make it an ordinary PHP array, and then it will be encoded as part of $arr.

jquery not posting array data

ive tried 10 different solutions to this issue on stackoverflow and none of them work, heres the issue, i need to post a array via ajax to a url
simple right?
the array comes from post values like this $_post[xxx] which i store in a var.
i mocked up a js function, that has the same error, instead of passing the array i just included as a var in the function, problem is the data is not gettin posted to the url.
pastebin link: http://pastebin.com/8ivWqJ8g
function generateImage() {
var Imagedata = [];
Imagedata['id'] = 1;
Imagedata['type'] = 'some type';
var url = '';
$.ajax({
url: url,
processData: false,
dataType: 'JSON',
data: JSON.stringify(Imagedata) ,
method:'POST',
async: false
});
Named properties of arrays do not get serialised when you convert the data to JSON.
Arrays are supposed to hold an ordered set of values, not an arbitrary set of name:value pairs.
Use a plain object ({}) not an array.
Asides:
Don't use processData: false unless you are passing something that isn't a string or an object to data (e.g. a FormData object). Since you are passing a string, it is harmless, but pointless. If you were passing an object (which you probably should be, see below), it would break things.
Don't use async: false. It is deprecated, and harms the user experience (since it locks up the JS thread until the response arrives).
If you want to populate PHP's $_POST then don't format your data as JSON. Pass the object directly to data: without using JSON.stringify.
If you do want to make a JSON formatted request, then don't forget to set the contentType.
function generateImage() {
var Imagedata = {
id: 1,
type: "some type"
};
var url = '';
$.ajax({
url: url,
dataType: 'JSON',
data: Imagedata,
method: 'POST'
});
// or …
$.ajax({
url: url,
dataType: 'JSON',
contentType: "application/json",
data: JSON.stringify(Imagedata),
method: 'POST'
});
}
data should be an Object like this:
$.ajax({
url: 'http://...',
dataType: 'JSON',
data: {id: 1, type: 'some type'} ,
method:'POST',
async: false
});

Can't send JSON as string via AJAX

So I'm trying to send a JSON as a string.
Then I have a PHP back-end that retrieves this JSON string and parses it using json_decode.
Unfortunately, I can't get to send this JSON as a string.
Here's the jQuery Ajax script I used:
var jsonString = JSON.stringify(checkables);
console.log(jsonString);
$.ajax({
url: $url,
type: 'POST',
data: {ajaxidate: JSON.stringify(jsonString)},
contentType: "application/json; charset=UTF-8",
success: function (data)
{
// just successful callback
},
error: function ()
{
// just error callback
}
});
Variable checkables contains raw form as JSON data:
After applying JSON.stringify(), this is now how it looks:
[{"name":"name","type":"multialphanumslug","value":"AD"},{"name":"server","type":"host","value":"10.1.1.1"},{"name":"port","type":"number","value":"8080"},{"name":"authid","type":"username","value":"barryallen"}]
At the back-end, I have this PHP script:
<?php
var_dump($_POST);
die();
?>
Now I suppose $_POST at back-end should now contain this:
array(
'ajaxidate' => "[{\"name\":\"name\",\"type\":\"multialphanumslug\",\"value\":\"AD\"},{\"name\":\"server\",\"type\":\"host\",\"value\":\"10.1.1.1\"},{\"name\":\"port\",\"type\":\"number\",\"value\":\"8080\"},{\"name\":\"authid\",\"type\":\"username\",\"value\":\"barryallen\"}]"
);
But it didn't receive anything. Here's the captured request:
The response from back-end?
I tried with POSTMan and I received an expected correct output:
Now that was ridiculous.
I'm stuck at this for 2 days trying to figure out what's going on or what did I miss. Any help will be greatly appreciated.
You need to parse the data on the server:
$myArray = json_decode($_POST['ajaxidate']);
var_dump($myArray);
Consider this:
<?php
$a = '[{"a": 1}]';
$b = json_decode($a);
var_dump($a);
var_dump($b);
?>
Output:
string(10) "[{"a": 1}]"
array(1) {
[0]=>
object(stdClass)#1 (1) {
["a"]=>
int(1)
}
}
dataType: 'json', tldr: Use It!
When setting dataType = json you tell jQuery that the response from the server should be interpreted as JSON and it will therefore parse it for you and give the parsed object / array as first argument to the success callback:
$.ajax({
// ...
dataType: 'json',
success: function(myJson) {
console.log(myJson); // this will be a JSON object/array...
}
});
As you mention dataType: json in your ajax call data need to be in json formate but using JSON.stringify convert Json object to json String that with make problem for you need to change
`var jsonString = JSON.stringify(checkables);`
to
var jsonString = checkables;
JSON.stringify()
Solved my own problem. Having #Munna suggested to use $.post() made me figure out to eliminate the unnecessary. From that case, the unnecessary is contentType option from $.ajax().
This is the updated working solution:
$.ajax({
url: $url,
type: 'POST',
data: {ajaxidate: JSON.stringify(jsonString)},
success: function (data)
{
// just successful callback
},
error: function ()
{
// just error callback
}
});
Thanks everyone who helped. Have a good day

PHP is not able to read data sent in jQuery.ajax POST

JavaScript code:
var data = {"hiSO": "my very complex - nested objects/arrays - data object"};
var j = jQuery.noConflict();
j.ajax({
type: "POST",
url: "postTestingResult.php",
contentType: "application/json; charset=utf-8",
data: {"data": JSON.stringify(data)},
dataType: "json",
success: ajaxSuccess,
error: ajaxError
});
PHP Code:
header('Content-Type: application/json');
if(!empty($_POST['data'])) {
$data = json_decode($_POST['data']);
//do things with data
echo json_encode(array("success" => "thanks for the info!"));
} else {
echo json_encode(array("error" => "'data' is not set or is NULL"));
}
No matter how I structure the data, $_POST['data'] always seems to be empty (specifically, Undefined). If you want a full copy of the data object I am using, check out this JSFiddle. Appreciate the help, thank you!
You've told the server you're sending JSON (via contentType: "application/json; charset=utf-8"), but you're not sending JSON, you're sending URI-encoded data. This is because you've given jQuery an object for the data option (an object with one property, whose value is a JSON string).
Your PHP code expects URI-encoded data, so to fix it just remove the contentType option so jQuery uses its default.
If you really want to send JSON instead (which would require changing your PHP), change
data: {"data": JSON.stringify(data)},
to
data: JSON.stringify(data),
or
data: JSON.stringify({data: data}),

How to transfer json string to another page using jquery's ajax method?

I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.

Categories