JS post Object via JSON - php

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

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']
}
}
}

JQuery, Ajax, Json, PHP multidimensional associative array

I am trying to loop through a multidimensional associative array retrieved via jquery/ajax from a php file.
The php array looks like this:
$pink = array ( "newarray" => array
( "varietyOne" => array
("name" => "Poublout", "year" => 2002),
"varietyTwo" => array
("name" => "Gerarde", "year" => 2003),
"varietyThree" => array
("name" => "Encore", "year" => 1956),
"varietyFour" => array
("name" => "Toujours", "year" => 1957),
"varietyFive" => array
("name" => "J'aime", "year" => 1958),
"varietySix" => array
("name" => "Alisee", "year" => 2001)
),
"varNumber" => array
("varietyOne",
"varietyTwo",
"varietyThree",
"varietyFour",
"varietyFive",
"varietySix"
)
);
print json_encode($pink);
The js looks like this:
$(document).ready(function () {
$('.clicker').click(function () {
$.ajax({
type: 'GET',
url: 'another.php',
dataType: 'json',
success: function (brandon) {
for (var i = 0; i < brandon.newarray.length; i++) {
var catName = brandon.varNumber[i];
for (var wineName in brandon.newarray[i][catName]) {
console.log(branond.newarray[i][catName][wineName]);
}
}
}
});
});
});
And here is the json rather than the php:
{"newarray":
{"varietyOne":{"name":"Poublout","year":2002},
"varietyTwo":{"name":"Gerarde","year":2003},
"varietyThree":{"name":"Encore","year":1956},
"varietyFour":{"name":"Toujours","year":1957},
"varietyFive":{"name":"J'aime","year":1958},
"varietySix":{"name":"Alisee","year":2001}},
"varNumber":
["varietyOne","varietyTwo","varietyThree","varietyFour","varietyFive","varietySix"]}
I've tried several different loops, changing my array values, but I can't make anything work. I can call an individual key=value pair in the array, but I can't get it to loop through all values.
Thank you.
And the results of console.log(brandon)
Object { newarray={...}, varNumber=[6]}
newarray
Object { varietyOne={...}, varietyTwo={...}, varietyThree={...}, more...}
varietyFive
Object { name="J'aime", year=1958}
varietyFour
Object { name="Toujours", year=1957}
varietyOne
Object { name="Poublout", year=2002}
varietySix
Object { name="Alisee", year=2001}
varietyThree
Object { name="Encore", year=1956}
varietyTwo
Object { name="Gerarde", year=2003}
varNumber
["varietyOne", "varietyTwo", "varietyThree", 3 more...]
0 "varietyOne"
1 "varietyTwo"
2 "varietyThree"
3 "varietyFour"
4 "varietyFive"
5 "varietySix"
So, the loop now outputs to console, but I want the text to be displayed on my site. Normally I use a $('#somediv').append(brandon.(whateverelse); and the information will appear. In this case it does not.
You shouldn't need the varNumber array.
All you need is:
for (var index in brandon.newarray) {
console.log(index);
console.log(brandon.newarray[index]);
console.log(brandon.newarray[index]['name']); // or brandon.newarray[index].name
console.log(brandon.newarray[index]['year']); // or brandon.newarray[index].year
}
In this case, index will be varietyOne, varietyTwo, etc.

Jquery serialize to PHP array

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
)

How can I post a JSON multi-dimensional data via Jquery.post?

How can I post a JSON multi-dimensional data via $.post? For instance, I have this multi-dimensional array in JSON format:
{
"file":
{
"name" : "1024x768.jpg",
"type" : "image\/jpeg",
"tmp_name" : "C:\\wamp\\tmp\\php8F59.tmp",
"error":0,"size":469159
}
}
I will use Jquery.post() to post the JSON data.
$.post("process.php",'{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}',function(xml){
});
So I can get this array in process.php using print_r($_POST):
Array
(
[file] => Array
(
[name] => 1024x768.jpg
[type] => image/jpeg
[tmp_name] => C:\wamp\tmp\phpA1.tmp
[error] => 0
[size] => 469159
)
)
Is this possible?
Try this:
$.post("process.php",{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}},function(xml){
});
that should give you the desired array on the php side
Edit: this works since jQuery 1.4 and above
$jsonArray ='{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}';
$arr = JSON.stringify($jsonArray);
$.post("/url",{data:$arr},function(){
});
in the php file do
$json = json_decode($_POST['data']);
print_r($json);
Edit
may be this will help, i have not tested it though...
var file=[];
file["name"]="1024x768.jpg";
file["type"]="image/jpeg";
file["tmp_name"]="C:\wamp\tmp\phpA1.tmp";
file["error"]="0";
file["size"]="469159";
var myObject = new Object();
var enumm=["name","type","tmp_name","error","size"];
function getEnum(index){
return enumm[index];
}
$.each(file,function(i,j){
myObject[getEnum(i)]=file[getEnum(i)];
});
$.post("/url",{data:$.param(myObject)},function(xml){
});
on the php side do
$json = parse_str($_POST['data'], $data);
print_r($json);

How use json in php with a 'complex' structure?

i want use json + php for my data. I read more document to do this, and the basic function are json_decode() and json_encode(). My problem is that, read more document and read different example of structure have created in me a lot of doubts.
I want create a structure like this begine from the basic to the container:
there is a Base, that have 2 property: id and value
there is a Operations that can have multiple Base
there is a Command that can have multiple Operations (and if possible a property callad name)
the structure in my mind is like this...
[ //The start of Commands
//Can make a property name here like "name":"puls1"
[ //Operation1
{ //Base1
"id":"22398",
"value":"255"
},
{ //Base2
"id":"22657",
"value":"80",
},
{ //Base3
"id":"7928",
"valore":"15"
}
],
[ //Operation2
{ //Base1
"id":"22398",
"value":"0"
},
{ //Base2
"id":"22657",
"value":"0",
},
{ //Base3
"id":"7928",
"valore":"0"
}
],
] //The close of Commands
But i have put the [ and { in the not correct order i think...
How can i make a json structure like this? And after set a command to insert a new Operation or remove Operation?
Thank's at all..
//Ok by answer of i made this code
class Base
{
var $i;
var $value;
function __construct($i,$v)
{
$this->id = $i;
$this->value = $v;
}
}
$a = new Base('1','11');
$b = new Base('2','10');
$c = new Base ('3','20');
$d = new Base ('4','30');
class Operation
{
var $name;
var $values = Array();
function __construct($a)
{
$this->name = $a;
}
public function addArray($a)
{
array_push($this->values,$a);
}
}
$oper1 = new Operation("op1");
$oper1->addArray($a);
$oper1->addArray($b);
$oper2= new Operation("op2");
$oper2->addArray($c);
$oper2->addArray($d);
$commands = Array($oper1,$oper2);
echo json_encode($tot);
Now the problem is how can i make the revert operation? Such a use of json_decode and incapsulate in its appropriate structure?
The json list type [] is equal to a array without keys in php.
The json dictionary type {}is equal to a keyed array in php.
What you want is something like this:
$json = array(
array(
array('id' => $num, 'value' => $val), // Base 1
array('id' => $num_1, 'value' => $val_1), // Base 3
array('id' => $num_2, 'value' => $val_2), // Base 2
),
array(...),
array(...),
);
If you're working with PHP I would construct the objects from native PHP Classes (json_encode works with php objects as well):
class Base {
var $id;
var $value;
}
Then it's just a matter of putting these objects in various arrays, which you can also abstract with methods like addToOperation($baseObj) and addToCommands($operationObj).
You're dealing with native data structures (Arrays), so you can use native methods to remove (array_pop) and add (array_push) data.
Something like this should work
// Build up your data as a mulitdimensional array
$data = array(
'operations' => array(
0 => array(
'bases' => array (
0 => array(
'id' => '22398',
'value' => 'whatever'
),
1 => array(
'id' => 'id goes here',
'value' => 'value goes here'
),
1 => array(
//data for operation 2
)
);
// Then use json_encode
$json = json_encode($data);
My syntax may not be perfect but that should give you the idea. To access it then you would use code like
$operations = json_decode($data);
foreach ($operations as $op) {
foreach ($op->bases as $base) {
//Logic goes here
}
}
Hope this helps.

Categories