Passing nested object in jquery ajax

I want to pass the following nested object to 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 am trying to pass it like the 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 am getting a runtime error as a response. I want to make sure this is the correct way to pass a nested object to AJAX using jQuery?

+3


source to share


2 answers


For now, you just pass the 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

      

To read data servers of data, you need to pass data as an object literal with key and value. Something like that:

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

      

On the backend server, you can access an object in different ways depending on the language.



PHP:

$dto = $_POST['dto'];

      

ASP.NET:

var dto = HttpContext.Current.Request.Form['dto'];

      

+6


source


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

jQuery $ .post () JSON Object



JQuery post JSON object to server

0


source







All Articles