How to convert an object to serialized data syntax in jquery.ajax function?

I have an object that I want to send using my jquery.ajax function, but I can not find anything to convert it to the format I need.

$.ajax({ type: 'post', url: 'www.example.com', data: MyObject, success: function(data) { $('.data').html(data) } }) MyObject = [ { "UserId": "2", "UserLevel": "5", "FirstName": "Matthew" }, { "UserId": "4", "UserLevel": "5", "FirstName": "Craig" } ] Serialized_format = [ { "name": "UserId", "value": "5" }, { "name": "UserLevel", "value": "4" }, { "name": "FirstName", "value": "Craig" } ] 
+4
source share
2 answers

So then I will post my comment as an answer. If you want to transfer the array to the server, you can convert it to JSON (at least that would be the easiest imo way).

Use JSON :

 $.ajax({ type: 'post', url: 'www.example.com', data: {paramter: JSON.stringify(MyObject)}, success: function(data) { $('.data').html(data) } }); 

where parameter is the name of the POST parameter you want to use.

JSON.stringify will give you a string like:

 '[{"UserId":"2","UserLevel":"5","FirstName":"Matthew"},{"UserId":"4","UserLevel":"5","FirstName":"Craig"}]' 

Getting server side, for example. with PHP and json_decode :

 $data = json_decode($_POST['parameter']); 

will give you an array of objects:

 Array ( [0] => stdClass Object ( [UserId] => 2 [UserLevel] => 5 [FirstName] => Matthew ) [1] => stdClass Object ( [UserId] => 4 [UserLevel] => 5 [FirstName] => Craig ) ) 

I also suggest renaming MyObject to something meaningful that reflects the contents of the variable. Actually you have an array, not an object (yes, I know that arrays are also objects).

+7
source

You do not need to serialize .ajax with the type 'post' to send the attributes "MyObject", for example html POST, to your script in the parameter "url".

For example, in PHP: Using:

 $.ajax({ type: 'post', dataType: 'json', url: 'www.example.com/receive.php', data: { param1: 'test', param2: 123456 }, success: function(data) { $('.data').html(data) } }) 

In receive.php, I have $_POST['param1'] and $_POST['param2'] .

+1
source

Source: https://habr.com/ru/post/1335892/


All Articles