Send php array to jquery ajax and create each loop from this array

Hi, I actually read a lot of topics about array and jquery, and they all show an example using jquery inside the hmtl script tag, but I'm trying to learn how to read the array sent by php throught ajax inside the 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

+4
source share
7 answers

try the baseline for a loop counting using length . This ... this should help.

 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]);
             }
        }
    });
 }
+4
source

Please use below code:

$(response).each(function(key,value){
    console.log(value);
});

get ('jazz', rock,... ..).

+2

for loop

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

        });
    },
});
+2

$. each: , . length (, ) 0 -1. .

$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
 //Check if the response is in expected JSON format.
  var flag = isJSON(response);
    if(flag === true)   
    { response = JSON.parse(response);  }              
    //Iterate the Array using for each loop of jquery
    $.each(response, function( index, value ) {
      console.log( "Index : " + index + "Value : " + value );
    });
  } // End of success function
}); //End of Ajax

//JSON format check
function isJSON(data) {
   var ret = true;
   try {
      JSON.parse(data);
   }catch(e) {
      ret = false;
   }
   return ret;
}
+2

.each jQuery :

$.ajax({
    url: "system/music_list.php",
    dataType: 'json',
    cache: false,
    success: function(response){
        $.each(response, function(index,value)
        {
            console.log(index); // print all indexes
            console.log(value); // print all values
        });
    },
});
+1
<div id="dat" name="dat"></div>
<script type="text/javascript">
    $.ajax({ url: "music_list.php",
             dataType: 'json',
             cache: false,
             success:function(response) { 
                 for( res in response) {
                     document.getElementById('dat').innerHTML+=response[res]+"<br/>"; 
                 }
             }
         });
</script>
+1

Source: https://habr.com/ru/post/1628776/


All Articles