Reputation: 6787
I have a form with a button other then submit button. I would like Vue to call a Django view asynchronously when that button is clicked and return a JSON message saying function was called successfully.
Upvotes: 1
Views: 1507
Reputation: 6787
Jquery and Vue dont work well together. Vue works inside Jquery but Jquery doesnt work inside Vue. Better option is to use Axios for Ajax. Call axios inside Vue method.
axios.defaults.xsrfCookieName = 'csrftoken' //need this for method:post
axios.defaults.xsrfHeaderName = 'X-CSRFToken' //need this for method:post
var vue_app = new Vue({
el: '#id_xyz',
data: {
vue_var1:'hello',
vue_var2:[],
},
methods:{
ajax_method_name1:function(){
console.log('Vue ajax_method_name1 is called');
axios({
method: 'post',
url: 'ajax/url1/',//your customer url that is set in backend to do Ajax work
data: {
axios_var1: this.vue_var1, //data to send to server
},
responseType: 'json', //server will response with this datatype
})
.then ( function (response){ //success function
console.log('axios ajax success. data returned ==' + response.data); //if returned data format is like {[ {'id':1,'id':2} ]} we may have to do response.data['output_dict'][0]['id']
this.vue_var2 = response.data['output_var'];
}.bind(this)) //bind(this) is required when accessing Vue variable inside Axios success function (.then)
.catch ( function (error){ //error function
console.log('Axios ajax error');
});
},
},
delimiters: ["[[","]]"],
});
Upvotes: 2
Reputation: 6787
There are 4 different ways of doing Ajax with Vue as described in this ARTICLE.
I dont fully understand it. Following is how you would do it using Jquery.
Javascript code :
$("#id1").blur(function() { //when field with id="id1" loses focus, Ajax happens
var email_entered = $(this).val();
$.ajax({
url: 'ajax/signup_email_verification/',
type: "POST", //needs csrf token
data: { email: email_entered,csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), },
dataType: 'json',
success: function (data) {
alert("Ajax successful");
},
error: function(error){
alert("Ajax error");
},
});
});
Django code:
def email_verification(request):
email=request.POST.get('email'); print('AJAX EMAIL = ',email)
data={ 'success':True }
return JsonResponse (data)
HERE are few preferred ways to do Ajax with plain JS or Jquery or Fetch or Axios.
Upvotes: 0