[asp.net-mvc] Difference Between $.getJSON() and $.ajax() in jQuery

I am calling an ASP.NET MVC action

public JsonResult GetPatient(string patientID)
{
...

from JavaScript using jQuery. The following call works

$.getJSON(
'/Services/GetPatient',
{ patientID: "1" },
function(jsonData) {
  alert(jsonData);
});

whereas this one does not.

$.ajax({
  type: 'POST',
  url: '/Services/GetPatient',
  data: { patientID: "1" },
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('Error loading PatientID=' + id);
  }
});

Both reach the action method, but the patientID value is null w/ the $.ajax call. I'd like to use the $.ajax call for some of the advanced callbacks.

Any thoughts appreciated.

This question is related to asp.net-mvc jquery

The answer is


The only difference I see is that getJSON performs a GET request instead of a POST.


.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

N.B .load, .get and .post are also simple wrappers around the .ajax method.


Replace

data: { patientID: "1" },

with

data: "{ 'patientID': '1' }",

Further reading: 3 mistakes to avoid when using jQuery with ASP.NET


contentType: 'application/json; charset=utf-8'

Is not good. At least it doesnt work for me. The other syntax is ok. The parameter you supply is in the right format.


with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().


There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

Read More .. jquery-post-vs-get-vs-ajax