Nested maps in jQuery ajax data to submit - how to serialize "correctly"?
var location = { "location" : {
"name" : $("#user_loc_name").val(),
"street_address" : $("#user_loc_street_address").val(),
"city" : $("#user_loc_city").val(),
"province" : $("#user_loc_province").val(),
"country" : $("#user_loc_country").val(),
"postal_code" : $("user_loc_postal_code").val(),
"public" : $("#user_loc_public").attr('checked')
}};
( ... )
$.post(url, location, success_callback);
The reason I need this "nested" map is because I am posting it to my backend on rails and I hope I can do simple updates to _ attributes (params [: location]) in the controller. Unfortunately with this solution I get the parameters:
{"location"=>"[object Object]", ...}
Not what I hope for. I hope that:
{"location"=> {"name" => "valforname", "street_address" => "valforstreetadress", ...}, <other params>...}
If I get rid of the "nesting" and just post the internal map, it works great, but each attribute appears separately in the params hash and is just cumbersome and messy. If I could get the whole map nested under the "location" key it would be much nicer.
+2
source to share
2 answers
jQuery does not support OOTB JSON serialization. Try any number of libraries. Here's the standard one :
<script src="http://www.json.org/json2.js"></script>
Then your code looks like this:
$.post(url, JSON.stringify(location), success_callback);
+1
source to share