Click here to Skip to main content
15,885,435 members
Articles / JSON
Article

Sending js Array object in jQuery Ajax post

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL1 min read 10.4K   1  
The post name should be “Serializing to JSON in jQuery” or something like that but I kind of twisted it the way I faced this issue. If you’re looking

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

The post name should be “Serializing to JSON in jQuery” or something like that but I kind of twisted it the way I faced this issue. If you’re looking for how to do the ajax calling in jQuery and blah da… then you should keep googling cause this post ain’t come any help on that. This post is basically about how to send an Array object as perameter in jQuery ajax calling.

You must know how to serialize an object to JSON in ASP.NET Ajax, but if we need to send an array from the client I couldn’t find any Microsoft-specific way to do that.

The specific situation – We have an array defined in javascript something like this:

var cities = new Array();
cities[0] = ‘dhk’;
cities[1] = ‘ctg’;

and then we need to turn this into a string to pass to $.ajax() like this:

$.ajax({
type: “POST”,
url: “Cities.aspx/GetCities”,
data: “{‘cities’:['dhk','ctg']}”,

There are a number of JSON libraries out there, but you might want to try the jQuery plugin written by Mark Gibson to avoid introducing a new dependency.
http://jollytoad.googlepages.com/json.js
It adds the two functions:$.toJSON(value), $.parseJSON(json_str, [safe]) to parse your object into JSON.

So basically this is what you would do.
- Create your array and serialize it into JSON
- Send it to your web-method.
- Receive it in server side as string with comma delimiter.
- Split the string and put the values into an array object.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --