Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send php array to jquery ajax and make a each loop from that array

hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file

here is my php example

$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);

then here is my ajax

$.ajax({
    url: "system/music_list.php",
    dataType: 'json',
    cache: false,
    success: function(response){
        // here i want to read the array and make a loop for each element 
    },
});

thanks if you can help me

like image 745
Mireille28 Avatar asked Dec 05 '22 19:12

Mireille28


2 Answers

try basic for loop with count using length This .. this should help surely.

 function ajax_test()
 {
    $.ajax({
        url: "system/music_list.php",
        dataType: 'json',
        cache: false,
        success: function(response)
        {
             for (var i = 0; i < response.length; i++)
             {
                 alert(response[i]);
             }
        }
    });
 }
like image 162
Amit Chauhan Avatar answered Dec 09 '22 14:12

Amit Chauhan


Try a for loop to loop the records

$.ajax({
    url: "system/music_list.php",
    dataType: 'json',
    cache: false,
    success: function(response){
        var record;
        for(record in response)
        {
            console.log(response[record]); 

        });
    },
});
like image 23
madalinivascu Avatar answered Dec 09 '22 14:12

madalinivascu