Call a function after multiple AJAX requests


SUBMITTED BY: YouKnowNothing

DATE: Jan. 11, 2016, 1:09 p.m.

FORMAT: JavaScript

SIZE: 1.8 kB

HITS: 6222

  1. //A function that handles multiple AJAX requests
  2. function AjaxMultiple(ajaxArray, callback){
  3. //Set the callback
  4. this.callback = callback;
  5. //A function that handles the callback from the requests
  6. this.CallbackHandler = function(){
  7. this.amount -= 1;
  8. if (this.amount === 0) this.callback();
  9. }
  10. //A variable that is used to indicate how many requests are remaining to be completed
  11. this.remain = ajaxArray.length;
  12. for (var i = 0; i<this.remain; i++){
  13. //Current object
  14. var ajax = ajaxArray[i];
  15. //Note: _this is used as the property "this" changes within $.post and $.get
  16. var _this = this;
  17. //Specify file directory (optional)
  18. ajax['name'] = "php/"+ajax['name']+".php";
  19. if (ajax['parameters']){
  20. //Handle post request
  21. $.post(ajax['name'], ajax['parameters'], function(xhr){
  22. ajax['callback'](xhr);
  23. _this.CallbackHandlerl();
  24. });
  25. } else {
  26. //Handle get request
  27. $.get(ajax['name'], function(xhr){
  28. ajax['callback'](xhr);
  29. _this.CallbackHandler();
  30. });
  31. }
  32. }
  33. }
  34. //Example usage
  35. //Ajax array containing 2 requests, one GET and one POST
  36. var ajaxArray = [
  37. //A GET request that obtains the current server time
  38. {
  39. name:"serverTime",
  40. callback:function(xhr){
  41. console.log("The current server time is "+xhr);
  42. }
  43. },
  44. //A POST request that obtains the user email from the userId
  45. {
  46. name:"userEmail",
  47. params:{
  48. userId: 34
  49. },
  50. callback:function(xhr){
  51. console.log("Your email is "+xhr);
  52. }
  53. }
  54. ];
  55. //Actual call to function
  56. new AjaxMultiple(ajaxArray, function(){
  57. console.log("All tasks completed");
  58. });
  59. /*
  60. Output:
  61. ==================================
  62. The current server time is 12:05
  63. Your email is xxxxxxx@gmail.com
  64. All tasks completed
  65. ==================================
  66. */

comments powered by Disqus