1

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?)

4 Answers 4

4

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.

$('#displaysomedata').click(function() {
        //alert("Button clicked.");
        // Use PHP to output the JSON-encoded array into a javascript variable

        var jsonobj = <?php echo json_encode($suitablemembers); ?>;

        // Now you can do whatever you need to with `jsonobj`
 });

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Just once on page load, as you said. I tried to include the code displayed above, but it does not work, I added alert(jsonobj) right beneath, and get nothing. Do I have to decode it again?
View your page source and make sure something was output there by PHP. Note, your Javascript MUST be inline on the same page where the PHP renders - this won't work if it is included in a script src. If the JSON string is actually there in the source, console.dir(jsonobj); in Firebug or Chrome/Safari developer tools, or IE8/9 developer tools console (F12)
Sorry for the newbie question. when you say that the js must be inline on the same page, and not in script src tags... I'm a little lost. How do I render that JS if not in src tags? <script type ="text/javascript"> $(function(){ $('#testbutton').click(function() { alert("test button clicked"); var jsonobj = <?php echo json_encode($suitablemembers); ?> alert (jsonobj); }); }); </script>
@jeremy if your Javascript is directly inside the <script> tags, you're fine (that's inline). If you call a remote js file in the script tag like <script type='text/javascript' src='somefile.js'></script> then the PHP won't work.
1

Take a look at the PHP function json_encode(), the fist example on that page is how to encode an array as JSON. You can use getJSON to load it from the JQuery side, as noted by toopay.

Comments

1

//main.js

var system_array=[];
function get_array(){
    $.getJSON("/json/get_array.php", function(json) {
          system_array=json;
     });
}

//get_array.php

<?php
    $result_array=array(1,2,3,4,5);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result_array);
    exit();
?>

Comments

1

Encode your data result into JSON, and retrieve it with ajax or getJSON in your jquery script.

EDIT :

I guess you need an example how to do that...

// At the last of your php script, uncomment this
// print_r($suitablemembers);
// and give a json instead
header('Content-Type: application/json');
echo json_encode($suitablemembers);

Then from your html or js file(or inline js), you can perform ajax or using get json shorthand

$('#displaysomedata').click(function() {
    //alert("Button clicked.");
    // Use PHP to output the JSON-encoded array into a javascript variable

    $.getJSON('path/to/above/script.php', function(data) {
       var items = [];

       $.each(data, function(key, val) {
       items.push(key + ':' + val);
       });
       alert(items.join(''));

    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.