Send JSON to the server using jQuery

toomuchcs picture toomuchcs · Nov 7, 2010 · Viewed 11.8k times · Source

I have the need to send an array of ID's to my server-side in the form of a JSON Object.I am using a dropdownlist where multiple values can be selected to do an action with them.

To get them in an array, I've used:

var selectedArray = [];

            var selectObj = document.getElementById('addedList');
            var i=0;
            var count=0;
            for(i=0;i<selectObj.options.length;i++){
                selectedArray[count] = selectObj.options[i].value;
                count++;
            }

Now the question is, I need to get those ID's to the server. I've always thought of sending it like a JSON object, since it has a variable amount of parameters. As far as I found out, you can convert a JS object to JSON.

Now I do have a few questions:

Could you give me an example of how to convert it? There seem to be a million ways, one of them being JSON.stringify(jsObj);. My object would simply consist of an array of values. As far as I know this would be an example:

{ array : ["value1","value2","value3"] }

Another question is: How can I send this using jQuery? Can I send a JSON object to the server using $.getJSON? (This uses $.GET under the hood), or do I need to use $.POST ?

Now I've just been trying, but can't get it out...

$.getJSON code

        $.getJSON("removerequest.htm",{ ids: JSON.stringify(selectedArray) }, function(data){
            $('#removerequestdiv').text('');

            $('#removerequestdiv').append('<select name="addedList">');
            for(var index in data){
                $('#removerequestdiv').append('<option value="' + data[index].id + '">' + data[index].voornaam + data[index].familienaam + '</option>');
            }
            $('#removerequestdiv').append('</select>');
        });

Answer

Pointy picture Pointy · Nov 7, 2010

The $.getJSON() routine is for fetching JSON-encoded content from the server. Your problem is the opposite: you want to send it to the server.

You should understand the terminology here. There's no such thing really as a "JSON object" in Javascript. It's just a Javascript object of some sort, and there's nothing special about it in that sense. What you want to do is serialize the Javascript object into a single string. That string is your parameter you'll send to the server, and the server will deserialize that string back into an object (in the context of whatever language your server code is using).

Thus, when you call JSON.stringify(obj), what you get is just a string. Passing such a string back to the server is no different than passing any other string; it's just a parameter. Use $.post() to post it, or you can even just stuff it into the value of a simple form input element and post a form the old-fashioned way.