setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically

request.onreadystatechange = func
. Even though I receive a response from the server when making the ajax request, the function func is not being called. It's important to note that func is passed as a string parameter when calling
getFromServer("http://localhost/ch02/checkName.php?username=sas","func")

function createRequest() {
    try {
        request = new XMLHttpRequest();
    }
    catch (failed) {
        request = null;
    }
    finally  {
        return request;
    }
}

function func(){
    alert("ok");
}

function getFromServer(url, readystateCallback) {
    request=createRequest();
    if (request == null) {
        alert("unable to create request");
    } else {
        request.open("GET", url, true);
        var func= new Function(readystateCallback);
        request.onreadystatechange = func;
        request.send(null);
    }
    return request;
}

Answer №1

When a function is defined in the global scope, it will be automatically added to the window object. This allows you to access the function using:

var func = window[readystateCallback];

However, instead of relying on this method, it is recommended to create your own object that acts as a map for function names to actual functions. This approach not only enables you to access functions within a local scope but also prevents accidentally calling an unexpected function as a callback.

function func() {
    alert("ok");
}
function otherfunc() {
    alert("really great");
}
...

var callbacks = {
    "func": func,
    "otherfunc": otherfunc,
    ...
}

With this setup, you can then use:

function getFromServer(url, readystateCallback) {
    var request = createRequest();
    if (request == null) {
        alert("unable to create request");
    } else {
        request.open("GET", url, true);
        var func = callbacks[readystateCallback];
        request.onreadystatechange = func;
        request.send(null);
    }
    return request;
}

Alternatively, the preferred solution is to pass the function itself rather than its name initially. This aligns with how most Javascript interfaces that utilize callbacks operate. You would call it like this:

getFromServer("http://localhost/ch02/checkName.php?username=sas", func);

Then you just need to do:

request.onreadystatechange = readystateCallback;

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

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

Learn the process of converting Null values to empty strings within a chain of functions when manipulating a database

Currently, I am utilizing the lodash library and have the following code in place: data: _(responseData.data) .pick(['title', 'layout', 'slug', 'author', 'seo', 'css', 'js']) ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

Learn how to pull values from a single JsonNode into multiple beans within a Play Framework controller

In my Java project using Play Framework, I am working with jQuery Ajax to post data in the form of a String representation of JsonNode. When writing an action method in my controller class to handle this Ajax call, I encountered an issue. The data being s ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

The user's input is not being accurately represented when making an AJAX request to the

When attempting to incorporate a user's city input (e.g. Los Angeles) into Ajax URL parameters, there seems to be an issue where the '+' is not being added between "los angels", resulting in a broken URL when console.log(searchURL) is used. ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Encountering a persistent Unhandled rejection Error while utilizing NodeJs with Bluebird library

Currently in the process of developing a daemon that listens to TCP connections, sends commands, and listens for events. I made the decision to utilize bluebird to eliminate callbacks, but I'm encountering an issue. I can't seem to catch a rejec ...

The breeze is puzzled by the altered being, unable to identify it

I am currently working on a breeze implementation that involves displaying properties from a location object on the UI. However, when I make changes to some properties and attempt to save them, breeze does not recognize the entity as being changed. Here is ...

Extracting specific keys from JSON data

I am working with an array named cols: var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic The JSON data is coming from the backend as: info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84} If I want to sel ...

Accessing a remote server is blocked in Phonegap Android Release builds

Having trouble with ajax requests in a Phonegap release build. Device: Samsung Galaxy S4 Issue: When using the Phonegap app and 'phonegap serve': Successful method: Posting data to server using form with hidden iframe as target and action poi ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

jQuery allows us to set two separate conditions for two distinct variables

I've written this function: settings_rc_left.on('click', function(){ var settings_list_last_element_id_one = settings_menu_element.attr('id') == 'r_02', settings_list_last_element_id_two = settings_menu_eleme ...

Is it possible to utilize the AmMap API for developing an Android application?

I am currently in the process of creating a unique application with HTML, JS, and jQuery Mobile that will feature interactive maps. I have been searching the web for APIs to incorporate interactive maps into my project without using Google Maps APIs when I ...

Tips for creating a new route within a separate component in React JS without causing the previous one to unmount

I am currently developing a recipe website using React JS and React Router. On the HomePage, I have set up a display of cards, each representing a preview of a recipe. Each card is enclosed within a <Link></link> tag. When one of these cards ...

Is there a way to use AJAX for transferring a value?

I am looking to transmit a value to a php-script (servo.php) that will then write the received data in a file (/dev/servoblaster). The script section of my HTML file (index.html): <script> function tiltt() { var tilt = document.getElementById("tilt ...

How can you ensure seamless synchronization while logging in a user with ReactJS and retrieving data from the API?

Is there a way to synchronize and run these two functions in succession before calling console.log(user) and setLogin()? The goal is to ensure that all the information retrieved from the API is available in the user context before activating the setLogin() ...

What is the best way to use Javascript in order to automatically open a designated tab within SharePoint 2013?

Currently, I am in the process of developing a website project which incorporates Bootstrap tabs utilizing jQuery. While these tabs are functioning excellently on various pages, I am faced with the challenge of linking specific icons to corresponding tabs ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...