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!
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!
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.
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
}
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 ...
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 ...
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 ...
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 ...
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 ...
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() { ...
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 ...
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 ...
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 ...
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 ...
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 ...
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=" ...
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 ...
How can I rearrange the items based on their 'name' property? staticdata.items = [ {id: '0', 'name': 'ABC'}, {id: '0', 'name': 'XYZ'}, {id: '0', 'name': ' ...
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. ...
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 ...
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} ...
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 ...
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 ...
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 ...