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

10,845

Solution 1

So I will put my comment as an answer then. If you want to transmit the array to the server side, you could transform it into JSON (at least this would be the easiest way imo).

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

Retrieving on the server side, e.g. with PHP and json_decode:

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

would give you back 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 to rename MyObject to something meaningful which reflects the content of the variable. In fact, you have an array, not an object (yes, I know arrays are objects too).

Solution 2

You don't need to serialize, .ajax with type 'post' send the attributes of "MyObject" like as html POST to your script in 'url' parameter.

For example, in PHP: Use:

$.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'].

Share:
10,845
Matthew
Author by

Matthew

Updated on June 06, 2022

Comments

  • Matthew
    Matthew almost 2 years

    I have an object that I want to send with my jquery.ajax function but I can't find anything that will convert it to the serialized 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"
      }
    ]