Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle!

Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The objective is to place this function at a centralized location (e.g., website.com/global-api.js). Our aim is for any developer to access this function from their respective sites (website.com/mysite.html), passing the dataset they wish to retrieve as an argument and modifying it as needed. I have included a rough diagram depicting this requirement, although its usefulness may be limited.

global-api.js

function globalApi(value){
    var setApiProp = {
        settings: { name: value },
        init: function(){ 'use strict';
            s=this.settings;
            this.getApiData(s.name);
        },
        getApiData: function(attr){
            path = '/api/'+attr;
            console.log('Get from: ' + path)

            var jqxhr = $.ajax({
                url: path,
                method: "GET",
                dataType: "json",
                async: false
            })
            .done(function(responseData){
                console.log('Response is: ' + responseData)
                return responseData
            })
        }
    }; //end
    setApiProp.init()
}

unitone.js

Within a DOM content loaded event:

var retrievedData = globalApi("news/")
console.log('Retrieved is: ' + retrievedData)
developersFunction(retrievedData);

The invocation from unitone.js successfully generates the correct path and retrieves the accurate data in globalApi. However, my current logs display;

Response is: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Retrieved is: undefined
Developer function data is: undefined

My query pertains to a reliable method of ensuring developersFunction waits until retrievedData is assigned before utilizing it in local functions?

Diagram illustrating the requirement: Unit files accessing function from central location

Answer №1

To ensure your function executes only after receiving a response from the API, you'll need to pass a callback function to the globalAPI function. Here's an example:

function globalApi(value, callBack)

When calling this function, include the desired function as an argument, such as developersFunction in your case:

globalApi("news/", developersFunction)

Within the globalAPI function, when the response is received, invoke the provided callback function like so:

.done(function(responseData){
                console.log('Response is: ' + responseData)
                // Log: Response is: [object Object],[object Object]..
                callBack(response);
  })

This approach ensures that your function will only run once the API response is obtained.

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

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

Efforts to toggle visibility of icons in React

One issue I encountered is with the Navbar in mobile mode, where the icons are covering the menu. Refer to the image for a visual representation of the problem. To address this issue, my plan is to hide the icons when the hamburger icon is clicked. Below ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

React Redux causing React Router to display empty pages

In my App.js, the following code is present: const Index = asyncRoute(() => import('~/pages/index')) const Register = asyncRoute(() => import('~/pages/register')) const AddDesign = asyncRoute(() => import('~/pages/add-des ...

Bring to the front the div altered by a CSS3 animation

Recently, I encountered an issue with a div card that triggers an animation when clicked. The animation involves the card scaling up larger, but the problem arises as its edges get hidden under other cards. To visualize this, take a look at the screenshot ...

How to retrieve a refined selection of items

In my scenario, there are two important objects - dropdownOptions and totalItem The requirement is as follows: If 12 < totalItems < 24, then display "Show 12, Show 24" If 24 < totalItems < 36, only show "Show 12, Show 24, Show 36" This patte ...

What distinguishes submitting a form from within the form versus outside of it?

When the code below, you will see that when you click btnInner, it will alert 'submit', but clicking btnOuter does not trigger an alert. However, if you then click btnInner again, it will alert twice. Now, if you refresh the page: If you first ...

JQuery Datatables: Struggling to make JQuery function work following AJAX update

Watch this screencast to get a clearer understanding of the issue.... I'm currently working on my first project involving AJAX, and I'm encountering some obstacles. The datatable is loading user details from a JSON output using AJAX. Each row ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

Navbar in bootstrap appears to be flashing when it is in its expanded

Example Link On smaller screens, the bootstrap navbar menu does not collapse by default when clicking on a menu item. To fix this issue, I added attributes data-toggle="collapse" and data-target="#navbar-collapse" to each menu item so that the menu will ...

When attempting to send an array value in JavaScript, it may mistakenly display as "[object Object]"

I queried the database to count the number of results and saved it as 'TotalItems'. mysql_crawl.query('SELECT COUNT(*) FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, count) { var ...

The image fails to display correctly

As I work on creating a basic webpage in HTML and JavaScript, my goal is to validate certain parameters (such as width, height) of an image that users upload via a form. In JavaScript, I extract the file from the form and attempt to display it as an image ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Embedding a table inside a Bootstrap popover

I'm struggling with adding a table inside a Bootstrap popover. When I click on it, the table doesn't show up. This is my first time trying to insert HTML into a popover, so I don't know the correct way to do it. Any help would be appreciated ...

Stop jQuery Tab from Initiating Transition Effect on Current Tab

Currently, I am utilizing jQuery tabs that have a slide effect whenever you click on them. My query is: How can one prevent the slide effect from occurring on the active tab if it is clicked again? Below is the snippet of my jQUery code: $(document).read ...

Displaying website content within a pop-up dialog box

Currently, I am delving into the world of AJAX calls using jQuery.get() to dynamically load website content onto my HTML page. However, I have some doubts about whether I am utilizing this command correctly. As an example, I am trying to fetch data from a ...

How can I use AngularJS to show a JSON value in an HTML input without any modifications?

$scope.categories = [ { "advertiser_id": "2", "tier_id": 1, "tier_name": "1", "base_cpm_price": "", "retarget_cpm": "", "gender": "", "location": "", "ageblock1": "", "ageblock2": "", "ageblock3": ...

Changing the name of a file using NPM

Is there a way to change the name of a specific file in npm scripts? I need to modify files for distribution, but they must have different names than the original... I attempted using orn, however it only works on the command line and not as an npm script ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...