0

I have an array that look like this

var ids = ["id1","id2","id3","id4"]

I want to foreach loop through the array and extract each of the ids and pass that into ajax. so it will auto fill in some input field

I am familiar with PHP where I would use

foreach($array as $temporaryvariable){
  // do stuff with $temporaryvariable
}

so I am looking for a Javascript or JQuery equivalent, so my final code will look something like the below

var ids = ["id1","id2","id3","id4"]

foreach(ids as id){
$.ajax({
  url: "../folder/lookupserver.php",
  type: "POST", 
  data: {
    'id' : id//each of the ids
  },
  dataType: "JSON",
  success:function(data){
    $result= data;
    $('#input field').val($result);
  }
}
Ivan
  • 34,531
  • 8
  • 55
  • 100
codenoob
  • 539
  • 1
  • 9
  • 26
  • 1
    You could use `forEach()` to loop through the array, however I see two issues. Firstly bombarding your server with several requests quickly is not a great idea - it's basically DDOSing yourself. Make one request with all data and return a single response. Also, if you're only updating one field, only the final result will be shown, which makes all previous requests redundant. – Rory McCrossan Aug 16 '16 at 20:28
  • 1
    Why would you want to execute ajax queries in a loop? You should pass all the `ids` in one query to your `lookupserver.php`, and have it return one result set. – BeetleJuice Aug 16 '16 at 20:29

7 Answers7

1

Use the forEach() method:

var ids = ["id1","id2","id3","id4"]
ids.forEach(function(id) {

  console.log(id);
  // here you can have an AJAX

});

This methods takes one parameter: a function, that will be executed for each element of the array. You need to specify the name you want to call each element you select. Like you would in PHP: foreach($ids as $id)

Ivan
  • 34,531
  • 8
  • 55
  • 100
1

A better, less server intensive way would be to pass...

The whole array to server,

var ids = ["id1", "id2", "id3", "id4"];

$.ajax({
    url: "../folder/lookupserver.php",
    type: "POST",
    data: {

        'id': ids
    },
    dataType: "JSON",
    success: function (data) {
        $result = data;
        $('#input field').val($result);
    }
});

then read the array in PHP and use a foreach to get the individual ID's like that.

This way you aren't sending so many requests in rapid successions to the server.

However...

If you really want to send that many requests, you'd use a forEach loop.

var ids = ["id1", "id2", "id3", "id4"];

ids.forEach(function (id) {
    /** Your AJAX request here. **/
});
Script47
  • 14,230
  • 4
  • 45
  • 66
  • it's better than his 4 AJAX requests but the initial question is "how to foreach loop through an array" ... – Ivan Aug 16 '16 at 20:44
  • @Ivan I provided a better solution which is perfectly acceptable too. – Script47 Aug 16 '16 at 20:44
  • 1
    @Ivan the initial question is often a corollary to the actual issue. You should always guide the OP towards the best solution for their use case - even if it's not what they specifically asked. – Rory McCrossan Aug 16 '16 at 20:58
0

you can use a for loop for that

var ids = ["id1","id2","id3","id4"]
var id;
    for(var i=0; i< ids.length;i++){
       id = ids[i];
       $.ajax({
            url: "../folder/lookupserver.php",
            type: "POST", 
            data: {

                   'id' : id//each of the ids
             },
                    dataType: "JSON",
                    success:function(data){
                           $result= data;
                           $('#input field').val($result);
                                }

         }
     }
Edison Biba
  • 4,384
  • 3
  • 17
  • 33
0

Javascript arrays also have a foreach function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Try something like

var ids = ["id1","id2","id3","id4"].foreach( function(element, index) {
    // custom ajax code here
});
Max Hartshorn
  • 709
  • 7
  • 19
0

In Javascript this would be a for loop like so

Example :

  var ids = ["id1","id2","id3","id4"]

  var i;

  for(i in ids){

        //do whatever here

}
KpTheConstructor
  • 3,153
  • 1
  • 14
  • 22
0

It's been brought to my attention that I should mention I'm using es6 syntax in this solution. Including object enhancement, arrow functions and the const keyword. Be sure to read up on these subjects before using this code in your own projects.

const ids = ["id1","id2","id3","id4"];

const options = id => ({ 
  url: '../folder/lookupserver.php',
  type: 'POST',
  data: { id },
  dataType: 'JSON'
});

const update = data => $('#update field').val(data);

const request = id => $.ajax(options(id)).done(update);

ids.forEach(request);
Corey Clark
  • 116
  • 1
  • 4
  • 1
    Why are you defining everything as `const`? – Script47 Aug 16 '16 at 20:49
  • It signifies a read only reference, informing other developers that you have no intentions on rebinding that variable else where. – Corey Clark Aug 16 '16 at 21:00
  • I know what it signifies but who says any of them have to be read-only? I highly doubt the `ids` would be read-only. – Script47 Aug 16 '16 at 21:08
  • No one did, but `const` should be used by default. That way no one has to guess what might happen later. – Corey Clark Aug 16 '16 at 21:09
  • In this case the OP seems rather inexperienced with JavaScript, so what if they used this code and it causes them issues? You could reference `const` in your answer and give a little bit of background about it? – Script47 Aug 16 '16 at 21:10
  • 1
    Ya you're right, thats a good point. – Corey Clark Aug 16 '16 at 21:22
-1
var ids = ["id1","id2","id3","id4"];
    i=0;
    $(ids).each(function(){
      console.log(ids[i]);
      i++;
    });