Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ajax beforeSend to modify data

Tags:

jquery

ajax

Let's say I have an Ajax call from jQuery like this:

$.ajax({
   url: myUrl,
   data: myData,
   type:'post'
});

I would like to be able to add to the myData using

$.ajaxSetup({
   beforeSend: function(call){...}
});

The result should be that all ajax calls (both post and get) is modified so if i get an extra parameter IsAjax=true

like image 874
devzero Avatar asked Aug 19 '10 12:08

devzero


People also ask

What is beforeSend AJAX?

The beforeSend function is a pre-request callback function that runs before the request is sent to the server. The beforeSend() function use to set the custom headers and all, it is an Ajax event that triggers before an Ajax request is started.

How do you trigger a change event after AJAX call?

One way to trigger an event is to use the jquery trigger function. Show activity on this post. function changeDate(){ $. ajax({ url, data: data, type: "POST", dataType: "json", success: function(cbdata) { update_table(cbdata); } }); } $('#selector').

Why do we use processData in AJAX?

processData. If set to false it stops jQuery processing any of the data. In other words if processData is false jQuery simply sends whatever you specify as data in an Ajax request without any attempt to modify it by encoding as a query string.

What is the use of 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.


2 Answers

$.ajaxSetup({
  beforeSend: function(jqXHR, settings) {
    settings.data = $.extend(settings.data, {isAjax: true});
    return true;
  }
});

==== UPDATE ====

When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

https://api.jquery.com/jquery.ajax/

As you can see, the setting processData should to be false. So it can be setted when you do request in $.ajax() or globally in $.ajaxSetup().

like image 105
verybadbug Avatar answered Sep 21 '22 01:09

verybadbug


This blog post explains how you can use $.ajaxSetup to add data. It accumulates like $.extend Just do this:

$.ajaxSetup({
  data:{
    isAjax:true
  }
});
like image 42
Mario Avatar answered Sep 21 '22 01:09

Mario