Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

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

like image 324
kevin Avatar asked Mar 10 '10 17:03

kevin


People also ask

How do I know if request is AJAX request?

mypage. php: if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }

Is AJAX client or server side?

AJAX stands for "Asynchronous JavaScript and XML". It is not exactly a client-side technology, nor a server-side technology: It's both! Ajax is a technique in which websites use JavaScript (client-side) to send data to, and retrieve data from, a server-side script.

How do I know if AJAX request is successful?

You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...

Which method is used to handle an AJAX request in the server side?

Sending Data to the Server By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server.


2 Answers

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"}
});
like image 59
Nick Craver Avatar answered Oct 22 '22 22:10

Nick Craver


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
}
like image 45
freddoo Avatar answered Oct 22 '22 23:10

freddoo