Transfer the function reference to a standalone JavaScript file for use as a callback function

In an effort to streamline my ajax calls, I have developed a JavaScript file that consolidates all of them. The code snippet below illustrates this common approach:

function doAjax(doAjax_params) {
    var url = doAjax_params['url'];
    var requestType = doAjax_params['requestType'];
    var contentType = doAjax_params['contentType'];
    var dataType = doAjax_params['dataType'];
    var data = doAjax_params['data'];
    var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
    var successCallbackFunction = doAjax_params['successCallbackFunction'];
    var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
    var errorCallBackFunction = doAjax_params['errorCallBackFunction'];

       //Make the ajax call
    $.ajax({
        url: getBaseURL() + url,
        crossDomain: true,
        type: requestType,
        contentType: contentType,
        dataType: dataType,
        data: data,
        success: function (data, textStatus, jqXHR) {
            console.log(typeof successCallbackFunction);
            debugger
            successCallbackFunction(data);
            
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (typeof errorCallBackFunction === "function") {
                errorCallBackFunction(errorThrown);
            }
        }
    });
    }

This script receives parameters and generates an ajax request accordingly. It is stored in a file called APIHandler.js.

I am attempting to invoke this function from various files, as demonstrated in the example below.

function RedirectToDashboard() {
    var params = $.extend({}, doAjax_params_default);
    params['url'] = `profile/5`;
    params['successCallbackFunction'] = `testsuccess`;
    doAjax(params);

}

function testsuccess() {
    alert("success");
}

Although the function runs successfully, there is an issue with referencing the callback function. When executing

console.log(typeof successCallbackFunction);
, it returns string instead of function.

I initially suspected the sequence of loading JavaScript files mattered. Both APIHandler.js and the page-specific JS are loaded before the ajax call triggered by a button click event.

Additionally, I considered whether parameter passing might be incorrect, leading JS to interpret the function name as a string. However, research indicates that simply providing the function name should suffice.

Could there be any other oversight causing this behavior?

Answer №1

Wow, it finally clicked why the error was happening. I mistakenly used quotes when setting the callback function. Immediately after submitting my question, the solution dawned on me.

params['successCallbackFunction'] = 'testsuccess'

should actually be revised to

params['successCallbackFunction'] = testsuccess

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 values from PHP using AJAX to dynamically update input field values

I have set up a unique Custom Post Type in Wordpress named Location/Tour and another one called Itinerary. Within my CPT Itinerary, I have integrated some ACF custom fields, including a repeater field containing various subfields (such as Relationship fiel ...

Best approach in VueJS: Utilizing animation to display a single element from a group in a set

Let me explain my specific case: I want to create an input-widget that can display a large number of checkboxes, divided into three parts based on user-specified data. My plan is to initially hide these three subsections with a header indicating their pre ...

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

A guide on updating label text using JavaScript or jQuery following a click on an HTML form

Seeking a solution to modify the text underneath a name form element on a squarespace.com website. This platform aids in website creation, but direct manipulation of the source code is not allowed. However, injecting JavaScript is permitted. I have identi ...

What is the best method to extract text data from the Froala editor?

Currently, my method involves using $('div#edit').froalaEditor('html.get') to get the HTML data from the editor. Unfortunately, this process becomes problematic when trying to process or store the text data in my backend due to the pres ...

Hiding content: impossible to change. Acting independently?

Currently, I am attempting to showcase a count-down feature on my website (which is currently in localhost so it cannot be linked). However, I have encountered a very peculiar issue. I suspect that the JavaScript may be causing the display to not appear. ...

Switch between various height and width options using JavaScript

Is there a way to create a toggle that changes both the height and width of an element when it is clicked? <div class="flexbox-container" id="main" onclick="staybig()">Create Account</div> .flexbox-container { ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

Showing Angular 2 Data in JSON Format

When I retrieve an object with a Promise, it is structured as follows: export class ShoppingCart { Cart_Items: [ { Id: number, SKU: string, Link: string, ImageURL: string, Title: string, Description: str ...

Attempting to access fetch_array() on an array object has resulted in a fatal error

if($this->cuvant_cautat) { $this->cuvant_cautat = $this->bd->query("SELECT cuvant_raspuns FROM dc_asociatii WHERE cuvant_stimul='".$this->cuvant_cautat."' ORDER BY id DESC LIMIT 0, 5"); //echo $this->cuvant_c ...

What is the best way to avoid repeated guesses in a number guessing game?

I've implemented an array named 'tries' to keep track of the numbers guessed by the user. Once the user correctly guesses the number, the total number of tries and the guessed numbers are displayed. How can I prevent the user from guessing a ...

ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another fil ...

The JavaScript if statement does not appear to be accurate

I am encountering issues with my if, else, and else if statements. Here is the code snippet in question: function draw(d) { var testarray = JSON.parse(a); var testarray1 = JSON.parse(a1); var testarray2 = JSON.parse(a2); var Yaxis = $(" ...

Extracting data from a Firebase realtime database JSON-export is a straightforward process that can be

I'm currently working with a Firebase realtime database export in JSON format that contains nested information that I need to extract. The JSON structure is as follows: { "users" : { "024w97mv8NftGFY8THfQIU6PhaJ3" : { & ...

Establishing a user session with Node.js

I am new to the world of node.js and JavaScript in general. I have a piece of code that currently handles login functionality by checking if a user exists in a MYSQL database. This part is functioning correctly. Now, I wish to improve this feature by crea ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

A space designated for numerous receivers

Is there a way to create a field that contains other elements, similar to sending messages to multiple users in a social network? https://i.stack.imgur.com/P9e24.png I attempted to understand the code for this, but it's quite complex. If anyone could ...

layering information on the backstretch

My goal is to include a div with a specific title above the JQuery Backstretch images. The current code setup is as follows: <div class="col-md-4 col-xs-12"> <div class="imgs"> </div> </div> When I try to insert any conten ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

Switch the text style when hovering, then switch it back upon second hovering

Searching for a method to modify the font of individual letters when hovering over them. The goal is for the letters to revert back to their original font after a second hover (not on the first hover-off). Any assistance would be greatly valued! ...