Shortcuts for Ajax calls in Jquery

This post should help a lot of people starting in jQuery and javascript. For ease of reference, I have borrowed code present in the ajax jquery docs.

The standard way in jQuery to make an ajax call is by using,

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

This gives you an infinite number of tweaks that’s available (all documented here). But, the truth is 90% of the time you do not need these extra options. So, here are a few shortcut functions that allows us to write even less with jQuery.

$.post

Let’s take an example use of $.post:

$.post('bam_data_processor.jsp', 'processAll=true', function(data) {
  $('#hadoop_result').html(data);
});

This is shorthand for,

$.ajax({
  type: 'POST',
  url: 'bam_data_processor.jsp',
  data: 'processAll=true',
  success: function(data) {
  $('#hadoop_result').html(data);
}),
});

$.get

Now, let’s take an example use of $.get:

$.get('bam_stored_configs.jsp', function(data) {
  $('#hadoop_result').html(data);
}, "json");

$.get is shorthand for

$.ajax({
  url: 'bam_data_processor.jsp',
  success: function(data) {
    $('#hadoop_result').html(data);
  }),
  dataType : "json"
});

$.getJSON

An even shorter method for dealing with JSON is.

$.getJSON('bam_stored_configs.jsp', function(data) {
  $('#hadoop_result').html(data);
});

which is shorthand for:

$.get('bam_stored_configs.jsp', function(data) {
  $('#hadoop_result').html(data);
}, "json");

It’s really great that the jQuery devs introduce conveniences like these to write even less code. HTH.

One thought on “Shortcuts for Ajax calls in Jquery

  1. Pingback: JavaPins ~

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s