codenoob codenoob - 3 months ago 12
PHP Question

javascript how to foreach loop through an array

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);
}

}

Answer

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. **/
});