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

Submitting a form using Ajax without needing to navigate away from the current page

I'm facing an issue with submitting the Ajax form to prevent the page from redirecting to another page. The script I've implemented is still directing to trolley1.php instead of staying on the current product page. The objective is to send the da ...

TypeScript encountered an unexpected { token, causing a SyntaxError

Despite multiple attempts, I can't seem to successfully run my program using the command "node main.js" as it keeps showing the error message "SyntaxError: Unexpected token {" D:\Visual Studio Code Projects\ts-hello>node main.js D:&bsol ...

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Picture goes missing from slideshow

I am currently using a CSS + Javascript slideshow on my website, inspired by an example from the W3Schools website. Here is the code I have adapted for my web application: $(document).ready(function() { var slideIndex = 1; function showSlides(n) { ...

Identifying the hashKey and selected option in a dropdown menu

My attempt to set the selected option for the select menu is not working because the data in the ng-model that I am sending has a different $$hashKey compared to the data in the select menu, and the $$hashKey holds the values. <select class="form-contr ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...

What steps do I need to follow in order to perform a particle design simulation on my laptop

Recently, I attempted to utilize some of the particle designs featured on this website https://speckyboy.com/particle-animation-code-snippets/, but encountered difficulties. I have included both the stylesheet and javascript files, yet the design does not ...

Vue paired with Rainyday.js

I attempted to incorporate Vue with rainyday.js by following different resources, but unfortunately could not find any relevant information. Can anyone provide guidance on how to successfully implement rainyday.js with Vue? <body onload="run();"> ...

Unable to process JSON data object

Having trouble with processing a json object. The form on the page contains a dropdown where selecting a truck number should autofill the rest of the form with data from a json file. Sample data: [ { "truckNum":"62-559", "description":"MOF ...

Tips for sending form data along with a file upload in a single Ajax request without relying on the FormData object

Hey there! I've been on the hunt for a solution that allows me to send both regular form data from text inputs and file uploads in a single ajax call. Unfortunately, using FormData is not an option due to its limited support in IE. Do you know of any ...

Using jQuery to enable scrolling and dynamically changing classes

I'm currently working on enhancing my website with a feature that changes the opacity of the first section to 0.4 when a user scrolls more than 400 pixels down the page. I attempted the following code without success: if($("html, body").offset().top ...

Angular and Firefox are flagging the response from my OAuth call as incorrect, however, Fiddler is showing a different result

Currently, I am in the process of developing a Cordova application and require OAuth authentication with my Drupal backend. My main issue lies in obtaining a request token for this purpose. Despite receiving a 200 response indicating success, when inspecti ...

Trouble with firing the click event using document.createElement('a') in Firefox

I wrote a function that fetches arraybuffer data from my API, generates a temporary anchor element on the webpage, and then triggers a click event to download the file. Interestingly, this function performs as expected in Chrome. @action async loadVouc ...

JavaScript code altered link to redirect to previous link

I added a date field to my HTML form. <input type="date" name="match_date" id="matchDate" onchange="filterMatchByDate(event)" min="2021-01-01" max="2021-12-31"> There is also an anchor tag ...

Double Tap Required to Update AngularJS Scope

Controller: // Modal Controller app.controller("ModalCtrl", ["$scope", "$filter", function($scope, $filter) { var date = new Date(); var currentDate = $filter('date')(new Date(), 'MM/dd/yyyy'); // Form Submit Actions $scope.s ...

Can multiple print buttons in different modals be connected to individual divs within their respective modals?

I am currently developing a webpage using the Foundation 5 framework that features a table of information. Each row in the table contains a link that, when clicked, opens a specific modal displaying detailed information related to that row. I want to add a ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Creating .ipa Files with React Native

Is there a way to generate .ipa files in React Native for iOS without using XCode or an Apple Developer Account? Many references have not been successful in helping me achieve this. I attempted to build from XCode, but encountered issues with provisi ...

Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state. <VideoPip :asset="asset" v-show="pipEnabled === true" /&g ...