Updating two separate <DIV> elements with a single AJAX request

Can two different targeted DIVs be updated simultaneously using a single ajax call?

Consider the index.html code snippet below:

<script>
      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("main_body").innerHTML = xmlhttp.responseText;}
                                                 }
      xmlhttp.open("GET","some_page.php",true);
      xmlhttp.send();
</script>

<div id="main_body">
<div id="update_1"></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"></div>
</div>

In the scenario above, all I know is that the content of some_page.php needs to be structured like this:

<php
     echo "<div id="update_1"><h1>Apple</h1></div>
           <div id="dont_ajax">A big size of html content....</div>
           <div id="update_2"><h1>Orange</h1></div>";
?>

I want to avoid loading the content of id="dont_ajax" due to its large size. Is there a solution like the following:

<script>
  xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("update_1").innerHTML = xmlhttp.responseText(1);
        document.getElementById("update_2").innerHTML = xmlhttp.responseText(2);}
                                             }
  xmlhttp.open("GET","some_page.php",true);
  xmlhttp.send();
</script>

<div id="main_body">
<div id="update_1"></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"></div>
</div>

This way, some_page.php can be simplified as:

<php
 echo "<h1>Apple</h1>"; //(responseText for 1)

 echo "<h1>Orange</h1>"; //(responseText for 2)
?>

I understand that my example may not work as intended, but it illustrates the issue and desired outcome. Any suggestions or alternative approaches in native JS would be appreciated.

I specifically require a solution using native JavaScript.

Answer №1

Absolutely, updating multiple elements is possible by preparing and parsing the response accordingly. The key lies in how you handle the response data.

This snippet of code may seem inefficient as the ajax response contains only a single responseText:

<php
 echo "<h1>Apple</h1>"; //(will be responseText(1))
 echo "<h1>Orange</h1>"; //(will be responseText(2))
?>

As a result, you'll receive

<h1>Apple</h1><h1>Orange</h1>
in the response, leading to cumbersome code trying to segregate it into different parts.

An optimal approach involves creating a JSON string instead:

<php
 echo "{update_1: '<h1>Apple</h1>', update_2: '<h1>Orange</h1>'}";
?>

Subsequently, parse the response and perform document updates accordingly:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   var data = JSON.parse(xmlhttp.responseText);
   ['update_1', 'update_2'].forEach(function(i){
      document.getElementById(i).innerHTML = data[i];
   });
}

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

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

"Could not locate the .php file on localhost, resulting in a 404

I've recently embarked on the journey of learning PHP programming, but I've hit a frustrating roadblock that's preventing me from moving forward. After setting up a LAMP server on my Linux Mint with default settings on localhost, I encounte ...

Having trouble establishing a basic websocket connection in NodeJS

I am currently following a tutorial on WebSocket protocol development from this link: . Upon visiting localhost:1337/index.html, I encountered the following error: This localhost page cannot be found. No webpage was found for the web address: http://loc ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...

Encountering Axios errors while executing API calls at a high frequency

Recently, I have been facing some challenges with making API calls from localhost using axios in a loop. While it works smoothly at times, most often I encounter errors like: cause: Error: connect ECONNREFUSED ::1:8000 at TCPConnectWrap.afterConnect ...

Designing a dynamic presentation with varying intervals between slides

I am working on a jQuery slideshow that smoothly transitions between different <div> elements. In the current code, the slides change every 5 seconds. Is there a way to modify this so I can specify custom durations for displaying each slide? Here i ...

Deliberately-paced, hands-off distant data storage

I'm currently working on a PHP webapp that needs to access a remote read-only database that is very slow (8-10 seconds per query). Unfortunately, I can't improve the speed of the remote database itself, but I can try different strategies on my en ...

Unraveling the PHP for-loop conundrum

In PHP 5.6, how come the following code displays 2 5 8 11 instead of 3 6 9 ? for ($i = 0; $i < 10; $i++) { echo $i += 2 . "<br />"; } ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Ensuring User Data is Current in the UI with Firebase Auth Callbacks

Below is the standard method for setting the user state to currentuser that is returned from onAuthStateChanged. I am looking for a useEffect hook that will be triggered whenever there is an update to the user's information. Unfortunately, I am unable ...

Menu that sorts items based on a specified range of values entered by the user

I'm looking to implement a customized filtering dropdown menu, similar to the one showcased on this website Currently, I have functioning filters that can select items based on a specific category. However, I want to enhance the functionality by inc ...

Using symbolic links prior to the controller/method in CodeIgniter

Feeling a bit stuck and in need of help, I've decided it's time to reach out for some assistance. Here's my situation - I've been attempting to use a symbolic link to mask my URL like this: www.website.com/uk/controllers/method/etc www ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

The event "click .className" within the Marionette module is failing to trigger

I'm facing an issue with some code that I've written. Here's a snippet of what it looks like: myApp.module(args, function(args){ Views.MainView = Marionette.ItemView.extend({ //template, tagName, className down: false, events: ...

Inaccurate AJAX response mentioned

For populating text boxes from a database, I am using an onChange event. Although the code runs, the response I get is incorrect. The code I am using can be found below: index.php <?php $servername = "localhost"; $username = "root"; $password = ""; $ ...

How can you utilize Angular Signals in combination with HostBinding to dynamically update styles?

Within a component called app-test, the following code is present: @Input({ transform: booleanAttribute }) reverse: boolean = false; @HostBinding('style.flex-direction') direction: string = this.reverse ? 'column-reverse' : &ap ...