ajax custom plugin

by nsshrinivasan

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>JS Fiddle Ajax component example</title>
        <style>
            article, aside, figure, footer, header, hgroup, 
            menu, nav, section { display: block; }
            .hidden { display: none; }
        </style>
    </head>
    <body>
        <div id="message" class="hidden" ></div>
        <div id="loading" class="hidden" >LOADING...</div>
        <p id="hello">Hello World</p>
    </body>
</html>

JavaScript

// we 'define' undefined to alleviate concerns
// that someone may have done something stupid
// like this in code before this code executes:
// undefined = "Im now defined.";
// credit: Ben Alman
var mySiteAjax = ( function( $, undefined ) {
  return (
    function( params ) {

      // use extend to merge our defaults with parameters
      // passed by function caller
      var settings = $.extend({
        url: "",
        spinner: undefined, 
          // use empty object if version 1.3.2-
          // credit: Ben Alman (see comments)
        dataType: "html",
        type: "GET",
        cache:    false,
        success:  function(){},
        errorMsg: "Oops. Sorry about that." 
          // credit: rmurphey (see comment below)
      }, params),
          retries = 0; // setting up retries variable
     // setting up a function that we can call recursively
     // to retry ajax calls 
     function ajaxRequest ( ) {
 
        $.ajax({
          beforeSend: function() { 
            $( settings.spinner ).show();
          },
          url: settings.url,
          type: settings.type,
          data: settings.data,
          dataType: settings.dataType,
          success: settings.success,
          complete: function() {
            $( settings.spinner ).hide();
          },
          error: function( xhr, tStatus, err ) {
            if( xhr.status === 401 || xhr.status === 403 ) {
              //redirect action here
            } else if ( xhr.status === 504 && !retries++ ) {
              //make our recursive request
              ajaxRequest();
            } else {
              $(document).trigger( "ui-flash-message", 
                [{ message: settings.errorMsg }] );
            }
          } // end error handler
        }); // end $.ajax()
      }; // end ajaxRequest() 
      
      // call our ajax request function. notice above
      // that we only define the function. here we make
      // the original call.
      ajaxRequest();
        
    }...