Pulling your JSON data from a file is a pretty straight forward process. Usually most of my AJAX requests are run through jQuery’s shorthand $.get() or $.post() functions. What I’ve come across, many times, is that these functions allow me to write my requests fast enough that I end up forgetting to declare my expected return datatype.

With the $.ajax() function you define your data type wherever you want, before or after your callback functions. With the shorthand versions you are stuck declaring your data type last.

$.get('json.php', function(data){
	$(data).each(function(key, value){
    	// Use the JSON Data
    }, 'json');
});

Of course if you get into a bad habit of not declaring your datatypes you’re leaving yourself open to the infamous “undefined” error. This is basically because jQuery doesn’t know how to parse the data.

This has saved me a bit of time in, and squashed some headaches, the past.

2 Comments

Namari Posted: Jul 07, 2011 @ 5:53am

Extremely helpful arctile, please write more.

Stuart Posted: Jul 12, 2012 @ 12:07am

This is a good tip, I’m always confusing the various $.ajax(), $.post() $.get() $.json() methods…

Leave a Reply: