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
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.
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.
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.
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
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" } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With