With every click of a button, hundreds of AJAX requests are generated in rapid succession

Here's a situation I'm facing - every page involves an ajax request. I managed to enable JavaScript to run on each ajax requested page. Out of curiosity, I started testing my code by opening Chrome's developer tools to peek behind the scenes.

I discovered some glitches, where pressing the button on page 1 triggers the same amount of requests as the number of times the button is pressed. However, when I try this on page 2 or 3, it results in hundreds of additional ajax requests within a short time frame. This behavior needs to be fixed. While I want JavaScript enabled on all pages, I need to prevent multiple ajax requests and ensure that the button's actions correspond appropriately.

Take a look at this .gif screenshot to understand better: https://i.sstatic.net/5LR5O.gif

Below are the code files:

page_1.php

<script>
document.addEventListener('DOMContentLoaded', function(){

var execute_sendAjax1 = document.getElementById('executeAjax1');
execute_sendAjax1.addEventListener('click', sendAjax1);

function sendAjax1(){
var xhr1= new XMLHttpRequest();

xhr1.onreadystatechange = function(){
    if(xhr1.readyState === 4){
        document.getElementById('ajax1').innerHTML= xhr1.responseText;

    /*<Allow JS on the requested page>*/
    var exJs = document.getElementsByTagName('script');
    var enableAll = null;
    for (var i = 0; i < exJs.length; i++) {
        enableAll += exJs[i].innerHTML;
    }
    eval(enableAll);
    /*</Allow JS on the requested page>*/

    }
}
xhr1.open('POST','page_2.php');
xhr1.send();
}

});

</script>

<button id='executeAjax1'>Execute 1</button>

<h1>Page 1</h1>

<div id='ajax1'></div>
...

This type of issue can lead to browser freezes, which is not ideal. Thus, I am seeking a more efficient method to allow JavaScript while preventing the creation of excess ajax requests after multiple button clicks. Page 1 operates as intended, avoiding the cascade of requests seen on page 2 and 3. Identifying a solution to address this anomaly is crucial to maintain a seamless browsing experience.

Answer №1

Generate a variable that stores the specific id where each page's request will take place, for instance

var ajaxDivId= document.getElementById('ajaxDivId');

This is what I'm explaining in detail

page_1.php

<script>

document.addEventListener('DOMContentLoaded', function(){

var execute_sendAjax1 = document.getElementById('executeAjax1');
  execute_sendAjax1.addEventListener('click', sendAjax1);

function sendAjax1(){
var xhr1= new XMLHttpRequest();

xhr1.onreadystatechange = function(){
    if(xhr1.readyState === 4){
    document.getElementById('ajax1').innerHTML= xhr1.responseText;

    /*<Allow JS on the requested page>*/

    //Target the AJAX response div to allow JS to run in that div
    var ajax1= document.getElementById('ajax1');
    //

    var exJs= ajax1.getElementsByTagName('script');
    var enableAll = exJs.length;
    for(var i=0; i < enableAll; i++){
    eval(exJs[i].text);
}

    /*</Allow JS on the requested page>*/

    }
}
    xhr1.open('POST','page_2.php');
    xhr1.send();
}

});

</script>

<button id='executeAjax1'>Execute 1</button>

<h1>Page 1</h1>

<div id='ajax1'></div>

page_2.php

<script>

var execute_sendAjax2 = document.getElementById('executeAjax2');
  execute_sendAjax2.addEventListener('click', sendAjax2);

function sendAjax2(){
var xhr2= new XMLHttpRequest();

xhr2.onreadystatechange = function(){
    if(xhr2.readyState === 4){
    document.getElementById('ajax2').innerHTML= xhr2.responseText;

    /*<Allow JS on the requested page>*/

    //Target the AJAX response div to allow JS to run in that div
    var ajax2= document.getElementById('ajax2');
    //

    var exJs= ajax2.getElementsByTagName('script');
    var enableAll = exJs.length;
    for(var i=0; i < enableAll; i++){
    eval(exJs[i].text);
}

    /*</Allow JS on the requested page>*/

    }
}
    xhr2.open('POST','page_3.php');
    xhr2.send();
}

</script>

<button id='executeAjax2'>Execute 2</button>

<h1>Page 2</h1>

<div id='ajax2'></div>

page_3.php

<script>

var execute_sendAjax3 = document.getElementById('executeAjax3');
  execute_sendAjax3.addEventListener('click', sendAjax3);

function sendAjax3(){
var xhr3= new XMLHttpRequest();

xhr3.onreadystatechange = function(){
    if(xhr3.readyState === 4){
    document.getElementById('ajax3').innerHTML= xhr3.responseText;

    /*<Allow JS on the requested page>*/

    //Target the AJAX response div to allow JS to run in that div
    var ajax3= document.getElementById('ajax3');    
    //

    var exJs= ajax3.getElementsByTagName('script');
    var enableAll = exJs.length;
    for(var i=0; i < enableAll; i++){
    eval(exJs[i].text);
}

    /*</Allow JS on the requested page>*/

    }
}
    xhr3.open('POST','page_4.php');
    xhr3.send();
}

</script>

<button id='executeAjax3'>Execute 3</button>

<h1>Page 3</h1>

<div id='ajax3'></div>

page_4.php

<h1>Page 4</h1>

This technique revolves around executing the script tags solely based on the designated div id where the ajax request output occurs. I just verified

this recently so now you can trigger an ajax request depending on how many times you click the button on those pages, allowing you to execute JS based on those requested pages. Remember, using eval() can be risky.

Answer №2

The main cause of this issue is due to the fact that you are continuously adding the responses from the calls into your webpage, generating new script tags and then running through all of them every time you click, leading to an exponential growth:

document.getElementById('ajax3').innerHTML= xhr3.responseText;

/*<Allow JS on the requested page>*/    
    var exJs = document.getElementsByTagName('script');
    var enableAll = null;
    for (var i = 0; i < exJs.length; i++) {
        enableAll += exJs[i].innerHTML;
    }
    eval(enableAll);
/*</Allow JS on the requested page>*/

If you analyze the content of your code instead of just looking at the network tab, you will be able to understand what happens after clicking the button for the first time.

To address this issue, I suggest a different approach: rather than immediately appending the response content to your DOM, only add the non-script HTML elements first and then execute the eval function only on the current response's script tag.

There are various ways to achieve this, including using regex to capture the script tag content, storing it, removing the script tag, adding the remaining content to your DOM, and finally running eval() on the stored script.

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

The functionality of this code is optimal in Chrome and Firefox, yet it encounters issues in IE

Currently, I am attempting to create a jquery tooltip that will pop up when a user hovers over a link. The link in question is set to display:block style in order to cover a larger area. Surprisingly, this setup works flawlessly in Chrome and Firefox, but ...

Angular 2 is all about managing validation messages within controls

I'm currently facing challenges with getting validation messages to display properly in Angular 2. The frequent updates to Angular 2 have made it difficult to find a simple and effective solution online, so please refrain from marking this as a duplic ...

What is the best way to change the inner text of an HTML element without causing it to resize or impacting its overflow?

Is it possible to change the text content of an HTML element without affecting its size? I am using Bootstrap and the card component. I want to dynamically update the card text without impacting the overflow that I have already set. Here is a sample of t ...

using Javascript to calculate motion based on specified angle

http://pastebin.com/3vwiTUyT I have posted my code here and need assistance. Specifically, I am trying to make krog1 move within the canvas based on a specific angle that I set. Unfortunately, I am unsure how to accomplish this task. ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

Basic HTML code that displays either one or two columns based on the width of the screen

My monitoring website displays dynamic rrd graphs in png format with fixed dimensions. I am looking to adjust the layout based on browser window size - showing the graphs in 1 column if the width is below a certain threshold, and in 2 columns if it exceed ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...

Tips on creating an infinite loop for multiple functions using jquery

Here is a snippet of my jQuery code which consists of three functions. These functions are meant to be executed in a loop, but unfortunately, the code is not running properly. I need help on how to properly implement recursive calls with these three func ...

Get a numerical value from a JSON object

Attempting to retrieve information from an API, but encountering an issue due to a numeric property name. The method for accessing the data is as follows: Success: data[i].price_usd Unsuccessful Attempt: data[i].24h_volume_usd Have experimented with ...

JavaScript appendChild method not functioning properly with dynamically created image elements in JavaScript code

I recently encountered an issue while working on a website project. I was trying to create an img element using JavaScript, but ran into a problem when I tried to add the src attribute and then use the appendChild function. I'm unsure if I am missing ...

Error message: "Issue with Jointjs library on Node.js server - Uncaught ReferenceError: Joint is not recognized"

I am attempting to create a sample diagram using the code below on a file hosted on a Node server: <!DOCTYPE html> <html> <head> <title>newpageshere</title> <link rel="stylesheet" href="joint.css" /> <script src="j ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Steps to bring an image forward on a canvas to enable its onclick function

One of the challenges I'm facing involves an image of a pawn on a board. The image is set up with an onclick function that should trigger an alert when clicked. However, there is a canvas positioned above the image, which is interfering with the funct ...

`How can I enable the download attribute feature on Safari browser?`

Is there a workaround for saving files with a specified name in Safari? The following HTML code does not work properly in Safari, as it saves the file as 'unknown' without an extension name. <a href="data:application/csv;charset=utf-8,Col1%2C ...

Return to the main page by clicking on the link #id

I am in the process of creating a personalized Wordpress theme that consists of one main page with 8 additional sub-pages. I am wondering how I can navigate to a specific section using an ID (for example, <a href="#how">how</a>) from the sub-pa ...

Can you explain the concept of ".el" as it relates to JavaScript, HTML, and jQuery?

After conducting a search on Google, I didn't find much information. Perhaps I am using the wrong terms. I am trying to figure out what the "el" in "$.el" represents in the following code snippet: $.el.table( $.el.tr( $.el.th('first name ...

The Vue component seems to be missing the definition of $v for Vuelidate

I've been struggling to resolve this issue. The error message I am encountering pertains to a Vue component that is utilizing the Vuelidate library for form validation. Do you have any insights on what might be causing this error? Uncaught TypeError: ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

Executing Ajax requests sequentially within a .each loop.Each Ajax request triggered one after the

Is there a way to run Ajax post requests sequentially, waiting for each one to complete before starting the next? I've tried various methods without success and am now looking for the best working approach. The current setup sometimes interrupts requ ...