Sam
Sam

Reputation: 1381

not able to get the count the response getting through ajax

I have a form that is used to upload multiple files on click of submit button.

For example i am uploading the following files

student.png

animal.png

pet.png

I am using the following ajax to send the values at the backend (code reference taken from).

$.ajax({
    type:"POST",
    url:this.vpb_settings.vpb_server_url,
    data:dataString,
    cache: false,
    contentType: false,
    processData: false,
    success:function(response)
    {
        console.log(response);
    }
});

When i try to print the response through "console.log()", i get the list of the names of the files that were uploaded, which is one of my requirement. So after using "console.log(response)" i get the output as

student

animal

pet

Now i wish to to calculate the number of names that i get, for this i used this code, "console.log(response.length)" but i got the output as

7
6
3

Whereas i want the response as 3 because there are 3 items in the list

can anyone please tell how this can be done

Upvotes: 0

Views: 42

Answers (2)

Scaramouche
Scaramouche

Reputation: 3257

Looks like you are using one ajax call per file, so of course, each response is the name of one file (a string), not an array, hence

  1. 'student'.length => 7
  2. 'animal'.length => 6
  3. 'pet'.length => 3

If you need the amount of files you could use a global counter, like this:

var counter = 0; //<--needs to be declared somewhere it gets initialized once only
function someFuncContainingTheAjaxCall(){
$.ajax({
    type:"POST",
    url:this.vpb_settings.vpb_server_url,
    data:dataString,
    cache: false,
    contentType: false,
    processData: false,
    success:function(response)
    {
        console.log('Files so far ' + (++counter));
    }
});
}

HIH

Upvotes: 1

Kasabucki Alexandr
Kasabucki Alexandr

Reputation: 630

You can create any variable in outer scope and increase it on success callback. Also you will need to reset it to 0 before do call.

Upvotes: 0

Related Questions