i have some problem with ajax call back function. I use ajax and vuejs together, after a make an ajax request in vue method, i would like to access the variable of vuejs but it not working. Here is my code
This is my vuejs function: in this function i tried to upload image to server with ajax
submitFile() {
let url = base_url+"/acp/attach/upload";
let formData = new FormData();
let mod_name = $("#vinpModName").val();
let mod_id = $("#vinpModId").val();
let file_title = $("#file_title").val();
//handle multi files upload
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];
var imgData = '';
if ( i > 0 ) file_title = file_title + ' ' + i;
formData.append('images', file);
formData.append('mod_name', mod_name);
formData.append('mod_id', mod_id);
formData.append('title', file_title);
$.ajax({
url: url,
data: formData,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
type: "POST",
success: function (data) {
var response = jQuery.parseJSON(data); console.log(this.myUploadData);
imgData = response.imgData;
if ( response.code == 1 ) {
SwalAlert.fire({
icon: 'error',
title: response.text,
})
} else {
SwalAlert.fire({
icon: 'success',
title: response.text,
})
}
},
error: function (jqXHR, textStatus, errorThrow) { //console.log(errorThrow);
SwalAlert.fire({
icon: 'error',
title: 'Có lỗi xảy ra khi upload! Vui lòng thử lại sau',
})
}
})
console.log(this.myUploadData);
//this.myUploadData.push(imgData);
}
},
in the function i log the vuejs variable 2 time, 1 worked and 1 does not work
here, the result when i tested in browser
Can anyone tell me what’s wrong with my script?
i want to access to the this.myUploadData and push the return object to this variable
Can any one help me with this!
2
Answers
You need to do that within the success callback also.
When your second console.log is evaluated the async request has not finished at all.
I’ve included a snippet of a Vue app with the same format as yours, it uses a different api and adds the response to an array, which then displays on the page. Hopefully you’ll find it useful in your understanding.
It uses arrow functions in the success callback, so that you can use
this
.Defines
myUploadData
in the Vue instance data, so that it’s reactive.Only pushes to myUploadData once the request has finished, in the
success
callback (Thanks @Renaud).