VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed.

The AJAX call executes successfully and updates data.message with the line:

self.message = 'Love the Vue.JS'

Although the console confirms that it works, the issue arises when the DOM does not reflect the new value of data.message. How can I ensure that the DOM gets updated when the data changes?

var app = new Vue({
  delimiters: ['[[', ']]'],
  el: '#app',
  data: { message: 'Hello Vue.js!' },
  methods: {
    fetch_data: function() {
      console.log('Executing ajax operation...');
      $("#retrieve_data_wait").text("Fetching data. Update will be displayed when ready...");

      $.ajax({
        url: '/test_json',
        dataType: 'json',
        timeout: 60000,
        success: function(data) {
          $("#retrieve_data_wait").text(data.test);
          self.message = 'Love the Vue.JS';
          console.log('SUCCESS')
          console.log(self.message);
        },
        error: function(data) {
          $("#retrieve_data_wait").text("Fail");
        }
        // error: function(jqXHR, status, errorThrown) {
        //   //the status returned will be "timeout" 
        //     alert('Got an error (or reached time out) for data generation.  Please refresh page and try again.  If you see this more than once, please contact your customer success agent.');
        // }
      });
    }
  }
})
<div id="app">
  <span id="retrieve_data_wait"></span>
</div>

Answer №1

One issue arises when the context of your code is lost while calling jQuery. The callback method you are using (success: function) lacks a reference back to Vue. To maintain the correct context, you can utilize the context property in your $.ajax call.

You can find detailed information on this topic on the jQuery website: https://api.jquery.com/jQuery.ajax/ - simply search for "context" to locate relevant documentation.

An improved version of your ajax call might resemble the following code snippet:

$.ajax({
  url: '/test_json',
  context: this,
//  [... etc ...]
  success: function(data) {
    this.message = "reference to Vue data message";
  }
);

Answer №2

To integrate the ajax call with the parent component in Vue, simply append bind(this) at the end of the success callback for the ajax request. The revised code snippet below illustrates the updated implementation:


    $.ajax({
       url: '/fetch_data',
       // additional parameters
       //... and so on
       success: function(response) {
         this.data = "updated data from Vue";
       }.bind(this),
    );

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

Issue encountered when attempting to execute a JavaScript AppleScript from another JavaScript AppleScript due to permissions error

I am in the process of organizing my .applescript files by separating them into different ones for better organization. Within my JS AppleScript file named Test.applescript, I am attempting to execute another JS AppleScript file called Group Tracks Depend ...

What is the best way to compare the previous and next values in React?

When working with the code snippet below to send a list of values to another component - React.createElement("ul", null, this.state.stock.map(function (value){ return (React.createElement(Price, { price: value })) }) ) the values are then sent t ...

Top replacements for jQuery in AngularJS applications

It would be great to compile a comprehensive list of jQuery alternatives that are compatible with AngularJS, capable of manipulating styles (css), and supporting effects like fadeIn, fadeOut, slideDown, slideUp, etc. Based on feedback from comments, we sh ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Keep a close eye on your Vue app to make sure it's

<template> <v-form :model='agency'> <v-layout row wrap> <v-flex xs12 sm12 lg12 > <v-layout row wrap> <v-flex xs12 md12 class="add-col-padding-right"> <v-radio-group v-mod ...

Tips for properly rendering contenteditable content in Laravel and Vue applications

I have successfully saved the content inside the #descrition section below. <div id="description" contenteditable="true"></div> The issue I am facing is that when I try to display it, it does not show in an HTML format. Instead, it displays e ...

Form with several file selection points

I am working on an application that features a dynamic form capable of uploading files to different individuals simultaneously. Each person is assigned a unique input file and has the option to add up to 2 additional dynamic inputs. <div id="InputsWra ...

"Troubleshoot: Inadequate performance of table search in node.js due

Embarking on a journey of learning here excites me. I have an insatiable appetite for new knowledge! Grateful in advance for any assistance! Presenting a concise Node.js JavaScript code snippet of 30 lines for a standard table search process. The "table" ...

Utilize a vacant implementation of an interface

I have a simple interface called EmployerContact. I'm wondering how I can create an empty object, mockEmployerContact, of type EmployerContact and then assign values to its properties later on. Do I need to start with default values for this object? e ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Tips on avoiding duplicate selection of checkboxes with Vue.js

Recently delving into vue.js, I encountered a challenge with multiple checkboxes sharing the same value. This resulted in checkboxes of the same value being checked simultaneously. How can this issue be resolved? var app = new Vue({ el: '#app&apo ...

"Troubleshooting the issue of null values in ASP.NET Core Razor Pages when using Ajax POST

I'm currently working on an ASP.NET (6.0) Razor Pages project where I am facing an issue with posting data using AJAX. Despite my efforts, the posted data always ends up being null. Even after going through similar questions on Stack Overflow, I have ...

Navigating through the layout in Vue.js2: routing behavior

I am in the process of designing a layout that includes: +-------------------------------------------------+ | HEADER (STATIC) | +-------------------------------------------------+ | FOREWORD (just homepage; dynamic ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

How can I configure Express to act as a pass-through proxy server?

How can I set up an express server to act as a proxy? Requirements: Support for both http and https Ability to function behind a corporate proxy Option to provide custom content for specific URLs I have experimented with various modules such as http-pr ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

In an effort to bring some flair to my React Hangman App, I am working on animating a collection

Challenge In my Hangman App, I am attempting to implement letter animations using react-spring. I want the letters from an array to fade in when loaded and fade out when removed by clicking on them. However, my previous attempts have resulted in laggy per ...

Cut off the initial characters in the URL's hash component

Hey there, I'm currently working on a task that involves removing a specific part of a URL string. Here's the scenario: if (window.location.hash == '#super-super-product') { change.window.location.hash.to.this: #product // this i ...

block the UI when a certain amount of time has passed

When I click on a button, I implement the following code: $(document).ready(function () { $('.find').click(function () { $.blockUI({ message: '<table><tr><td><img src="images/pleas ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...