April 10, 2012

$.ajaxSetup does not set content type for Get requests

Question by Deeptechtons

Code 1


Request Response for Code1

Code 2

   contentType: "application/json",
   dataType: "json"


Request Response for Code 2

Code1 effectively sets both the content-type and datatype
Code2 does not set the content-type Is this Intended or Have i to do Voodoo stuff for making it work ?

Answer by Kevin B

I would just create a quick wrapper for the ajax method.

$.myAjax = function(url,data){
    return $.ajax({
        contentType: "application/json",
        url: url,
        data: data || {},
        type: "GET",
        dataType: "json"
// used with

The reason that the header isn’t getting passed is that if the contentType isn’t specified for the given request and there is no data, the contentType is not set. It may be a bug since the contentType was set in the ajaxSetup, but I’m not positive on that.

Answer by Starx

$.ajaxSetup hold the default options for most of the all ajax request, but does not send an ajax request it self.

But $.ajax is the actual function that sends the request.

On Code 1:

It simply sends a GET Ajax request with comprehensive method $.ajax()

On Code 2:

The default options for all the ajax request are set before any request are sent. Then when the actual request is made using $.get, this parameters no longer have to be defined.


This seems to be a bug. Such problem occurs when you are sending $.get request without any data. Check here. You need to see the request headers using firebug or similar.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!