8

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?

3
  • 1
    Runtime error is because of the Server Side response. Not because of your script. And you script is working fine. Try posting the URL's response, so that we can try meddling with it. Commented Feb 14, 2013 at 13:39
  • Is it an option to JSON encode it before you send it? Don't think it's possible out of the box with jQuery. You can pass object with arrays, but not object with objects. (example 3 here: api.jquery.com/jQuery.get) The parameters should be encoded as parent_param1[sub_param1]=sub_val1&parent_param1[sub_param2]=sub_val2&... so you could create a function that generates a string like that. Commented Feb 14, 2013 at 13:43
  • Guys is my method is correct to pass nested object by ajax jquery? Commented Feb 14, 2013 at 13:56

2 Answers 2

8

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

To retrieve the data in PHP, you would need to json_decode it. $dto=json_decode($_POST['dto'], true); echo $dto['parent_param1']['sub_param1']; // outputs sub_val1
0

I believe the issue you're having is that you are trying to post the object itself. You'll want to post the value as a string and then decode on the object on the server side. A similar issue here:

jQuery $.post() JSON Object

JQuery post JSON object to a server

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.