Let’s assume, we have more than five forms and in all those forms, we are posting data through AJAX POST methods.

Assumption 1 - We want to pass some value in the header.
Assumption 2 - On success, we want a success message and on error, we want an error message to display.

Now, it's clear that in all POST methods, we need to pass a value in the header and also want to display a message in case of an error and in case of success, as well. Rather than applying the same method separately for all the forms or options while posting, we can create a common.js and can handle all the forms with a single jQuery method. The code is given below-

  1. $("body").bind("ajaxSend", function(elm, xhr, s)
  2. {
  3. if (s.type == "POST") {
  4. var headers = {};
  5. var token = $('[name=__RequestVerificationToken]').val();
  6. xhr.setRequestHeader('__RequestVerificationToken', token);
  7. xhr.error(function() {
  8. alert("A security token error has been occurred. Please try again.");
  9. });
  10. }
  11. });
Whenever an AJAXSend method is called and the type will be POST, the value will be passed in the header of the current POST URL and further code will execute. I have passed a __RequestVerificationToken just for an example as this is just a demo. You may modify it, as per your need.

Examples

You can take an advantage through this in variety, which is up to your logic and requirement.

I believe, the concept is clear to all, as this can be used, where common things are required in our code.

Important

Hope the concept is clear and you like the blog. Happy coding.