I have a page which does a SQL query via PHP and generates a small array. I want to have jquery on the same page be able to make use of the array, or more specifically, of the variables in the array.
Code follows:
$result = mysql_query("SELECT characters_ID, name FROM characters where whichfamily = '$famID' && deathdate = '' && isfemale = '0' && $currentturn > borndate + 128",$db);
$rowcheck = mysql_num_rows($result);
//echo $rowcheck;
$suitablemembers = array();
$i = '0';
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $col => $val){
if ($col == 'characters_ID') {
$suitablemembers['idnum'][$i] = $val;
}
if ($col == 'name') {
$suitablemembers['name'][$i] = $val;
}
//$_SESSION['currentplayerCP'] = $val;
//$_SESSION['currentplayerMaxCP'] = $val;
}
$i++;
}
print_r($suitablemembers);
The print_r gives output like this:
Array ( [idnum] => Array ( [0] => 3 [1] => 10 ) [name] => Array ( [0] => Orland [1] => Raguet ) )
more code follows:
$('#displaysomedata').click(function() {
//alert("Button clicked.");
// somehow do a while or loop to display data from that array
}); // end displaysomedata click function
I’ve played with JSON encapsulation some, but I’m not sure if it is a workable solution for this.
How can I move the data from a php array into jquery variables (in a loop?)
JSON is exactly the solution you need for this. Your PHP script encodes the array as JSON, and you can echo it out on the page.
This assumes that you do not need to dynamically retrieve the data from PHP, but rather are just producing it once on page load. If you need to retrieve it dynamically, you would need to make use of
$.ajax()in jQuery.Note: For this to work properly, the Javascript above must be inline on the same page generated by the PHP. If it is included via
<script src=>, PHP cannot modify it.