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

Ajax is failing to receive the PHP response

I've been struggling with retrieving values from the database using AJAX during the window load event. When I directly access the PHP script, I see the correct values on the screen. However, when trying to fetch these values through AJAX on another pa ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

Spring's MVC framework encountered a 400 Bad Request error when processing an

Encountering a recurring issue with receiving a 400 Bad Request error during Ajax requests. It's puzzling as to what could be causing this problem. The technologies being used include: <dependency> <groupId>org.codehaus.jackson</gr ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

What is the best way to modify the state of an array of objects by applying a filter in Vue 3?

I am currently facing an issue with a component that is listening for an emit and then attempting to filter out a user with a specific userId from the users state. The challenge lies in the fact that assigning filteredUsers to users does not appear to be ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

Interaction issue with Material UI and React tabs: hovering fails to open and close tabs correctly

I am currently immersed in a project that involves React and Material UI. My goal is to create tabs that trigger a menu upon hovering, but I seem to be facing some challenges with this functionality. That's why I'm reaching out here for assistanc ...

Utilize Google Maps geocoding functionality to pinpoint a location and then

I've encountered this strange phenomenon, but first let's take a look at the code: HTML <div ng-app='maptesting'> <div ng-controller="MapCtrl"> <div id="map_canvas" ui-map="myMap" style ...

Activate the button when the password is correct

Check out my code snippet: $("#reg_confirm_pass").blur(function(){ var user_pass= $("#reg_pass").val(); var user_pass2=$("#reg_confirm_pass").val(); var enter = $("#enter").val(); if(user_pass.length == 0){ alert("please fill password ...

Navigating tables with jQuery using a loop and extracting data from two tables with matching row names

I am facing a challenge with a function that combines data from two tables, each containing a column named "name". How can I specify which table's name should be displayed? function createTableRow(customers) { var data = JSON.parse(customers.resu ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

Automatically filling in related information in multiple input fields after choosing a value in a specific input field using JavaScript

My horizontal form is dynamically generated using JavaScript, with each input field having a jQuery autocomplete that retrieves data from a database using the $.get method. I'm looking to automatically populate the second input field with the corresp ...

Is it possible to transfer a URLFetchApp.fetch request from the Google Apps Script side to the JavaScript side?

My current task involves parsing an XML document tree upon clicking a button. The XML file is obtained using a lookup function that requires two values ("id" and "shipping") to be inserted into the appropriate URL. Then, the data retrieved is parsed using ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

What is the process for accessing the Recaptcha parameters known as recaptcha_challenge_field and recaptcha_response_field?

Recently, I began implementing the Google Recaptcha Web service on my website to combat spamming. I decided to use AJAX with a combination of Javascript and PHP to respond to my web pages. After following all the steps outlined in the Google Code Recaptcha ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

Generate an array in JavaScript using the values from input fields

Is there a way to create a JavaScript array that stores the values of all input fields with the class 'agency_field', when there are x number of these fields in the form? I attempted to achieve this using jQuery, but encountered a syntax error. ...