javascript objects to json string to php array -> POST - php

Hey guys i really need help with this. i pass this json object to php..
var x = {};
x.xt = {};
x.xt.id = id;
x.xt.to = foo;
somearray.push(x);
convert object to json:
$.toJSON(x);
json string:
[{"x":{"xt":"9","to":"2"}}]
them i post this:
$.post(
"temp/sop.php",
{ xa: somearray},
function(data){
console.log("response - "+ data);
});
server side:
$xtj = $_POST["xa"];
$encodedArray = array_map(utf8_encode, $xtj);
$asnk = json_decode($encodedArray);
This returns:
string(4) "null"
and this:
$asnk = json_encode($xtj);
returns:
null
the data base it is set to:
UTF8
also when i test if it is an array, comes back true..
any idea how to solve this? thanks
also server side:
$xtj = $_POST["xa"];
$asnk = json_decode($xtj);
this returns:
NULL

$.toJSON(x) does not do the conversion in-place; it returns the JSON, and you're just discarding it. You need this instead:
$.post(
"temp/sop.php",
{ xa: $.toJSON(somearray) },
// ...
});
Then, on the PHP side, you won't want array_map as it's not going to be an array until you decode the JSON:
$xtj = $_POST["xa"];
$encodedArray = utf8_encode($xtj); // I'm not sure you need this, by the way.
$asnk = json_decode($encodedArray);

try using
if(get_magic_quotes_gpc()) $xtj = stripslashes($xtj);
to lose the excessive escaping before trying to decode.

What you are doing is you are converting to json string in JS ($.toJSON()).
And then in PHP you are again trying to convert to json string (json_encode()).
And you are using array_map() on something that is not an array but a string. (Try echo $_POST["xa"]; to see the contents of it.)

Related

An empty JSON object produced by jquery code is wrongly parsed to an empty string in PHP code

I am passing a JSON object via ajax to my php file. Then I use the function json_encode, and save it to the database.
The problem is, when the JSON object is empty {}, then in PHP it is not an empty object/array, but it is an empty string "".
I need to deserialize it as encoded (empty JSON object), not as an empty string.
What am I doing wrong?
JQUERY:
_key = $(this).data('column-name');
_temp = {};
$(this).find('> .rc-picker-content > .rc-picker-item').each(function (__index, $__element) {
_temp[__index] = {};
_temp[__index] = $(this).attr('data-value');
});
_attr[_key] = _temp; //the variable which is sent via ajax to php
PHP
if (isset($_POST['value']) && is_array($_POST['value'])){
$_POST['value'] = json_encode($_POST['value']); //this hould be enmpty array not empty string
}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
It may help.
I found a solution.
I convert the object to string before sending it via ajax to my php file.
_temp = JSON.stringify(_temp);
This solution has already been proposed. I just had to restructure my code.

js json.stringify to PHP json_decode

I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);

How to get data from json array in JavaScript?

I have php function, that returns array to JavaScript like this:
$data['first'] = 10;
$data['second'] = 20;
echo json_enocde($data);
In JavaScript the returned value is named response. I need to display the values and tried like this after reading about json:
alert("First: " + response.first + " Second: " + response.second);
But this code only shows undefined values in places of response.first and response.second.
If I write alert(response), then I get answer:
{"first":"10","second":"20"}
This means, that JavaScript is getting the information.
How can I get the values separately from the json encoded array?
Regards
Use JSON.parse() to turn the JSON string into a JavaScript object.
Looks like you still have the JSON string, and not parsed it to an JS object. Use JSON.parse:
var jsonString = '{"first":"10","second":"20"}'; // from whereever
var obj = JSON.parse(jsonString);
alert("First: " + response.first + " Second: " + response.second);
alert(obj); // should now be "[object Object]"
use eval like (NOT RECOMMENDED)
var res = eval(response); //as you can see people are against it so I am editing the answer
USE
JSON.parse()
OR if you use jquery
jQuery.parseJSON(response);

editing json string in php

I am trying to edit a data query using php by passing it through javascript,
my ajax request looks like
var totalSearchResult=10;
$.ajax({
url:"php/queryManipulation.php",
type: 'POST',
data: { totalQuery : totalSearchResult, query : '{"data":{"match_all":{}}}'},
success: function(finalList)
{
alert(finalList);
}
});
my php code looks like
<?php
$from=$_POST["totalQuery"];
$qry=json_decode($_POST["query"]);
$qry->from=$from; }?>
I am trying to get it in the form,
{"data": {"match_all": {}} , "from": 10}
I get the error Object of class stdClass could not be converted to string
Edit: Changed json_decode return value from array to object
You need to encode the json again just after finishing the edits.
So what you can do is something like:
<?php
$from = $_POST["totalQuery"];
$qry = json_decode($_POST["query"]);
$qry->data->from = $from;
//you will get the new json string
//as the finalList variable in your post callback
echo json_encode($qry);
?>
You should use json_decode($string, true) - so it will be an array.
Details here: http://php.net/manual/en/function.json-decode.php
You can decode to an array (not sure about objects) and re-encode:
$qry = json_decode($_POST['query'], TRUE);
$qry['from'] = 10;
$new_qry = json_encode($qry);

How to pass JS array via POST AJAX to PHP?

Here is my code:
var var_ids = new Array();
var i = 0;
jQuery("select").each(function() {
var_ids[i] = jQuery("option:selected",this).val();
i++;
}
var $data = {
action: "do_something",
var_ids: var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
And in my php:
$ids = mysql_real_escape_string(trim($_POST['var_ids']));
exit(print_r($ids));
And it just returns garbage...So my question is how to pass an array via AJAX to post php?
Thank you.
Most likely you get unexpected results because you apply string-related functions trim and mysql_real_escape_string to array $_POST['var_ids']
As long as it is just an array of integers - the only mysql sanitize you need is casting to int:
$ids = array_map('intval', $_POST['var_ids']);
print_r($ids);
$_POST['var_ids'] is an array in your example on the PHP side. You can only call trim and mysql_real_escape_string on strings not arrays. Try this in php:
$postData = isset($_POST['var_ids'])?$_POST['var_ids']):null;
if(is_array($postData)){
foreach($postData as $key=>$value){
$postData[$key] = mysql_real_escape_string(trim($value));
}
}
Viola, $postData is now a PHP array with trimmed and escaped values.
It's in the docs about 1/4 of a way down titled pass arrays of data to the server
var var_ids = new Array('10','12','13');
var $data = {
action: "do_something",
'var_ids[]': var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
Make it json_encoded array ... And then You can json_decode() the array properly.
You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way.
Javascript JSON Instructions
JSON PHP Reference
You can either post each of the items with the key items[], then you could access the array as $_POST['items'] or you can serialize the array, send it and unserialize in PHP (JSON.stringify and PHP json_decode).

Categories