JSON & AJAX - Beginner Needs A Little Advice

I’m learning to use JSON with AJAX. I have the AJAX part down fine. It’s the JSON part I’m unsure about. I’ve searched for some answers to some really simple questions but it seems that everything I find is jQuery or not what I am looking for.

Question: how do I escape JSON data I plan to submit using AJAX via the POST method? Here is my JSON object:


var json_data = 
	{ 
		'band': 'The Beatles',
		'country': 'England',
		'year_formed': '1963',
		'style': 'Rock',
		'members': ['Paul', 'John', 'George', 'Ringo']
	}
	
	data = encodeURIComponent(json_data);

When I do a document.write on the variable data, all it displays is “%5Bobject%20Object%5D”.

So, how do I escape this JSON data so I can submit it to the server? I have the feeling I am not doing something right.

I do not want to use any libraries and am not going to download JQuery or anything from json.org. I am trying to learn this right now. I also am not going to use any built-in browser objects because they are not widely supported yet.

Thank you for your help! :slight_smile:

In modern browsers, you would use the JSON.stringify() method: https://developer.mozilla.org/En/Using_native_JSON

If you only need to support Firefox 3.5 and newish versions of Chrome, Opera and Safari, and IE8 (in standards mode only) and newer, then JSON.stringify is all you need. If you need to support other older things, then you need to find a serializing function to emulate it.

The sensible one to use is obviously json2.js: http://www.json.org/json2.js

I would have a look at the stringify function in there (just strip it out if you want) since it is what the standard JSON.stringify is based on.

There is also a nice-looking (haven’t read it fully) sitepoint article on this, which offers a nice, simple cut-and-paste solution: Cross-browser JSON Serialization in JavaScript » SitePoint

Thanks for the reply, Raffles. With all the hype about using JSON with AJAX, I thought there would be a simple way to prepare the JSON object to be sent. But there isn’t. And maybe that is why I couldn’t find any information about how to do it. Using any native JSON object to do it is not an option since only the most recent browsers support it.

That article you linked to was helpful. I’ll try it out and see how it works.

Thanks. :slight_smile: