JavaScript: the battle between anonymous and direct function invocation

Here is an interesting observation: when I assign an anonymous function to the onreadystatechange variable, everything works fine. However, if I try to assign a named function to this variable, it does not work as expected.

 <script language="Javascript">
    function postRequest(strURL) 
    {
        var xmlHttp;
        if (window.XMLHttpRequest) // Mozilla, Safari, ...
            var xmlHttp = new XMLHttpRequest();
        else if (window.ActiveXObject) // IE
            var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttp.open('POST', strURL, true);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.onreadystatechange = function() 
        {
            alert("you are in anonymous");
        }
        xmlHttp.send(strURL);
    }
</script>

The code above functions correctly, but the following code snippet does not work as intended. The function foo() does not get called:

 <script language="Javascript">
    function foo()
    {
        alert("you are in foo");
    }
    /*----------------------------------------------*/
    function postRequest(strURL) 
    {
        var xmlHttp;
        if (window.XMLHttpRequest) // Mozilla, Safari, ...
            var xmlHttp = new XMLHttpRequest();
        else if (window.ActiveXObject) // IE
            var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttp.open('POST', strURL, true);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.onreadystatechange = foo; 
        xmlHttp.send(strURL);
    }
</script>

Why do you think that is?

Answer №1

The problem has been successfully resolved. It turns out that declaring the variable xmlHttp as a global variable was necessary. Even though I wasn't directly using it in the function foo(), it seems to have been required internally by the xmlHttp object. Does anyone understand why this is the case? Regardless, I'm grateful that this issue has been fixed. Many thanks.

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

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

What is the best way to display the Edit and Delete buttons in a single column?

Currently, I am encountering a small issue. I am trying to display Edit and Delete Buttons in the same column but unfortunately, I am unable to achieve that. Let me provide you with my code. var dataTable; $(document).ready(function () { dataTa ...

How can I search for a particular string in JavaScript?

I have a unique custom div that has been modified to function as an input element. Inside this custom div input element, there is a <p> tag with a default placeholder text. My goal is to verify whether the content of this div is empty or contains new ...

Node.js web server operating on port 3000 is running a script

I have developed a Node.js script that extracts data from a database and saves it in a file. Additionally, I have set up a Node.js web server listening on port 3000 using forever to keep it running constantly. However, the script currently lacks a web inte ...

Looping through an array asynchronously and returning the result

I'm having some trouble with an asynchronous loop. Here's the code I've been working with: let items = []; data.forEach(async item => { var newItem = new Item(data); newItem.options = await this.fetchOptions(data[" ...

jQuery UI validation causing submission of a form with invalid data

Currently, I am troubleshooting an issue with a form that utilizes Ajax to submit data to the backend. For validation, I'm using the jQuery-ui validation plugin. The problem I am encountering is that the form submits even when fields are left empty. ...

Converting Byte strings to Byte arrays in Node.js using JavaScript

Currently facing a challenge while trying to complete the pythonchallenge using JS and Node. Stuck on challenge 8 where I need to decompress a string using bzip2: BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x ...

Exploring ways to connect my React application with a node backend on the local network?

On my MacBook, I developed a react app that I access at http://localhost:3000. In addition, I have a nodejs express mysql server running on http://localhost:5000. The issue arises when I try to open the IP address with port 3000 in the browser of my Window ...

Showing attributes of models using Sequelize and Handlebars

As a novice in the world of programming, I am currently immersed in a website project where users can write and post articles. One crucial aspect I am focusing on is displaying the history of articles written by each user on their account page. Despite uti ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Is there a way to automatically calculate the sum of two boxes and display the result in a separate

I am working with two boxes: one is called AuthorizedAmount and the other is called LessLaborToDate: <div class="col-md-6"> <div class="form-group"> <label>Authorized Amount</label> <div class="input-group"> & ...

Acquiring Device Data in React-Native for iOS

Hello, I am currently attempting to retrieve device information from an iPad. I attempted to use the library found at https://github.com/rebeccahughes/react-native-device-info, however, it caused issues after performing a pod install. My main goal is to ob ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

Will there ever be a possibility in the future to compile from D 2.0 to Javascript?

An experienced C++ programmer (that's me) is venturing into other programming languages and considering the value of learning more about D 2.0. The clean, fresh rewrite of D has caught my eye with its pragmatic and wise choices. Now, I'm eager to ...

Forward after asynchronous JavaScript and XML (AJAX)

Currently, I am working on an MVC project where I need to achieve the following: The scenario involves sending an ajax request from a JS script and then redirecting to a page along with a model once the request is processed. I attempted to send a form as ...

What is the best way to manage files in Vue.js?

I am faced with a challenge in storing image files and video files as Blob data. One thing I like is that the uploaded video and image files display instantly, which is pretty cool. I'm not entirely sure if the code below is correct - how can I navi ...

"Implementing a .gif Preloader Before Executing Animation with jQuery

I am currently working on an animation project using Jquery. The project consists of various images in .png format and div tags, with some being small file sizes while others are as large as 5mb. Is there a way to incorporate a pre-loading (.gif) animatio ...