Mujtaba Haider
Mujtaba Haider

Reputation: 1650

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 value in all the cases i tried Plese anyone let me know where i am wrong my Php code

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

and the js code

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

also treid this js

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

Upvotes: 0

Views: 6051

Answers (2)

funrob
funrob

Reputation: 619

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

Upvotes: 1

Bhanu Krishnan
Bhanu Krishnan

Reputation: 3726

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

    });

Upvotes: 2

Related Questions