1

I am running a loop function with an AJAX request inside it, and the success function on the AJAX need to access a counter variable outside of the loop function, but it wont access it.

   var updateCount = 10;
   var runCount = 0;
   $('#main-table .changed').not("[value='0']").closest('tr').each(function(e){
            if($(this).closest('tr').find('.changed').val() == 1){
                var row = $(this).closest('tr');
                var notes = row.find('input[name="notes"]').val();
                var category = row.find('select[name="category"]').val();
                var fileId = row.find('select[name="file"]').val();
                var fileRow = row.find('.file-id').val();
                var quarter_id = row.find('.quarter-id').val();  
                $.ajax({
                    url: '/myurl',
                    type: "POST",
                    data: {_token: CSRF_TOKEN, 'file_row' : fileRow, 'files' : fileId, 'notes': notes, 'category' : category, 'type' : type, 'quarter': quarter_id, 'row_count':updateCount},
                    success: function(data){
                        if(data == 0){


                            console.log("yes");
                            //I need to increment the runcount here, but it wont increment
                            runCount++;


                        }
                    }
                });


               //If i increment the run count here outside the AJAX request, it works
                runCount++;



                if(runCount == updateCount){
                   console.log("Done");
                }
            };
    });

As stated in the notes, i need to access the runCount variable inside the ajax success function, but I cant. It works fine if I access it just outside of the AJAX request.

Just to confirm, the ajax request is working, as it is console logging yes for each time, so I cant see why it wouldn't increment?

Scriptman
  • 424
  • 2
  • 13
  • 1
    It does increment your var, but since it's asynchronous, you can't see it if you access your variable in your normal code flow. – Zenoo Jan 16 '18 at 10:59
  • And where & when exactly are you accessing the variable to check whether it has increased or not …? Smelling another duplicate of the old classic https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call here … – CBroe Jan 16 '18 at 11:00
  • Success function is asynchronous, as a result your loop finishes before the response arrives. – Aleksei Maide Jan 16 '18 at 11:00
  • Add a `console.log(runCount);` after `runCount++;` and you will see that you are indeed updating the variable. – jotaelesalinas Jan 16 '18 at 11:06
  • @jotaelesalinas It doesn't increment, I have tried it. –  Jan 16 '18 at 11:10
  • Also @CBroe, the code is in my application to access the runCount and check it, I just didn't feel it was necessary to add that into the question, I only kept the code that is necessary to keep the question code clean –  Jan 16 '18 at 11:11
  • Well it _is_ necessary, so add it please. – CBroe Jan 16 '18 at 11:16
  • @CBroe, you're correct. I think the duplicate post you have linked is the problem I am having. –  Jan 16 '18 at 11:30

2 Answers2

0

there is likely a better way to do it, but one sure-fire way is to make another function (in javascript) and update it with that, like:

function bumpRunCount(){
  runCount++;
}

then call that function from the ajax result. That of course is dependent on the scope of runCount. I only mention that because you mention a function, and I dont see one, so it is possible that you are only showing a part of the function. If that is the case, you will need to make sure var runCount is part of the global namespace; or at least accessible.

NappingRabbit
  • 1,888
  • 1
  • 13
  • 18
  • Thanks for the suggestion but this didn't work sadly. Still getting the same result. –  Jan 16 '18 at 11:13
  • @Sam is it possible that you are checking the variable for an increase before the asynchronous call is complete? – NappingRabbit Jan 16 '18 at 11:33
  • 1
    I think the comment in the question is where my problem is. I think as its asynchronous, its just continuing on with the loop before running any sort of callback from the ajax request. –  Jan 16 '18 at 11:36
  • that seems likely – NappingRabbit Jan 16 '18 at 11:37
0

To avoid this scope problem try this, try parsing the variable inside the loop function

 var runCount = 0;
   $('#main-table .changed').not("
     [value='0']").closest('tr').each((runCount)=>{
        if($(this).closest('tr').find('.changed').val() == 1){
            var row = $(this).closest('tr');
            var notes = row.find('input[name="notes"]').val();
            var category = row.find('select[name="category"]').val();
            var fileId = row.find('select[name="file"]').val();
            var fileRow = row.find('.file-id').val();
            var quarter_id = row.find('.quarter-id').val();  
            $.ajax({
                url: '/myurl',
                type: "POST",
                data: {_token: CSRF_TOKEN, 'file_row' : fileRow, 'files' : 
                fileId, 'notes': notes, 'category' : category, 'type' : 
                type, 
                'quarter': quarter_id, 'row_count':updateCount},
                success: function(data){
                    if(data == 0){


                        console.log("yes");
                        //I need to increment the runcount here, but it wont increment
                        runCount++;


                    }
                }
            });


           //If i increment the run count here outside the AJAX request, it 
           works
            //runCount++;


        };
});
Leon Tinashe
  • 97
  • 1
  • 9