Same-Origin AJAX Request Using Vanilla JavaScript

Ciprian on Tuesday, January 9, 2018 in AJAX and Fetching Data

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

This JavaScript function will send an AJAX request – GET or POST – with no third-party dependencies. I find it more reliable and flexible than the Fetch API. If my request is not promise based, or I don’t need to doany synchronous operations, then the function below is the best choice.

function so_query(so_method, so_uri) {
    let xhttp = new XMLHttpRequest();

    xhttp.open(so_method, so_uri, true);

    if (so_method === 'GET') {
        xhttp.send();
    } else if (so_method === 'POST') {
        xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhttp.onload = function () {
            // Do something with the response
            console.log(this.responseText);
        };
        xhttp.send('param1=param1value&param2=param2value&param3=param3value');
    }
}

// Usage
so_query('GET', 'https://www.example.com/query.php');

Note that the URL should be on the same domain as the function caller, in order to avoid CORS warnings. If this is the case, the URL should accept incoming requests.

In my case above, where I have a PHP script, I have added the following lines at the top of my example query.php file:

header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS' );
header( 'Access-Control-Allow-Headers: X-Requested-With' );

Remove what you don’t need and make sure you only allow your domain origins.

Related posts

Leave a Reply

You have to agree to the comment policy.