What is the best way to ensure that $.getJSON executes before $http in Javascript?

Within my web page controller, I have implemented the following Javascript code:

 $.getJSON('resources/properties/properties.json', function(data) {
    $scope.properties = data; 
    });

$http({
    method: 'GET',
    url: $scope.properties.Properties.dataLocation
        }).
        success(function (data) {
        $scope.all_types_and_configs = data;
        $scope.exec = [];    
        }).
        error(function (data) {
        $scope.error = data.message;
        $scope.data = '';
        return;
        });
});

The format of the json file being fetched is not causing any issues.

The intention is for the $.getJSON command to be executed first and then followed by the $http request. However, when I attempt to display "properties" using a console.log just below it, the output is "undefined."

Why is the sequence of execution not following the order in which it has been written?

Answer №1

The code is running sequentially, with callback functions executing upon completion of corresponding requests. To ensure the second call is made after the first request completes, place it within the first callback function:

$.getJSON('resources/properties/properties.json', function(data) {
    $scope.properties = data;
    $http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
        success(function (data) {
            $scope.all_types_and_configs = data;
            $scope.exec = [];    
        }).
        error(function (data) {
           $scope.error = data.message;
           $scope.data = '';
           return;
        });
});

Answer №2

The execution is asynchronous, allowing both calls to be made independently. When using $.getJSON, utilize the third parameter - success callback - to synchronize them. Check out the documentation for more information.

Why are you combining jQuery AJAX and Angular $http?

Answer №3

If you want to ensure that your code runs only after a request has been completed, you can utilize the JQuery.done function.

Here is an example of how you can achieve this:

(function() {
  var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
    .done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
        if ( i === 3 ) {
          return false;
        }
      });
    });
})();

Answer №4

Just like how you've successfully executed the line $scope.properties = data; after receiving the JSON, you need to place it within the callback function that you pass to getJSON.

Why isn't the code running in the order it's written?

Actually, it is.

When you use getJSON(url, foo), it indicates "Send an HTTP request to the specified URL and set up a function foo to be called upon receiving the response".

You might be expecting it to pause and wait for the response before proceeding with anything else. However, that would freeze the user interface and cause a negative experience.

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

Ways to customize pixel scrolling on page reload or through the use of a hyperlink to a specific tab in a page

I have implemented a Bootstrap panel using the following code: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab&qu ...

"Turn a blind eye to Restangular's setRequestInterceptor just this

When setting up my application, I utilize Restangular.setRequestInterceptor() to trigger a function that displays a loading screen whenever a request is made with Restangular. Yet, there is a specific section in my application where I do not want this fun ...

Implement a code to apply to an image that is loaded dynamically

I have a situation on a page where an image is loaded via ajax within a wrapping div. I need to execute some code as soon as that image is loaded. Unfortunately, I am unable to modify the ajax call, which means using on('success') directly on the ...

What is the best way to apply CSS modifications to sibling elements that are related?

I have several parent div elements with pairs of button and div child elements. My goal is to apply changes to the corresponding div when a button is clicked. For example, clicking Button 2 should only affect toast 2. However, I am facing an issue where o ...

Split the text using the newline character (' ') and not the double newline character (' ')

Looking to create a filter that separates all \n and combines them back as \n\n. Is it possible to only target the single \n without affecting the double \n\n? Currently, the issue arises when the input field loses focus, caus ...

Reactjs and Redux encounter an Unhandled Rejection with the error message stating "TypeError: Cannot read property 'data' of undefined"

Encountering an error while implementing authentication with react + redux. When attempting to register a user in the redux actions using async / await, I consistently receive this error within the catch block. Here is the snippet of the actions code: imp ...

AngularJS mouse event is triggered repetitively within a loop

My goal is to activate the function setHighlight when a li element is hovered over with a mouse. The ng-mouseover event is employed within an ng-repeat loop. The problem arises when hovering over a li element: the ng-mouseover event gets triggered multipl ...

Unable to deactivate button using JavaScript following an AJAX request

Within my JS file, I am attempting to disable a button after making an AJAX call: $('document').ready(function() { const runField = $('input[id=run]') const runButton = $('.btn-run') const saveButton = $('.btn-save ...

The injector is currently updating the initial value in the test

I am currently testing one of my injectable components by using a provider to assign a mock value to APP_CONFIG. Here is the structure of the component: export let APP_CONFIG = new InjectionToken<any>('app.config'); @Injectable() export cl ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Showcasing Portfolio Work in a User-Friendly Mobile Design

Currently revamping my portfolio website and looking for ways to optimize the display of my personal projects. I have a card-like interface in place that works well on desktop but only shows one project at a time on mobile devices. Seeking solutions to imp ...

List-style-type outside of a table's boundaries

I recently experimented with using <ol> as list elements within a table in order to dynamically insert new table rows. <table> <thead> <tr> <th>head</th> <th>head</th> <th>h ...

What is the code for a non-breaking space in a JavaScript string?

It seems that this code is not functioning as expected: text = $td.text(); if (text == '&nbsp;') { text = ''; } Could it be related to a non-breaking space or the ampersand causing issues in JavaScript? ...

Using Jquery to Connect a Change Event to Child Elements

<form id="duration"> <label for="change-chart-type-24H" > ; <input style="display:none;" name="chart-type" id="change-chart-type-24H" type="radio" value="24H">24H ...

Tips for designing a versatile component to handle numerous buttons triggering form pop-ups

library used: mui 5.4.1 To implement a TableCell with an IconButton that triggers the opening of a Form, follow this code snippet. const items = [ { id: "001", name: "A", price: 2000 }, { id: "002", name: &q ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...

What to do when faced with an unexpected return in a requireJS application while running JSLint?

When setting up my application with `requireJS`, I have two key files: main.js is responsible for configuring everything, while app.js actually "runs" the application. This is how main.js is structured: /*jslint browser: true, indent : 2, nomen : true, ...

Creating a live notification in the chat that displays "User is typing" to all participants

I am working on developing a chat application using jQuery and PHP. I am looking for guidance on how to implement a feature where a user, let's say "Evx," types a message in real-time and it is instantly displayed to all other users. This functionalit ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...

The functionality of the controller is not functioning properly in AngularJS

The button syntax is <div class="btn-group" align="center"> <button ng-click="myFunction()" id="one" class='btn btn-primary btn1' >Save Entry</button> <button ng-click="close_window()" id="two" class='btn btn-pr ...