Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass accepts header parameter to jQuery AJAX

When I inspect the following code in Chrome Console it shows me a Request header Accept:undefined

jQuery.ajax({         url: _this.attr('href'),         accepts: "application/json; charset=utf-8",              }); }); 

How do I set accept type as JSON. I don't want to set a custom header or use beforeSend

like image 525
aWebDeveloper Avatar asked Sep 10 '12 07:09

aWebDeveloper


People also ask

What are headers in Ajax call?

The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.

What is AJAX call in jQuery?

jQuery ajax() Method The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

How does Ajax return an API call?

The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


2 Answers

Try this ,

$.ajax({        headers: {               Accept: "text/plain; charset=utf-8",              "Content-Type": "text/plain; charset=utf-8"      }        data: "data",       success : function(response) {       // ...   } }); 

See this post for reference:

Cannot properly set the Accept HTTP header with jQuery

like image 153
karthick Avatar answered Sep 19 '22 12:09

karthick


There two alternate ways to set accept header, which are as below:

1) setRequestHeader('Accept','application/json; charset=utf-8');  2) $.ajax({     dataType: ($.browser.msie) ? "text" : "json",     accepts: {         text: "application/json"     } }); 
like image 27
gaurang171 Avatar answered Sep 20 '22 12:09

gaurang171