Transfer structured data to php via mail

Suppose I have the following data:

var arr = [], arr1 = [], arr2 = [], arr3 = [], arr4 = []; var a = 'something', b = 'else'; arr1['key1-1'] = 'value1-2'; arr1['key1-2'] = 'value1-2'; for (var i = 0; i < someCond; i++) { arr = []; arr['key2-1'] = 'value2-1'; arr['key2-2'] = 'value2-2'; arr2.push(arr); } 

Now I need to pass the hole to the php script.

I packed it into one variable, for example:

 var postVar = { a: a, b: b, arr1: arr1, arr2: arr2 }; 

I am using jQuery, so I tried to publish it like this:
1)

 //Works fine for a and b, not for the arrays $.post('ajax.php', postVar, function(response){}); 

and this:
2)

 var postVar = JSON.stringify(postVar); $.post('ajax.php', {json: postVar}, function(response){}); 

with php file

 $req = json_decode(stripslashes($_POST['json']), true); 

which also does not work.

How do I structure / format my data to send it to PHP?

thanks

EDIT:
Case 1: console.log (postVar); console.log (postVar)

PHP answer print_r ($ _ POST): array ([a] => something [b] => else)

As you can see, on the php side there are no arrays (objects).

Case 2:
When I add the following:

     postVar = JSON.stringify (postVar);
     console.log (postVar);

I get
{"a": "something", "b": "else", "arr1": [], "arr2": [[], [], []]}
with console.log (postVar)

So this is the problem in this case ... isn't it?

+4
source share
2 answers

As it turned out, although arrays are objects, JSON.stringify ignores properties without an array in arrays. Therefore, I had to explicitly declare all variables as objects. Except arr2, which is really used as an array.

Here is the full code:

 var arr = {}, arr1 = {}, arr2 = []; var a = 'something', b = 'else'; arr1['key1-1'] = 'value1-2'; arr1['key1-2'] = 'value1-2'; for (var i = 0; i < 3; i++) { arr = {}; arr['key2-1'] = 'value2-1'; arr['key2-2'] = 'value2-2'; arr2.push(arr); } var postVar = { a: a, b: b, arr1: arr1, arr2: arr2 }; postVar = JSON.stringify(postVar); $.post('ajax.php', {json: postVar}, function(response){}); 

And on the PHP side:

 $req = json_decode($_POST['json'], true); print_r($req); 


Hope this helps others with the same issue.

0
source

You should check magic_quotes before adding such stripslashes

 if( get_magic_quotes_gpc() ) { $jsonString = stripslashes( $jsonString ); } $data = json_decode( $jsonString ); 

I suggest you turn off magic quotes ... it's not magic at all

0
source

All Articles