skip to Main Content

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!

2

Answers


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

    Login or Signup to reply.
  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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search