softshipper
softshipper

Reputation: 34081

Detect if is an AJAX requests

How can I detect, if a request is an AJAX or not?

Would checking

req.Header.Get("X-Requested-With")

work for all browser?

Upvotes: 2

Views: 1420

Answers (1)

sunshinekitty
sunshinekitty

Reputation: 2375

Unfortunately "X-Requested-With" is not always reliable. If you are in control of making the Ajax call you may use the beforeSend function to ensure this is set:

$.ajax({
    url: "http://localhost/url",
    data: { signature: authHeader },
    type: "GET",
    beforeSend: function(xhr){xhr.setRequestHeader('X-Requested-With', 'xmlhttprequest');},
    success: function() { alert('Success!' + authHeader); }
});

You may then check if req.Header.Get("X-Requested-With") == 'xmlhttprequest'

Upvotes: 3

Related Questions