2

I have the following AJAX function written in jQuery (just make AJAX call to get outcome for div A and div B - the example is simplified)

JavaScript

$(document).ready(function(){
    $( "#c" ).on( "click", function() {
        jQuery.ajax({
            type: "POST",
            url: "post.php",
            data: "",
            dataType:"JSON",
            success: function(data){
                if (data.status == 1){
                    $("#a").html(data.a);
                    $("#b").html(data.b);
                }
            }
        })
    })
})

HTML

<div id="a"></div>
<div id="b"></div>
<button id="c">Start</button>

I understand how to make the HTML template for vue.js and how to set JavaScript variables, but how do I to set AJAX request for vue.js?

Thank you.

2 Answers 2

2

Well, first thing first, you have to get rid of DOM Targeting with jQuery.In VueJS, there are no direct DOM manipulation. Next, you have to stop thinking jQuery way - Vue and jQuery are 2 totally different things which have different design pattern.

About your problem:

First you have to attach event listener on DOM Element

<button id="c" @click="ajaxMethod">Start</div>

Then into your Vue instance, you want to define that method, but before you make it, make sure you have jQuery installed

new Vue({
  el: '#app',
  data: {
   msg: 'hi';
  },
  methods: {
   ajaxMethod() {
    jQuery.ajax({
      // bla bla bla...
    })
   }
  }
})

But at the end, I won't to suggest you use jQuery here - there are much better libs such as Vue Resource and Axios.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for pointing the difference between the data centric logic of Vue and the DOM manipulating approach of JQuery
1

The suggested way is to use the axios library.

<div id="app">  
  <div>{{a}}</div>
  <div>{{b}}</div>
  <button @click="retrieveData">Start</button>
</div>

Where the Vue instance is

import axios from 'axios'
new Vue({
  el: '#app',
  data: {
    a: '',
    b: ''
  },
  methods: {
    retrieveData() {
      axios.post('post.php', {}, )
       .then(resp => {
         this.a = resp.data.a
         this.b = resp.data.b
       })
    }
  }
})

9 Comments

Hi, thank you very much for the answer, is the Axios library a part of vue.js or must be loaded separately?
Testing now, I get the following error: SyntaxError: import declarations may only appear at top level of a module
Make the import declaration appear at the top of the file
How is different from using jQuery inside retrieveData method?
It depend on the environment you are using import it the same way you imported jquery
|

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.