What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX.

I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered.

1) It appears that the Javascript function process is always actively "listening", is this standard behavior for Javascript? Or are there specific events that prompt the repeated execution of "process"? 2) Does any function assigned to "body onload" run repeatedly? If so, how frequently does this repetition occur? 3) How can we ensure a single execution of the process function if needed?

4) I'm slightly puzzled because I assumed the body would load only once. However, could it be that after the "body onload" event, the "process" function gets called, which then modifies the "body" by updating divMessage, essentially triggering another "body onload" cycle again, followed by "process" and so on.. ?

Many thanks in advance for your assistance!

<head>
  <script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
  Server requests your name:
  <input type="text" id="myName" />
  <div id="divMessage" />
</body>

Contained within quickstart.js

function process()
{
  // Proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // Retrieve the user-inputted name from the form
    name = encodeURIComponent(
    document.getElementById("myName").value);
    // Call the quickstart.php page located on the server
    xmlHttp.open("GET", "quickstart.php?name=" + name, true);
    // Define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;
    // Initiate the request to the server
    xmlHttp.send(null);
  }
}

// Callback function executed upon receiving a message from the server
function handleServerResponse()
{
  // Continue only if the transaction has completed
  if (xmlHttp.readyState == 4)
  {
    // Status code 200 signifies successful completion of the transaction
    if (xmlHttp.status == 200)
    {
        xmlResponse = xmlHttp.responseXML;
        xmlDocumentElement = xmlResponse.documentElement;
        helloMessage = xmlDocumentElement.firstChild.data;

        // Display the received data from the server
        document.getElementById("divMessage").innerHTML =
                  '<i>' + helloMessage+ '</i>';
      }
    }
  }
}

In addition, here's the contents of quickstart.php

<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$name = $_GET['name'];

// Generate output based on the user name received from the client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
  echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
  echo 'Stranger, please tell me your name!';
else
  echo htmlentities($name) . ', I don't know you!';

echo '</response>';
?>

Answer №1

After encountering an issue, I resolved it by closing down and restarting the process. It turned out that there was some extra code which I had previously commented out but was still cached. This code was calling "process" function every second from within handleServerResponse():

// display the data received from the server
    document.getElementById("divMessage").innerHTML =
              '<i>' + helloMessage+ '</i>';
    setTimeout('process()', 1000);

I apologize for the oversight. The lesson learned here is to always clear the browser cache before testing any code changes :) So, it seems like the advice to verify if this function is being called from elsewhere was spot on. Nonetheless, I gained valuable insights and knowledge while troubleshooting this issue. Thank you so much @pst!

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

Determining outcomes of forms added in real-time

Need assistance with dynamically creating tickets, calculating prices, and displaying results when additional tickets are added. Currently facing an issue where price data is not being calculated when a new ticket is added. Any help would be greatly apprec ...

Determine the overall cost based on varying percentage increases for each step

I am currently working on developing a price estimation calculator. Here is the breakdown: For 1000 MTU, the price will be 0.035, resulting in a total of 35. For 2000 MTU, the price will be 0.034, making the total 67. For 3000 MTU, the price will be 0.03 ...

What is the process for showcasing specific Firestore items on a webpage?

database I've encountered an intriguing bug in my code that is proving difficult to resolve. The code involves a straightforward setup with React and Firestore, where items are listed on one page and their details are displayed on the next. However, t ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Error message: Invalid label detected in Jquery ajax request

I am currently trying to make an ajax call to the URL below: However, I keep encountering an invalid label error in the firebug console. I have included my ajax code below. Can you please review it and let me know if there is something wrong with it? //M ...

Guide to creating "bidirectional data binding" in Vue

I have a child component that is responsible for uploading a photo. The uploaded photo is assigned to the child component's data called "photo". I need to connect the parent data called "file" with the child data called "photo". And whenever "photo" i ...

How to sort WordPress RSS feed in alphabetical order using JavaScript

Currently using WP, but feeling limited due to restricted access to PHP and plugins. Searching for a JAVASCRIPT code solution to fetch RSS feed from a URL and organize the feed titles in ALPHABETICAL order. The JS code can be inserted into the footer and ...

Tips for positioning the labels in a sankey diagram for optimal alignment

When multiple values are the same in this scenario, such as 0, the labels start to overlap. Can anyone provide guidance on how to align these labels vertically? Ideally, I would like them to be positioned at the top of the node/bar. Highcharts.chart(&apos ...

The JSON on the Express page only appears after refreshing the page

When accessing my page at /id, the data pulled from an external API using Express does not display until the page is refreshed. Any suggestions on how to solve this issue? // Retrieves basic account data router.get('/:id', function(req, res, nex ...

JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide. However, I'm facing an issue with moving the active link to the top of the na ...

Problem with animated scrolling in Jquery

Currently, I am working on a function that aims to smoothly scroll the web to a specific div each time a user scrolls "into" a container div. You can get a better idea of what I mean by looking at my JSFiddle. Everything works perfectly when the user scro ...

Refreshing div content based on dropdown selection without reloading the page

I am currently working on implementing a dynamic dropdown feature that will update text content on a webpage without needing to refresh the entire page. The updated text will be fetched from a PHP function which receives input from the dropdown selection. ...

Guide to Appending "Z" to a Date String Using Moment.js in JavaScript and Node.js

I am struggling to format my date to include the "Z" letter at the end. Despite numerous attempts, I have been unsuccessful. The desired format is "YYYY-MM-DDT00:00:00.000Z," but currently it does not include the Z How can I add the Z using moment? It&ap ...

Changing the prefix for a guild can be done without needing a complete restart, while adding a new guild to my database inexplicably requires one

I have set up a code that adds guilds to the database with default settings when they join. If the guild decides to change the prefix, it updates successfully and they can immediately start using it. However, there is an issue where I have to restart the b ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

Challenges surrounding jQuery's .before

Currently, I am in the process of creating a simple carousel consisting of 4 divs. The carousel is utilizing 2 jQuery functions to position a div at either the first or last slot. The transitions being used are only alpha transitions as there is no need fo ...

What can I do to keep my navbar on top of the slideshow?

Is there a way to create a responsive navbar that sits in front of a slideshow containing images? I attempted to place the div within the main, but unfortunately it was unsuccessful. ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

What could be the reason my node.js application built with express is unable to retrieve data from mongoose

Currently, I have experience in PHP MVC and recently delved into learning Nodejs. Here is how my app directory structure looks like: root - controllers -user.js - model -user.js - public -stylesh ...

Retrieve highlighted text along with its corresponding tag in ReactJS

my <span class="highlight">highlighted</span> word The text above is showing an example including HTML tags. However, when using window.getSelection(), only the text "my highlighted word" is returned without the surrounding <span& ...