Handle Multiple AJAX POST Methods Through A Single Code Using JQuery

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 display an alert in case of success.
  • You can redirect on a particular page.
  • You can create some fields.
  • You can also work conditionally with the errors, using error status.
  • Set value of some fields.

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

  • AJAX methods will be separate, Do not confuse.
  • Sometimes bind() method doesn’t work and in its place, on() method has been used. This is just because of jQuery version compatibility. Please check your jQuery version first and then apply the alternative method for the same. In this case, syntax may differ among all the options.

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

Ebook Download
View all
Learn
View all