When using a custom AJAX function, make sure that bindings are functioning properly when setting properties within a callback in Ember

I've encountered some unexpected behavior while trying to set an Ember property inside a custom AJAX function callback.

The AJAX function is triggered in the route, as seen in the code snippet below. The success callback updates the 'session.ajaxStatus' property from 'checking' to 'success' when a successful response is received. It consistently logs 'route: success' in the console from the callback function.

The issue arises when I attempt to observe and react to that property in a component. Occasionally, the observer recognizes the update from 'checking' to 'success', but other times it does not.

My assumption is that this discrepancy could be due to the varying response times. To address this, I wrapped the AJAX function in Ember.run to ensure it operates within the Ember run loop.

How can I guarantee that the observer binding always functions correctly? Should I consider revising the entire approach?

Route:

session: Ember.inject.service(),

...

actions: {
  ajaxRequest: function() {
    Ember.run(this, function() {
      var self = this;
      var url = self.get('session.url');
      self.set('session.ajaxStatus', 'checking');
      console.log('route: ' + self.get('session.ajaxStatus'));
      Ember.$.ajax({
        url: url,
        type: "GET",
        success: function(response) {
          console.log('success response');
          callBack(response);
        },
        error: function(response) {
          self.set('session.ajaxStatus', 'error');
        }
      });
      callBack = function(jobsInLicense) {
        self.set('session.ajaxStatus', 'success');
        console.log('route: ' + self.get('session.ajaxStatus'));
        //Always logs 'route: success'.
      };
    });
  },
}

Component:

session: Ember.inject.service(),

checkAjaxStatus: function() {
  console.log('component: ' + this.get('session.ajaxStatus'));
  //Sometimes nothing is logged.
}.observes('session.ajaxStatus'),

Answer №1

If feasible, it is best to avoid using an observer in this case. The necessity of its use depends on the actions required within the checkAjaxStatus function.

In reference to your query, While inside the route, there is no need to encapsulate it in Ember.run.

export default Ember.Route.extend({
    session: Ember.inject.service(),
    actions: {
        actions: {
            ajaxRequest() {
                var self = this;
                var url = self.get('session.url');
                self.set('session.ajaxStatus', 'checking');
                Ember.$.ajax({
                    url: url,
                    type: "GET",
                }).then(function(response) {
                    self.set('session.ajaxStatus', 'success');
                }, function(jqXHR, textStatus, errorThrown) {
                    self.set('session.ajaxStatus', 'error');
                })
            },
        }
    }
});

Regarding your component code,

session: Ember.inject.service(),

checkAjaxStatus: Ember.observer('session.ajaxStatus', function() {
        console.log('component: ' + this.get('session.ajaxStatus'));
        //At times, nothing gets logged.
    }),

Also, be sure to include {{session.ajaxStatus}} within the component's Handlebars code.

I performed a test in twiddle, which you can review for further insight.

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

What steps can be taken to resolve the issue of the Cannot POST /index.html error?

Here is an example of a calculator app created using HTML and Javascript. Upon running the program with nodemon and accessing localhost:3000, pressing the submit button triggers an error on Google Chrome. [nodemon] starting `node calculator.js` Server sta ...

How can a controller in AngularJS detect when the back button of the browser is pressed

I've created a browser trivia game where authenticated players can select a game type, triggering a socket.io event in my Node.js server. The view then transitions to a "Searching for game" screen with a loading icon as the server waits for enough pla ...

What is the sequence of the middlewares for error handling and handling of 404 errors?

The express.js website has confused me with contradictory statements regarding error-handling middleware. According to one page, you should define error-handling middleware last, after other app.use() and routes calls. However, another page states that you ...

Implementation of Oriented Bounding Box (OBB) in THREE

After utilizing the Yuka_OBB implementation to create an oriented bounding box, I have some inquiries about the results achieved: Bed (AABB) https://i.sstatic.net/OgZBU.png Bed (OBB) https://i.sstatic.net/fzOOW.png Wall (AABB) https://i.sstatic.net/R ...

Oops! It looks like there was an error. Remember that AJAX events should be connected to the

I am completely new to the world of Ajax and unfortunately, I encountered an error message in my browser: "JQMIGRATE: AJAX events should be attached to document: ajaxComplete" After some research, it seems like I need to incorporate certain Ajax functi ...

Verify if the current day falls within the range of Monday to Sunday using Node.js

Currently developing a food delivery app similar to foodpanda. Encountering an issue where a restaurant's operating days are from Monday to Friday, and I need to prevent users from placing orders on Saturdays and Sundays (or any other specified servic ...

"Encountering a 'Cannot GET' error message while utilizing Rest API in Node.js

Currently, I am developing a project using nodejs along with the expressjs framework. My focus right now is on setting up and running a "Rest Api," but I seem to be encountering an error message that reads: Cannot GET /published Let me share my routes fil ...

Error 403: ACCESS DENIED - The server comprehended the inquiry, yet declines to carry it out

Encountering a persistent 403 error when making an AJAX call to an API. This issue is specific to Microsoft Edge, while other browsers like IE, Chrome, Firefox, and Safari work without any errors. The page doesn't utilize bootstrap, as there have be ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

Accept only numerical values, addition and subtraction symbols, commas, the F5 key, and various other characters

I want to restrict key strokes to only numbers (including those on the numpad), minus (-) and plus (+) signs, and commas (,). Currently, it types twice when I input a number (e.g. 2 is displayed as 22) and replaces the current value with the new number. F ...

Encountering an Uncaught TypeError: Attempting to call a controller function using AJAX in Magento results in undefined not being a function

I've developed a custom module in the admin panel called createadmincontroller. It's configured in the config.xml file. I'm trying to call the controller index function from a .phtml file using Ajax, but I keep getting an error that says "Un ...

Strategies for combining objects with varying structures on a map

SUMMARY: Looking to merge the data from Students into the corresponding values of Employees, where the value from Students should be included in the same array as Employees['avg_rate' and 'expense']. The updated object array should be ...

Transform for loop from Axios post requests to promises

I am currently working with a loop of axios requests: for(const [number, response] of Object.entries(questions)){ axios.post( this.address+'surveypost', {"patientID": patientID, "questionID": number, "lik ...

Encountering issues with MediaSession.setPositionState() and seekto functionalities not functioning properly

Having trouble with MediaSession.setPositionState() not displaying the audio time and seekbar not behaving as expected. const sound= document.querySelector('sound'); function updatePositionState() { if ('setPositionState' in navigato ...

Having trouble with an endless GET request loop in NextJS 13 while utilizing the Next-Auth middleware. Experiencing difficulties fetching the RSC payload

UPDATE: The issue has been identified! It seems that the bug is caused by using the beta turbopack. I have reported this problem and we are awaiting a resolution. Query: I recently delved into a project in NextJS 13 with the new app directory setup. Afte ...

Update a specific div using Ajax with auto-refresh functionality

I am attempting to implement an automatic refresh every 5 seconds on a div using AJAX intervals, but I seem to be missing something. Here is the code for my div: <script> function loadlink(){ $('#chart').load(function () { ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Excess space at the bottom of the Heatmap chart in Highcharts

I am facing an issue with a heatmap having extra space at the bottom that I cannot seem to remove. Despite trying various solutions from different Stack Overflow threads, such as adjusting chart.marginBottom, chart.spacingBottom, x and yAxis margins, and d ...

Display a collection of objects using Jade / Pug syntax

Struggling to find resources on Pug / Jade templating, turning to this platform for help. I've been diving into documentation on iterations along with consulting this helpful link. Working with Node.js, Express, and pug for a school project - a mock ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...