0

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:

  • self.option_id
  • self.option_name
0

2 Answers 2

4

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)
      }
    })
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.