1

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

enter image description here

here, the result when i tested in browser

enter image description here

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!

5
  • Does this answer your question? Access Vue Instance Using this Commented May 17, 2020 at 8:08
  • this won't work for me :( Commented May 18, 2020 at 8:09
  • Can you explain what's not working? You've changed success: function (data) { to success: data => { and moved this.myUploadData.push(imgData); into the success callback and it's still not working? Commented May 18, 2020 at 8:14
  • yes, that's right, the error log tell me that this.myUploadData is not defined Commented May 18, 2020 at 8:40
  • Have you defined myUploadData in the Vue instance data? Could you update your question to show? Commented May 18, 2020 at 9:26

2 Answers 2

2

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

new Vue({
  el: "#app",
  data: () => {
    return {
      myUploadData: []
    }
  },
  methods: {
    submitFile() {
      $.ajax({
        url: `https://us-central1-dadsofunny.cloudfunctions.net/DadJokes/random/jokes/1`,
        headers: {
          Accept: "application/json"
        },
        success: data => {
          //Request has finished
          this.myUploadData.push(data);
        },
        error: data => {
          alert(data);
        }
      });

      //Request hasn't finished yet
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <button type="button" @click="submitFile">Submit File</button>

  </div>

  <div v-for="uploadData in myUploadData">
    {{uploadData}}
  </div>
</div>

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

Comments

0

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.

1 Comment

i tried to log in the success callback already but it not work too

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.