Using an AJAX function to retrieve data from two different server-side scripts and populate two separate HTML elements on the page

My goal in this coding situation is to change values in multiple DOM targets. The example from Tizag shows the DOM being altered within the onreadystatechange function, like this:

if(ajaxRequest.readyState == 4){
    document.myForm.time.value = ajaxRequest.responseText;
}

However, I wanted to experiment with returning a value instead of directly changing the DOM. I modified the code accordingly, but encountered issues.

Below is the revised code where I attempted to access 2 different scripts towards the end. Is it feasible to accomplish this task?:

function ajaxFunction(){
    var ajaxRequest;  // Key variable enabling Ajax functionality

    try{
        // Compatible with Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // For Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Error handling for unexpected scenarios
                alert("Your browser broke!");
                return false;
            }
        }
    }
    
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            return ajaxRequest.responseText;
        }
    }
    
    ajaxRequest.open("GET", "/time.php", true);
    var time = ajaxRequest.send(null);  
    ajaxRequest.open("GET", "/date.php", true);
    var date = ajaxRequest.send(null); 

    document.getElementById('time').innerHTML = time; 
    document.getElementById('date').innerHTML = date; 
}

Answer №1

It seems like the 3rd argument in the ajax.open function call signifies that the request is handled asynchronously, implying that the return value from ajax.send won't be the direct response from the server script.

To properly handle this, make sure to assign your local variables inside the anonymous function linked to onreadystatechange. By examining the ajax object, you can identify which specific server script was invoked.

Consider creating two separate ajax objects - one for fetching the date and another for retrieving the time - for better organization.

Additionally, exploring jquery could prove beneficial as it simplifies the process of executing ajax requests by handling much of the underlying complexity for you.

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

What is the best way to save a current HTML element for later use?

Here is a simple HTML code that I would like to save the entire div with the class test_area and then replicate it when needed. Currently, my goal is to duplicate this div and place the clone underneath the original element. How can I achieve this? Unfortu ...

I'm looking to fill multiple input boxes with the same value

I am looking to pass the same value to multiple input boxes. Currently, the script below only displays in one box but I want to display the main box result in all multiple input boxes. <script type='text/javascript' src='http://code.jque ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

What is the best way to show a macOS progress pie loading icon alongside files?

While using macOS, a pie loading icon appears next to a file during downloading or transferring. To illustrate, here is an example of a file being downloaded from Chrome: I am interested in implementing a similar feature in my Electron/Node application. ...

The Jquery append function is limited to the initial ajax request, necessitating a page refresh in order to populate another div with the desired

When making an AJAX request to retrieve a JSON array, upon successful completion another AJAX request is triggered. The retrieved data is then populated into the div of a bootstrap modal using the jQuery append function. Everything functions as expected ...

What is the process for deselecting a checkbox?

I am facing a situation where I need to uncheck a checkbox that is always checked based on user input from another section of my form. Specifically, I have implemented an onChange="functionName" event on a select box. Can someone guide me on how to accom ...

Error: Cannot access the 'top' property of an undefined object

Here is a snippet of my jQuery code: $(document).ready(function(){ $('.content-nav a').on('click',function(){ var str = $(this).attr("href"); var the_id = str.substr(1); $("#container").animate({ scrollTop: $ ...

Enhance design based on scrolling function in React

I've been trying to update the color of my header when a user scrolls the page, but for some reason, my onScroll method isn't working. Can anyone help me figure out why and how to solve this issue? The onScroll method is triggered by the bottom T ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

Guide to effectively deleting a Django object instance using Ajax

In the HTML, a list has been generated representing all objects (Cards). Currently, there is a delete button that uses Django functionality, but it requires a page reload to take effect. Is it possible to integrate AJAX into this program easily? Being new ...

What is the reason behind the delayed mutation of the state when invoking the setState method in React?

Currently diving into the Forms section within the documentation of ReactJS. Just implemented this code snippet to showcase the use of onChange (JSBIN). var React= require('react'); var ControlledForm= React.createClass({ getInitialState: f ...

Direct all paths to the base path "/" using Express

Is there a way to redirect all URLs containing "/something" in Express to the base path "/:=", while still maintaining additional paths to their respective pages? For instance, I would like to implement the following redirects: "/something" redirects to ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

Error: The specified module 'sqlite' does not have an export named 'default' as requested

Having some difficulty with importing sqlite into my project. When I add this line: import sqlite from 'sqlite'; An error occurs: file:///D:/WebPro/WebProg/cwCode/dbInteract.js:2 import sqlite from 'sqlite'; ^^^^^^ SyntaxError: ...

Unable to modify a variable within a request

Having trouble updating a variable within a request? It seems like the variable doesn't change when it should. const request = require("request"); var all = JSON.parse(body); var steamplayer = all['response']['players']['play ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

Chrome Extension: Passing a variable between Content Script and background.html

Struggling to understand how to transfer a variable or an array of variables from a content script to a background page. The goal is to identify specific DOM elements using the content script and then send them to the background page for a cross-domain XML ...

Is there a way to ensure my function runs as soon as the page starts loading?

My goal is to have a function execute as soon as a person opens my page, without requiring any interaction. The function should trigger on page load, rather than waiting for a click event. Additionally, I want the function to repeat every 90 seconds. I&apo ...

Using a loop variable within a callback function in JavaScript/TypeScript: Tips and tricks

I have a method in my TypeScript file that looks like this: getInitialBatches() { var i = 0; for (var dto of this.transferDTO.stockMovesDTOs) { i++; this.queryResourceService .getBatchIdUsingGET(this.batchParams) ...