datavoredan
datavoredan

Reputation: 3746

vue 2.3 AJAX data binding not updating

After a successful ajax call the data rendered on the page is not updating. It is remaining empty / null.

It seems that I am missing how to connect the data returned as a front end variable and the dynamically / live rendered html elements.

Here is the relevant code snippets for context. Is it clear from this what is missing / 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/[email protected]"></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

When entering the following in the console, non null values come back as expected:

Upvotes: 0

Views: 1295

Answers (2)

ptpaterson
ptpaterson

Reputation: 9583

first, if that is the exact code, then self I don't think is initialized. Use var self = this or let self = this

But mainly, you need to define self outside of the ajax call. In javascript the this keyword refers to the calling object. directly inside of the created() function, it's the Vue instance. However, this will NOT refer to the Vue instance once inside the ajax callback.

Understand JavaScript’s “this” With Clarity, and Master It

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)
      }
    })

  }

Upvotes: 3

Bert
Bert

Reputation: 82469

You need to capture this outside the callback.

created: function(){

    const 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)
      }
    })
}

Upvotes: 4

Related Questions