datavoredan datavoredan - 2 months ago 28
Ajax Question

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/vue@2.3.3"></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:


  • self.option_id

  • self.option_name


Answer Source

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

  }