Same-Origin AJAX Request Using Vanilla JavaScript

on in AJAX and Fetching Data
Last modified on

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();, so_uri, true);

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

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

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