Remove specific request headers set in jQuery.ajaxSetup - javascript

I setup some custom headers using
$.ajaxSetup({
headers : {
'x-custom' : 'value'
}
});
It will addx-custom header for all the ajax request. But I want some specific requests to NOT contain this header.
I tried this, delete header from ajaxSettings before that ajax call and add it back when its completed
delete $.ajaxSettings.headers["x-custom"];
$.ajax({
...
"success": function (data) {
$.ajaxSettings.headers["x-custom"] = 'value';
...
}
});
But I feel this is not the correct way, as the request that fired before finishing that call will not get that header. What else can I do please suggest.
Should I add the header back in the next line after $.ajax instead doing it in callback?

Since this question doesn't have any answer that can be marked as Accepted. I am posting the solution.
Looks like adding back the header immediately after the AJAX call would make sense. This way we won't be waiting for success callback and then adding it.
delete $.ajaxSettings.headers["x-custom"]; // Remove header before call
$.ajax({
...
"success": function (data) {
...
}
});
$.ajaxSettings.headers["x-custom"] = 'value'; // Add it back immediately

You could add an ajaxComplete function. It will run after all your ajax requests and do whatever you wish.
Something like this,
$(document).ajaxComplete(function(event, xhr, settings) {
// Add the headers again.
$.ajaxSetup({
headers : {
"x-custom" : "value"
}
});
}
});
You can find the documentation here.
Also, as of jQuery 1.8, the .ajaxComplete() method should only be attached to document.

Related

Bind event to jQuery.post and callbacks

I am using jQuery.post a lot in my project and every time the browser sends a post request, I want to show a preloader while the request is in process and then stop the preloader when i get the reply form the server:
var params = {'action':'get_customer_info', 'customerID':4};
preloader.start();
$.post('ajax/url', params, function(response){
preloader.stop();
responseHandler(response);
});
Instead of adding the preloader.start() and preloader.stop() lines every time I call jQuery's post, I'd like to bind/trigger events on before the jQuery.post as well on the success/fail handlers.
I know how to bind and trigger events in general, but I'm not sure how I would do this with the $.post and handlers.
How do I do this?
You could set up the global ajax events, that way the preloader shows on every ajax request
$(document).ajaxSend(function() {
preloader.start();
}).ajaxComplete(function() {
preloader.stop();
});
Or you could create your own post function
function post(url, params) {
preloader.start();
return $.post('ajax/url', params, function(response){
preloader.stop();
});
}
To be used like
post('ajax/url', params).done(function(response) {
responseHandler(response);
});

Intercepting AJAX Calls

I'm currently facing problem intercepting AJAX Calls.
I know how I can somehow intercept AJAX Calls at some level by ajaxSetup().
But I have one question: ajaxSetup() intercepts all calls within the document. I DON'T WANT TO DO THAT.
What I'm really trying to do is changing the default type 'GET' to 'POST' of some calls. And for that I need to use ajaxSetup(). Is there any way how can I 'setup' only selected or 'ajax calls which follow a certain URL pattern'?
Thank you.
Use beforeSend in $.ajaxSetup()
$.ajaxSetup({
beforeSend: function (jqXhr, settings) {
settings.type = settings.url.indexOf("foo") > -1 ? "POST" : "GET"
}
});
GET request changed to POST -> fiddle
(check the network panel for the changed submission method)

Need to call one javascript function before all ajax and jquery post function

I have various function with the ajax and $.post syntax which gives call to the server function. But when session gets expired and page is not refreshed my ajax code wont work. In this I want to redirect the page to login controller.
As it this is ajax call my redirection code is not working.
Is there any code or JavaScript/jQuery function which gets executed before any other jquery ajax and post function.
I am using PHP(Yii framework) on server side.
Please let me know. Thank you.
You can use the "beforeSend" ajax event where you can check you session and if it's expired you can do something else:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
Check this for more info: http://api.jquery.com/Ajax_Events/
jQuery provides a set of AJAX events you can listen during request lifecycle. In your case you can subscribe to ajaxError event triggered on document to react when requests failed as unauthorized:
$(document).on('ajaxError', function(el, xhr) {
if (xhr.status == 401) {
alert('Unauthorized');
}
});
This code can solve your problem.
$(document).bind("ajaxSend", function(){
//DO Someting..
});
Note beforeSend is local event and ajaxSend is global event
/***
* Global Ajax call which gets excuted before each $.ajax and $.post function
* at server side chk session is set or destroy
***/
$(document).on('ajaxStart', function()
{
$.post( BASEURL+"/login/chkLogin",
{},
function(data)
{
if (data == 'login') {
window.location = BASE_URL+'/login'; //Load the login page
}
else
{
//alert('all okay! go and execute!');
//No need to write anything in else part
//or can say no need of else block
//if all okay normal ajax action is processed
}
});
});
This is what I want. working perfectly for my functionality. Thank you for all answers and comments. I got a big reference from you.
use ajaxComplete event.
$( document ).ajaxComplete(function() {
window.location.href = "/login";
});

jQuery ajax overwrite data/url beforeSend on specific url

Question
I wanna set a ajax setting for global ajax handled by jQuery
Condition:
If ajax url is 'www.example.com', the data (querystring or body) will append token.
I tried two method
.ajaxPrefilter
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
// Add data to ajax option
if (options.url.match(/www\.example\.com/i) !== null) {
originalOptions.data.token = 'i_am_token'
}
});
To add token when url is www.example.com-> it not work!
In console/debugger originalOptions Object is added token property,
but request sent not having token parameter
.ajaxSetup / beforeSend Event
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
// Only GET Method
if (settings.url.match(/www\.example\.com/i) == null){
settings.url.replace(/((\.\/[a-z][0-9])*\?+[=%&a-z0-9]*)&?token=[a-z0-9]*&?([=%&a-z0-9]*)/gi, "$1$3")
}
},
data: {
token: 'i_am_token'
}
});
And a reverse resolution, add token for each ajax request.
Same as last one, settings.url changed by string replace in the console/debugger.
But request still sent original url.
Test in jsfiddle: http://jsfiddle.net/qVLN2/2/
Thanks for your reading and help :)
You should notice that the String.replace function doesn't affect the original string!
You can try using settings.url = settings.url.replace(....); in your code.

JQuery Ajax POST throwing an empty error without making the request

I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers

Categories