Jquery serialize to PHP array - php

I want to send the result of a HTML sorting to the server by serializing with jQuery.
This works if I only send the result:
var result = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: '/cms/update/',
data: result,
});
But I try to send a Javascript Object to the server wich contains the serialized 'result'
In PHP I get an array with result_2 as the serialize object:
Array
(
[ids_1] => miti_1_ti_2_col_2
[article_id] => article_id_2
[result_1] =>
[ids_2] => miti_1_ti_2_col_1
[result_2] => article_id[]=2
)
How can I get this result to be an array in PHP?

As I understood "result" is a serialized object too.
So you have to unserialize result at first.
Then you have to unserialize result2. Something like that:
$res1 = unserialize($data);
if (isset($res1['result_2']){
$res2 = unserialize($res['result_2']);
}
Updated:
I don't know if your result_2 in data is already serialized. Therefore here are two examples:
if result_2 is not serialized in data:
$arr = array('id_1' => 'miti_1_ti_2_col_2',
'article_id' => 'article_id_2',
'result_1' => '',
'ids_2' => 'miti_1_ti_2_col_1'
);
$arr['result_2'] = $arr;
$test1 = serialize($arr);
$test1 = unserialize($test1);
If result_2 is already serialized in data:
$arr = array('id_1' => 'miti_1_ti_2_col_2',
'article_id' => 'article_id_2',
'result_1' => '',
'ids_2' => 'miti_1_ti_2_col_1'
);
$arr['result_2'] = serialize($arr);
$test2 = serialize($arr);
$test2 = unserialize($test2);
$test2['result_2'] = unserialize($test2['result_2']);
This code works I checked out it. If your code still doesn't work check result in JS.

If I've understood correctly, you need to convert a string such as action[]=1&action[]=2 into an array?
If that is right you can use the following: (when $_POST["order"] = "action[]=1&action[]=2")
$result = preg_split("/&?action\[\]=/", $_POST["order"], -1, PREG_SPLIT_NO_EMPTY);
This will give you:
Array
(
[0] => 1
[1] => 2
)

Related

PHP handling multi-dimensional object//array from AJAX Jquery post

I have a large multi-dimensional object of arrays in JS that I am trying to pass to PHP using Ajax. The keys of some of the array values are written arrays test[key], and in PHP I want them to be read as such test => array([key] => 123). Note, I am working in Wordpress.
Working example
JS:
var args = {
'action' : 'save',
'test[key1]' : ['123', 'abc']
}
var request = $.ajax({
url: settings.get('ajaxurl'),
data: args,
type: 'post',
success: function(response) { // }
});
PHP print_r on output:
[action] => save
[test] => Array
(
[key1] => Array
(
[0] => 123
[1] => 234
)
)
However, I want to send all of the test[key1] (and a lot more data) at the second level of the object. I have a lot of data and need them grouped accordingly.
Not working example
JS:
// simple changing the args
var args = {
'action' : 'save',
'data' : {
'test[key1]' : ['123', 'abc']
}
}
PHP print_r on output:
[action] => save
[data] => Array
(
[test[key1] => Array
(
[0] => 123
[1] => 234
)
)
This seems to be really difficult to explain - but it looks like PHP isn't parsing the array keys properly when it's not on the top level of the array. Am I doing something wrong // is there a way around this? I can provide more insight if needed, I attempted to make this as clear as possible.
When printing the keys of the data array, it prints them without the final ]. So it shows test[key1 instead of what I am expecting. Maybe they get stripped somewhere?
I think you need to stringify the data
var request = $.ajax({
url: settings.get('ajaxurl'),
data: JSON.stringify(args),
type: 'post',
success: function(response) { // }});
Then use json_decode to make it useful in PHP.
Edit:
This might get you where you want to go...
var args = {
'action' : 'save',
test : {
key1 : [
'123',
'abc' ]
} }
Since JavaScript does not allow for associative arrays.
Please try this args, this will give multi-dimensional array result.
var args = {
'action' : 'save',
'data' : {
'test': {
'key1' : ['123', 'abc']
}
}
}

JS post Object via JSON

I am aware, that there are many questions regarding this topic in general... however, so far I haven't found a solution to my specific problem:
I have objects, looking something like that:
var myArray = [];
var ArrayObject = {
power: 10,
name: 'arrayobject'
}
myArray.push(ArrayObject);
var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);
Now I would like to post this data to php:
post("./output.php", myObject,'post');
Well, this does not work... I also tried it with
var myJSON = JSON.stringify(myObject);
and on PHP Side with
//$myObj = json_decode($_GET['myObject']);
but that does not work as well... if I remove the 'myArray' from 'myObject' that works, but having all data in one object would be very nice.
Can anyone tell me how to do that or point me in the right direction?
Thank you very much!
If you make request like this
function test(){
var myArray = [];
var ArrayObject = {
power: 10,
name: 'arrayobject'
}
myArray.push(ArrayObject);
var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);
jQuery.post('output.php', {
data: {
myObject:myObject
},
}, function(data) {
console.log(data);
});
}
then you access the data in PHP like
$_POST['data']['myObject']
Whole $_POST will look alike
array (
'data' =>
array (
'myObject' =>
array (
'Name' => 'test',
'myArray' =>
array (
0 =>
array (
'power' => '10',
'name' => 'arrayobject',
),
),
),
),
)
You don't need to json_decode it automatically does

how do I get my php array to json

I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);

Create an object from a valid JSON array with php

I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array.
Here is what I've tried:
print_r($json_obj) yields:
Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) )
print_r($json_obj[0][1]) yields:
featured
print_r($json_obj[1][0]) yields:
uploads/featured/moon-5469.jpg
print_r($json_obj[1][1]) yeilds:
featured
print_r($json_obj[0][0]) yields:
uploads/featured/doublewm-4097.jpg
PHP Code:
<?php
$resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"],
["uploads/featured/moon-5469.jpg","featured"]]';
$json_obj = json_decode($resultSet);
// print_r($json_obj);
print_r($json_obj[0][1]);
?>
The JSON validates per JSONLint
[
[
"uploads/featured/doublewm-4097.jpg",
"featured"
],
[
"uploads/featured/moon-5469.jpg",
"featured"
]
]
I would like to end up with a object with all the keys in the json_obj... ie:
json_obj = array(
'uploads/featured/moon-5469.jpg',
'uploads/featured/doublewm-4097.jpg'
);
If your input is always in the same format, you can handle it like this
$tmp = json_decode($resultSet);
$json_obj = array();
foreach ($tmp as $values) {
array_push($json_obj, $values[0]);
}
This will give you $json_obj in the desired format with a hardcoded $resultSet like the one you provided.
maybe this is what you are looking for:
json encode server-side like:
echo json_encode($html);
json parse clientside like
var str = JSON.parse(data);
alert (JSON.stringify(str))
I managed to fix it like this:
Changing the json object to this format
data = { gallery: gallery_name,
files: [
// imagefile,imagefile,imagefile...
]
};
And the using the following php
$resultSet = json_decode($_GET['submittedResults'], true);
$gallery = $resultSet['gallery'];
$files_to_zip = $resultSet['files'];

Parsing JSON data with php - Data coming back empty

I have a piece of JSON that I'm parsing with php. I need to get one of the pieces of data out of it.
Here's the output of the json when I do a print_r:
Array ( [deviceId] => 07a9727e-3fe5-4f44-9765-134388241f39 [programId] => 3895 [serviceId] => 19977 [createdAt] => 2013-12-12T07:19:04.466Z [updatedAt] => 2013-12-12T07:19:04.466Z [objectId] => 7TxmL2GiXq )
Here's my code trying to extract deviceId:
$objectData = json_decode($data, true);
print_r($objectData);
$deviceId = $objectData->deviceId;
$deviceId is coming back empty.
Any help would be appreciated. Thanks.
Do this:
$deviceId = $objectData['deviceId'];
You are using the optional second parameter TRUE in your json_decode call, which converts it into an associative array instead of an object.
Alternatively:
$objectData = json_decode($data);
$deviceId = $objectData->deviceId; // Works

Categories