Skip to content Skip to sidebar Skip to footer

How To Pass A Php Array To Javascript Array Using Jquery Ajax?

I followed other reslted question but still unable to solve this problem. I want to store the values of an array from php into an array of js. I tried myself butr getting indefined

Solution 1:

Try below code

   <?php
        $var=5; 
        $myArray = array();
        while($var<10){
        $myArray[]=$var;
        $var++; 
        }
       $dataarray=array("myarray"=>$myArray);
        echo json_encode($dataarray);
        ?>

Jquery

  jQuery(document).ready(function(){
    jQuery("#previous").click(function(){
    var res = new Array(); 
        jQuery.getJSON("phparray.php", function(data) {
    var i= 0;
    while(i<data.myarray.length){
                res[i]=data.myarray[i];
             i++;
    }
  jQuery("#result").html(res[0]);
            });
        });

    });

Solution 2:

The problem with your code is you are updating the result before the JSON has been loaded. There is also no reason to copy every item in the array in this case just set res = data (although the above example of sending back an associative array or JS object is good practice).

PHP

<?php
  for($var=5; $var<10; $var++){
    $myArray[]=$var;
  }
  echo json_encode($myArray);

JavaScript

$(document).ready(function() {
  var res;
  $("#result").bind('update', function() {
    $("#result").html(res[0]);
  });
  $("#previous").click(function(){
    $.getJSON("phparray.php", function(data) {
      res = data;
      $("#result").trigger('update');
    });
  });
});

Post a Comment for "How To Pass A Php Array To Javascript Array Using Jquery Ajax?"