JQuery

From The Travis van der Font Wiki
Jump to: navigation, search

AJAX (Asynchronous JavaScript & XML) Request Example

const objectValue = {
    value: document.getElementById('input_item').value
};

var form_id = 'test_form';

var functionValue = function ()
{
    var _checkbox_item        = [];
     _checkbox_item['yes'] = document.getElementById(form_id).elements['checkbox_item[]'][0];
     _checkbox_item['no']  = document.getElementById(form_id).elements['checkbox_item[]'][1];

    if (_checkbox_item['yes'].checked === true)
    {
        return true;
    }

    return false;
};

$.ajax(
{
    url:     'test.php',
    method:  'POST',
    data: {
        booleanValue:                         true,
        stringValue:                         'test',
        integerValue:                         123,
        objectValue:                          objectValue
        functionValue:                          functionValue
    },
    success: function (resultData)
    {
        console.log('Save Complete');
}
}).done(function ()
{
   console.log('AJAX Request is done.');
}).fail(function (jqXHR, textStatus)
{
   console.log('Request failed: '+textStatus);
});
Functional Example
// <input type="text" data-attr="example">

$('[data-attr="example"]').change(function (eventData)
{
    AJAXrequest('/api/example', {data:eventData.target.value}, function (data)
    {
        console.log('success!');
    });

    // AJAXrequest('/api/example', JSON.stringify(json_data), function (data) { ... }, 'application/json');
});

function AJAXrequest(url, postedData, callback, content_type)
{
    content_type = content_type || 'application/x-www-form-urlencoded; charset=UTF-8';

    $.ajax(
    {
        type:       'POST',
        url:         url,
        contentType: content_type,
        data:        postedData,
        dataType:    'json',
        success:     callback
    });
}

For the jQuery API. Please see JavaScript APIs.

Note: To display a JSON Content Type POST method through PHP: var_dump(json_decode(file_get_contents('php://input')));