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

retrieve data properties from an object

Suppose I have the following setup: var myObj = [ { name: 'A', number: 'b1', level: 0 }, { name: 'B', number: 'b2', level: 0 }, ]; I need to figure out how to retrieve all the names and format them like this: ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

What is the mechanism behind ajax operation on a wame server?

Hello everyone, I'm diving into learning AJAX for the first time by following tutorials on w3schools. Despite my best efforts to follow the step-by-step instructions, I am struggling to make an AJAX example work. Could someone please assist me? Thank ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...

Crafty Checkbox Selector [ leveraging jquery ]

I have created some fake checkboxes using elements like <span> after the real checkbox and they are working fine! However, I am having trouble counting the checked checkboxes when a checkbox is clicked. I have tried using methods like: $(".elm:chec ...

Personalizing/Concealing Navigation Controls

Looking for a way to customize the Navigation in the Pagination Plugin; changing 'First, Prev, Page 1, Page 2, Next, Last' to 'Prev, Next, Page 1 of 2' The documentation suggests using show_first_last set to false to hide 'First/L ...

While JSON Lint may declare the JSON data as valid, JSON.parse may still encounter an error when trying

I'm struggling to parse a simple JSON object. It's strange because when I check the validity of my JSON string on JSONLint (http://jsonlint.com/), it shows that it's valid. var data = '{"token":"9eebcdc435686459c0e0faac854997f3","email ...

Ways to invoke a specific component within ReactDOM.render in React

Currently, I am facing an issue where 2 components need to be rendered present in a single div using myProject-init.js, but both are getting called at the same time. In myProject-init.js file: ReactDOM.render( <div> <component1>in compone ...

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

Can the MemoryRouter be successfully nested within the BrowserRouter in a React application?

I've been on a quest for some time now, trying to uncover whether it's feasible to utilize MemoryRouter solely for specific routes while maintaining the use of BrowserRouter in general. My goal is to navigate to a particular component without alt ...

Retrieve the parseJSON method using a string identifier

I am trying to serialize a C# const class into name-value pairs, which I need to access by their string names on the client side. For example: return $.parseJSON(constantClass).property; This approach is not working as expected. Is there any alternative ...

Leaflet Alert: The number of child elements is not the same as the total number of markers

Encountering a problem with Leaflet clustering using v-marker-cluster. Within the icon createFunction of the cluster, the className of children is used to determine the cluster style. Here is a snippet of this function : const childCount = marker_cluster._ ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

fetching a set of data entries from an entity on dynamic CRM platform utilizing the REST API along with asynchronous JavaScript and XML

Seeking to display all accounts from the account entity in an alert box by making an ajax call to the Service OrganizationData.svc. The post method works fine for adding an account, but when trying to retrieve all accounts using GET, I encounter some diff ...

Adjust the size of an HTML image for printing using a JavaScript window.print() function

On my website, I have a print option set up where specific elements are hidden using @media. How can I adjust the size of an image within the @media query when my JavaScript print function is triggered? I am able to modify a regular div element easily, but ...

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

Whenever the page is refreshed, the props in my application are dynamically updated thanks to the getStaticProps function I utilize

Currently, I am in the process of learning nextjs as a beginner. Through the utilization of the getStaticProps function, I have come to understand that data fetching occurs only once at build time and the values remain static thereafter. Despite this, I ...