getButterfly Logo

Same-Origin AJAX Request Using Vanilla JavaScript

This JavaScript function will send an AJAX request – GET or POST – with no third-party dependencies:

function soQuery(soMethod, soUri) {
    var xhttp = new XMLHttpRequest();, soUri, true);

    if (soMethod === 'GET') {
    } else if (soMethod === 'POST') {
        xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhttp.onload = function () {
            // do something to response

// Usage
soQuery('GET', '');

Note that the URL should be on the same domain as the function caller.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Leave a Reply

Subscribe to our mailing list