Namespace: Ajax

WJBRYANT. Ajax

The WJBRYANT.Ajax namespace contains methods that provide common Ajax functionality.
Source:

Methods

<static> request(options) → {boolean}

Sends an Ajax request using the specified options. Ajax requests are sent with a special 'X-Requested-With' header that can be used to identify the requests on the server.
Parameters:
Name Type Argument Description
options Object <optional>
an object containing members specifying the options of the request

Valid members of this object are:
{string}                 [url=location.href]   the url to send the request to

{string}                 [method='GET']        the request method ('GET' or 'POST')

{string|Object|FormData} [data=null]           the data to send with the request

{number}                 [timeout]             the amount of time in milliseconds to wait
                                               for a response before canceling the request.
                                               The onfailure and oncomplete callbacks will
                                               be executed.

{Function}               [onbeforesend]        the function to be executed before the
                                               request is sent. This function is passed the
                                               XMLHttpRequest object as a parameter.

{Function}               [onuploadprogress]    the function to be executed everytime upload
                                               progress occurs (XHR Level 2). This function
                                               is passed the Event object as a parameter.

{Function}               [ondownloadprogress]  the function to be executed everytime download
                                               progress occurs (XHR Level 2). This function
                                               is passed the Event object as a parameter.

{Function}               [onsuccess]           the function to be executed when the response
                                               is received successfully. This function is
                                               passed the XMLHttpRequest object as a parameter.

{Function}               [onfailure]           the function to be executed when the response
                                               is received and the status is not 200 or 304
                                               (an error occurred). This function is passed
                                               the XMLHttpRequest object as a parameter.

{Function}               [oncomplete]          the function to be executed when the response
                                               is received whether or not it was successful.
                                               This function will always be executed after
                                               the onsuccess or onfailure function. This
                                               function is passed the XMLHttpRequest object
                                               as a parameter.
Source:
Returns:
whether or not the request was made successfully
Type
boolean
Example
// these variables do not change with each request,
// so they are set outside of the function
var contactForm = document.getElementById('contactForm'),
    url = contactForm.getAttribute('action'),
    img = document.createElement('img'),
    imgContainer = document.getElementById('submitDiv'),
    submit = document.getElementById('submit');

// preload loading animation image
img.setAttribute('src', '/img/loading.gif');
img.setAttribute('alt', 'Loading...');
img.className = 'loading';
img.setAttribute('width', '16');
img.setAttribute('height', '16');

// send an Ajax request when the form is submitted
contactForm.onsubmit = function () {
    // disable the submit button so the user cannot submit the form
    // again while awaiting a response
    // if Ajax is used, it will be reenabled in the oncomplete callback
    // otherwise, it will remain disabled until the page is updated
    submit.disabled = true;
    imgContainer.appendChild(img);

    return !WJB.Ajax.request({
        url: url,
        // the submit button will not be included with the data
        data: WJB.Ajax.scrape(contactForm),
        timeout: 4000,
        onsuccess: function (req) {
            var response;
            try {
                // we are expecting data formatted as JSON
                response = JSON.parse(req.responseText);

                // in this example, the server will set the
                // message property in the response if the
                // user should be notified of something
                if (response.message) {
                    alert(response.message);
                }
            } catch (err) {} // do nothing if text cannot be parsed
        },
        onfailure: function (req) {
            // check req.readyState
            // if it's not 0, check req.status for more info
            // otherwise, it was aborted (timed out) and req.status is not accessible
            if (req.readyState) {
                alert('Error: Server returned status code ' + req.status);
            } else {
                alert('Error: Request timed out');
            }
        },
        oncomplete: function (req) {
            imgContainer.removeChild(img);
            submit.disabled = false;
        }
    });
};

<static> scrape(form, submit, clickXY) → {string|FormData}

Scrapes the data from a form and encodes it to be sent.
Parameters:
Name Type Argument Description
form Element the form to be scraped
submit Element <optional>
the submit button that was pressed
clickXY number[] <optional>
the x and y coordinates of the image submit that was pressed
Source:
Returns:
the encoded data to be sent - returns false if unable to encode
Type
string | FormData