kevin
kevin

Reputation: 4357

how to detect if a request is ajax or normal on server side

im using jquery to make ajax requests. is it possible to detect if the request is an ajax request or a normal request on the server side? does jquery add any input variables or headers to make this possible?

thanks

Upvotes: 8

Views: 3765

Answers (2)

freddoo
freddoo

Reputation: 6858

If you are using asp.net mvc your controller will have a property IsAjaxRequest simply check for this property

if (IsAjaxRequest) 
{
   // do your stuff and render ajax view
}

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630379

jQuery seconds an additional header on the request when it's ajax header called X-Requested-With with a value of XMLHttpRequest. Check for this header on the request.

Alternatively, set any header you want using .ajaxSetup like this:

$.ajaxSetup({
  headers: {"X-My-Header":"Bob"}
});

Upvotes: 13

Related Questions