JavaScript AJAX

Posting Data

NOTE: POSTing data to a URL which gets rewritten can cause the query parameters to get lost.

Ajax request handler function

/**
 * POSTs an ajax request and handles the json response
 *
 * Takes a URL, the post-data, and a callback function and subclass name.
 * An asynchronous request is sent to the URL and the post-data is sent as query parameters.
 * The server returns a json object with at least these keys:
 *     - json.status = `1`: on app success, `error`: on app error
 *     - json.message = {error message}: on error (required.): {some success message}: on success (can be empty).
 * The original request parameters as well as the response data are passed to the callback function.
 *
 * @param string request_url : The URL to send the request to.
 * @param array request_data : Key-value pair data to send with the request.
 * @param string callback_function_name : The callback function name. Optional.
 * @param string callback_class_name : The callback function's class name. Optional.
 */
function send_ajax_request(request_url, request_data, callback_function_name, callback_class_name)
{
    // Using the jQuery core $.ajax() method.
    $.ajax({
        url:        request_url,
        data:       request_data,
        type:       'post', // Whether this is a POST or GET request.
        dataType :  'json', // The type of data we expect back from the response (JSON).

        // Code to run if the request succeeds:
        success: function(json_response)
        {
            // If the response is not a json object but the request got a 200: the server created invalid output.
            if (json_response == 0) {
                console.log('Ajax response returned `0`. No JSON data.');
            } else {

                // Check for an error message from the application.
                if (json_response.status == 'error') {
                    console.log('Error: ' + json_response.message);
                } else {

                    // if a callback function is defined...
                    if ((callback_function_name != undefined) && callback_function_name != '') {
                        // If a callback class name was defined...
                        if ((callback_class_name != undefined) && callback_class_name != '') {
                            // Call the callback class function and pass it the JSON response.
                            window[callback_class_name][callback_function_name](json_response);
                        } else {
                            // If the callback class name was NOT defined...                        
                            // Call just the callback function and pass it the JSON response.
                            window[callback_function_name](json_response);
                        }
                    }
                }
            }
        },

        // If the request fails: raw request and status codes are passed to this function.
        error: function(xhr, status, error)
        {
            console.log('Ajax request failed!');
            console.log('Status: ' + status);
            console.log('Error: ' + error);
        }
    });
}

// Set some data and call the function.
var data = {};
data['foo'] = 'bar';

// Simple request.
send_ajax_request(
    'http://myurl.com',
    data
);

// Request with callback to a global function.
send_ajax_request(
    'http://myurl.com',
    data,
    'myGlobalFunctionName'
);

// Request with callback to a class-function.
send_ajax_request(
    'http://myurl.com',
    data,
    'myClassFunctionName',
    'myClassName'
);