`Vanilla JavaScript AJAX request without using any external libraries or

Seeking advice on creating an ajax request function that is compatible across various browsers without relying on a javascript framework such as jQuery. Any ideas or suggestions are appreciated!

Answer №1

Utilizing the XMLHttpRequest object may seem daunting at first, but it's actually quite simple once you get the hang of it. To ensure compatibility across various browsers, there are some tricks involved in setting up the object initially, but afterwards, it's smooth sailing for basic tasks.

If you check out the MSDN page dedicated to XMLHttpRequest, Microsoft provides examples including a function for creating the object in a way that works on older versions of Internet Explorer. Here is their recommended approach:

function getXMLHttpRequest() 
{
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            return null;
        }
    }
}

function handler()
{
    if (oReq.readyState == 4 /* complete */) {
        if (oReq.status == 200) {
            alert(oReq.responseText);
        }
    }
}

var oReq = getXMLHttpRequest();

if (oReq != null) {
    oReq.open("GET", "http://localhost/test.xml", true);
    oReq.onreadystatechange = handler;
    oReq.send();
}
else {
    window.alert("AJAX (XMLHTTP) not supported.");
}

The above code snippet might not adhere to best practices (Microsoft's MSDN examples sometimes lack expertise), but it serves as a good starting point. For example, note that success in HTTP responses should be considered from the 200 to 299 range according to specifications.

Answer №2

In the realm of modern browsers (without considering older versions like IE), I frequently rely on this approach for managing JSON data transmission.

function ajaxRequest(method, url, data, callback){

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = handleResponse;
    xhr.open(method, url);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(data && JSON.stringify(data));

    function handleResponse(){
        if(this.readyState === this.DONE) {

            switch(this.status){
                case 200:
                    if(this.getResponseHeader('Content-Type').split(';')[0] !== 'application/json'){
                        return callback("Unexpected Content-Type: '" + this.getResponseHeader('Content-Type') + "'", null);
                    }
                    return callback(null, JSON.parse(this.response));

                case 401:
                    location.href = '/authentication/login';
                    return;

                default:
                    return callback("Unexpected status: " + this.status + "", null);
            }
        }
    }//handleResponse
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing various data using Ajax

I am currently in the process of extracting various pieces of data from my insert.php page, including the post id, username, and user id. I intend to include other selected data as well. However, when trying to echo out multiple queries, all the informatio ...

Guide on encrypting data on the server with PHP and decrypting it on the client side using JavaScript

I'm currently developing a training website with PHP and I am looking to share my training resources securely without worrying about copyright issues. My plan is to encrypt the documents on the server before sending them, and then have them decrypted ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Issue with Passing 'key' Prop to React Component in a Mapped Iteration

https://i.sstatic.net/qeFKT.pngI'm struggling with adding a key prop to a React component in a mapped array within a Next.js project. The issue lies in a Slider component and an array of Image components being mapped. Even though I have provided a uni ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...

Issue with data not being transferred to Vue component

I am currently working on a Vue component that receives an array of 'items' from its parent. These items are then categorized with two items in each category: computed: { // sort items into categories glass: function() { ...

What is the most common method for creating a dropdown menu for a website's navigation?

Is there a common approach to creating an interactive drop-down navigation menu in the industry? I have searched on Google and found multiple methods, but as a student working on my first big web project, I am hoping to find a standard practice. I don&apo ...

Utilizing Node.js to iterate through arrays grouped by categories

Here is some data I need to work with [ [ '@test','1.2.6-unstable' ], [ '@test','1.3.2-unstable' ], [ '@test','1.4.6-unstable' ], [ '@test2','4.0.1-unstable' ], [ &ap ...

ASP.NET - The Power of a Long Press

I am currently working on implementing a Long Press event in JavaScript on an ASPX page. Due to my limited experience with JavaScript, I am facing a few challenges. I found a similar question that was previously asked here. When running the code, I encoun ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Black textures with images sourced from the same domain - Cross-origin

Despite trying numerous solutions and tips to resolve the cross-origin issue, I still can't seem to fix it. There are no errors, the images are hosted on the same domain as the webgl test, but the textures appear black. Occasionally when I refresh rep ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

Troubleshoot and resolve the issue of a page scroll freeze bug occurring while scrolling through an overflowed

My webpage features a Hero section with 2 columns - the left column contains a gallery slider, and the right column consists of 2 text blocks. The challenge here is that the right column needs to be 100% of the screen height while scrolling. To achieve thi ...

Arranging objects in an array using jQuery for optimal organization

How can I rearrange the items based on their 'name' property? staticdata.items = [ {id: '0', 'name': 'ABC'}, {id: '0', 'name': 'XYZ'}, {id: '0', 'name': ' ...

Is there a way to retrieve SQL information through an API and then incorporate that data into react-native-svg charts? I have an API that contains data I would like to retrieve and showcase

I am utilizing an API to retrieve data, which includes the execution of SQL queries. The API is responsible for fetching data and running these queries. I am looking for a way to replace the static data in my charts with dynamic data fetched from the API. ...

Issues with Flask-Restless operators causing improper filtering functionality

Currently, I am working on developing a login feature for a mobile web application using Flask and Flask Restless. During testing, I noticed that even though my database only has one record, every time I send an AJAX request to Flask Restless, it returns t ...

The art of integrating partial rendering into a template

I'm currently working on a project using Angular 2 and I need to display a partial inside a template without having to create a new component. Is this doable? import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} ...

Understanding the lockfile: deciphering the significance of each line in the yarn.lock file

I'm curious about the meaning of each line in this file. I encountered issues with packages due to dependencies in my project. After upgrading nuxt from version 1x to 2x, all tests started failing. After spending hours searching online, I discovered ...

What is the method for determining the required or imported base path?

My package.json includes the main option to set the default file for importing like import 'my-index' from 'my-module' However, I would like to break up my-module into separate files so developers can include them individually with sta ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...