The issue of data binding not refreshing in vue 2.3 with AJAX requests

Following a successful AJAX request, there is an issue with the updated data not displaying on the page. Instead, it remains empty or null.

There seems to be a disconnect between the data returned as a front-end variable and the dynamically rendered HTML elements.

Below are the code snippets for better understanding. Can you identify what is missing or incorrect?

Javascript

page = new Vue({

  el: "#container",

  data: {
    option_id: null,
    option_name: null
  },

  created:function() {

    $.ajax({
      type: 'POST',
      contentType: 'application/json',
      dataType: 'json',
      url: 'ajax_methods/get_option',
      success: function (ajax_data) {

        self = this;

        self.option_id = ajax_data.option_id;        
        self.option_name = ajax_data.option_name;

      },
      error: function (e) {
        console.log(e)
      }
    })

  }
})

HTML

<script type="text/javascript" src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483e3d2d087a667b">[email protected]</a>"></script>
<div id="container">

  <p>{{ option_name }}</p>

    <button v-on:click="send_option()"
      type="button"
      id="left_button"
      name="left_button"
      v-bind:value="option_id">

</div>

Checking AJAX success

Upon inspecting in the console, non-null values are being returned as expected when the following variables are checked:

  • self.option_id
  • self.option_name

Answer №1

Make sure to assign this outside of the callback function.

initialize: function(){

    const outerThis = this;

    $.ajax({
      type: 'GET',
      contentType: 'application/json',
      dataType: 'json',
      url: 'ajax/endpoints/get_values',
      success: function (apiResponse) {

        outerThis.value1 = apiResponse.value1;        
        outerThis.value2 = apiResponse.value2;

      },
      error: function (err) {
        console.log(err)
      }
    })
}

Answer №2

Initially, if that code snippet is accurate, it appears that self is not properly initialized. Consider using either var self = this or let self = this

More importantly, ensure that self is defined outside of the ajax call. In JavaScript, the this keyword references the calling object. Within the created() function, it represents the Vue instance. However, within the ajax callback, this will not point back to the Vue instance.

Enhance your grasp of JavaScript's "this" concept and master it using this resource

created:function() {

   var self = this    
   $.ajax({
      type: 'POST',
      contentType: 'application/json',
      dataType: 'json',
      url: 'ajax_methods/get_option',
      success: function (ajax_data) {

        self.option_id = ajax_data.option_id;        
        self.option_name = ajax_data.option_name;

      },
      error: function (e) {
        console.log(e)
      }
    })

  }

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

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

Can someone advise me on how to ensure my function effectively delivers a desired outcome?

My goal is to learn Javascript on my own, but I'm struggling to make progress. I've created a function called fixedSpending() that takes two inputs, num1 and num2, and adds them together. However, when the user hits the "=" button, I expect the f ...

Is it always the case that modifying the props of a child component will trigger a re-render of the parent component, even

I am currently exploring ways to prevent a modal element from re-rendering when it is supposed to be hidden. The tutorial I am following suggests converting the component to a class-based one and using shouldComponentUpdate(). However, I wanted to test if ...

What is the best way to display a button only during office hours from 9am to 5pm using React.js or JavaScript?

If I want a button to only be visible from 9am to 5pm, how can this be achieved where the button is hidden outside of that time frame? ...

The request for an advertisement was successful, however, no ad could be displayed as there was insufficient ad inventory available. Please handle the situation appropriately with the

Using react-native, I am trying to incorporate ads into my app but encountering an error. Despite attempting various solutions, nothing seems to work. It appears that the issue may lie with the AdMob Android SDK. While I have reviewed SDK videos related to ...

How can you convert Promise.all to a single Promise?

I have successfully implemented two API calls using Promise.all method with no issues. Even though one API call is sufficient to retrieve the results, I decided to stick with Promise.all and it's still working fine. I attempted to replace Promise.al ...

What is the best way to convert a circular JSON object to a string

Is there a way to stringify a complex JSON object without encountering the "Converting circular structure to JSON" error? I also need its parser. I am facing issues every time I try to use JSON.stringify and encounter the "Converting circular structure to ...

Steps for utilizing Bazel to compile TypeScript

Calling all Bazel (Blaze) experts: I'm curious about the best method for integrating Bazel as a build system for cutting-edge web applications built in Typescript. Is there a preferred setup or perhaps a template that demonstrates this integration? T ...

Obtaining objects from a Meteor collection on the server triggers a "Must have Fiber to proceed" error

As a beginner in creating meteor apps, I am working on a project that involves querying git issues from a specific repository. The goal is to generate tasks from these issues after retrieving them using the Github API. However, I keep encountering an error ...

Nuxt - Vue - Utilizing middleware on a layout in a few simple steps

Recently, I developed a middleware for authentication in my Nuxt application and now I want to utilize it within a layout. However, when trying to call the middleware using the following code: export default { middleware: 'auth', I encounte ...

What is the most effective way to set up HTTPS for handling all connections in Node.js?

In my project to create a stateless authentication system using Double Submit Cookie in Node.js/ExpressJs, I am exploring ways to ensure all connections are made over HTTPS. My goal is to optimize for handling high traffic while also prioritizing security ...

Populate the label text within a Gridview by parsing JSON data through AJAX

I am currently working with a grid view that obtains data from a vb.net class object. The gridview contains a TemplateField with a label control, as shown below: ...

ng-html-bind for a label with a checkbox

Currently, I have a view that uses the standard bootstrap layout for checkboxes. In this layout, the input is located within the label tag. <div class="checkbox"> <label ng-bind-html="vm.trustedHtml"> <input type="checkbox" ng- ...

Removing the dollar sign and retaining only the numerical values in an array using JavaScript

Using the code snippet below, I am attempting to retrieve elements by their class name in JavaScript and save them in an array. This is the current output I receive: "I received this output from the initial prices array $30.00, $20.00, $40.00" My inquiry ...

Display the output returned from the AJAX request (HTML and/or JavaScript)

How can I effectively render content from an ajax call when the response may include html and/or javascript? I used to rely on document.write() for synchronous calls, but now that I need to use asynchronous calls, I have to find a different approach to dis ...

Learn how to use jQuery to load a text file containing arrays and then format them as

I'm attempting to load a .txt file containing multidimensional arrays using AJAX, and then sort through the data to display it on my website. However, I'm facing an issue where the data is only returning as plain text, even after trying to use JS ...

Updating textbox values with ajax results in the page refreshing and the newly assigned values being lost

I'm currently working on updating a section of my webpage using AJAX instead of C#, as I don't want the page to refresh. All I need to do is execute a SELECT query to retrieve the current client from the SQL database and populate the correspondin ...

Is it possible to obtain the parameters using an empty object with the getStaticPaths function?

Within the getStaticPaths function, a path is returned with params postId:1. If additional params like postId: 2 or postId: 3 are included, they will also be statically generated. Is my understanding correct? Is there a way to avoid loading any post based ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

Can you use the OR operator between vee-validate3 rules?

For this input, the value can be either a username or email address. Here is an example: <ValidationProvider name="email" rules="username || email" v-slot="{ errors, valid }"> <v-text-field v-model="something" :error-messages="er ...