1

I have a webpage where I have a table like following :

===========================================
Vehicle Num |  GPS speed | GPS Location
===========================================
            |            | 
            |            |

So after document.ready(), I am firing AJAX call for each vehicle row to get the GPS info for corresponding vehicle. Here is my code :

var length = 47; // I have 47 vehicles
    var vehicleNum = "";
    var ajaxURL = "";
    $('document').ready(function(){
        for(var i = 1; i < length; i++)
        {
            vehicleNum = $("#"+i+"-vehicleNum").val();
            //strip spaces from vehicle number
            vehicleNum = vehicleNum.replace(/\s/g, '');
            ajaxURL = "http://www.vehicletrack.biz/api/vehlastlocation?token=K2ZPJFJP3A&vehname="+vehicleNum;

            //start ajax request
            $.ajax({
                url: ajaxURL,
                dataType: "json",
                success: function(data) {

                    if(data.result[0].error)
                    {
                        //error
                    }
                    else
                    {
                        // alert(i);
                        alert(i);
                        $("#"+i+"-speed").html(data.result[0].speed);
                    }
                }
            });

        }
    });

I am getting speed value updated only for the 47th vehicle. What should be the correct approach (and optimized one)? Any suggestions please.

EDIT This is one of the JSON response

{"result":[{"longitude":76.391529,"latitude":27.974347,"location":"Delhi-Ajmer Expressway - Madhosinghpura- Alwar - Rajasthan - India","speed":0,"dttime":"14 Feb 2016 00:38:47","ignition":0,"vehicle_name":"HR38T7623","icon":0}]}
Naveen
  • 7,944
  • 12
  • 78
  • 165
  • Use javascript closure i.e anonymous function – Mohammed Raja Feb 13 '16 at 20:16
  • Yeah, it looks duplicate. But seriously, I couldn't understand the answers in the linked question. Can anyone explain in 2 - 3 lines w.r.t my code. – Naveen Feb 13 '16 at 20:29
  • 1
    Your loop exits before your first request got success. Your loop ends with i=47. Though you have 47 times call to server but when your first request get success and try to executes success block, it found i=47 and same for rest of the call. – Mohammed Raja Feb 13 '16 at 20:36
  • So that means its possible that none of the response is served as the loop might have already finished... right? Or if I am lucky and the loop is still running when responses start coming, I may get few responses served? – Naveen Feb 13 '16 at 20:41
  • Yeah. If your server is in your local system and its lightning fast! but loops always finished in no time. – Mohammed Raja Feb 13 '16 at 21:24

0 Answers0