Pass nested object in jquery ajax

17,365

Right now you are just passing an object to the server, without a key. You need to pass the data as a JSON string.

console.log(typeof data); //object
console.log(typeof JSON.stringify(data)); //string

In order to read the data serverside, you need to pass the data as an object literal with a key and a value. Something like this:

data: { dto: JSON.stringify(data) },

On the serverside, you can access the object in different ways, depending on the language.

PHP:

$dto = $_POST['dto'];

ASP.NET:

var dto = HttpContext.Current.Request.Form['dto'];
Share:
17,365
Admin
Author by

Admin

Updated on June 19, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to pass following nested object in ajax using jquery:

    {
       "parent_param1" : [
          {
             "sub_param1" : "sub_val1",
             "sub_param2" : "sub_val2"
          },
          {
             "sub_param1" : "sub_val1",
             "sub_param2" : "sub_val2"
          },
          {
             "sub_param1" : "sub_val1",
             "sub_param2" : "sub_val2"
          }
       ],
       "parent_param2" : "par_val2",
       "parent_param3" : "par_val3"
    }
    

    I'm trying to pass it like following example:

    var url = encodedURL;
    var data = 'Above Object';
    
    $.ajax({            
        type:'POST',
        url:url,
        dataType:'json',
        data:data,
            success:function(res){                      
                  alert('success');                         
        },
        error:function(e){
          alert('error');   
        }                   
    });
    

    I'm getting runtime error as response. I want to make sure that Is that correct way to pass nested object in AJAX using jQuery?