Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My goal is to get - finally - a 'normal' JS array in my js-file. Maybe json is the way to do it - but the elements in the array should remain in order and its just an array of three arrays: [["1","2","3"]["1","2","3"]["1","2","3"]].

my php-query (it does produce the array above - I mean: it does work):

// this is file 'dbquery.php'

<?php
    include_once('../resources/init.php');

    $query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
    $qlen = mysql_query("SELECT COUNT(1) FROM `results`");
    $len = mysql_result($qlen, 0);

    $user_a = array();
    $solu_a = array();
    $time_a = array();

    while($row = mysql_fetch_assoc($query)){

       array_push($user_a, $row['useranswer']);
       array_push($solu_a, $row['solution']);
       array_push($time_a, $row['time']);
    }

    $cd_result = array($user_a, $solu_a, $time_a);
    $cd_answer = json_encode($cd_result);
    echo $cd_answer;
?>

I assume json is not the adequat form here.

Now all I want is an js-array in my js-file like : my_array = [[1,2,3],[1,2,3],[1,2,3]]

But I terribly fail to achieve this.

With $.ajax() I don't know how to get ALL the data at once without 'data: ' each single value. I just want to "catch" my echo from the php - how to do so?

share|improve this question
 
possible duplicate of What is the best way to send PHP array via jquery? –  Felix Kling Feb 5 at 10:12
 
Do you need it dynamic (i.e in response to a JS event) or is it OK to have it set just when the page is rendered? –  halfer Feb 5 at 10:58
 
I need the array once in a function. I am drawing a graph from a DB after the user performed some tasks (i.e. submitted his own data to the DB - but this part already works). - So I guess it is sufficient if the array is saved in a global at pageload. –  Chrugel Feb 5 at 11:04
add comment

2 Answers

up vote 0 down vote accepted

If you just need a PHP variable passed to JS when the page is rendered, then do this in your PHP view layer:

<script type="text/javascript">
    var myInt = <?php echo $int ?>;
    var myString = '<?php echo $string ?>'; 
    var myArray = <?php echo json_encode($array) ?>;

    // All these JS variables can now be used here
</script>

Obviously, you need to ensure that the variables are valid - so in the case of the int, if it is null or undefined, you need to ensure you don't render the assignment - otherwise it will produce a client-side error.

share|improve this answer
 
Now I can't follow. I tried such solutions before (as they are mentioned all over the internet) - but I tried this in my js-file. Now you say 'php view file', but I don't have a such... My difficulties arise from this: I just had a fully on client-side page, results of one user are shown to them. But then I wanted to collect the data and show the users their result and ALL results. So I made a DB, a .php for upload (via $_POST and hidden formular), and another .php for 'download' which is here not working. I simply don't want to rewrite my whole JS code in php! –  Chrugel Feb 5 at 12:05
 
I've not advised you to rewrite your JS in PHP. I don't follow the problem you're having though, can you write a single sentence that encapsulates the problem you're having? You will have a "php view file" - this just means whatever PHP system outputs HTML to the client. Most people use a template library (to separate business logic from layout) but I appreciate not everyone does. –  halfer Feb 5 at 12:31
 
Sorry for misunderstanding you! I figured out (in my almost empty test-project) it works this way, when I am pasting my dbquery.php just on top on my JS-file, rename and include this formarely js-file as .php-file. Unfortunately in my real project this leads (although the alert with the array works now!) in the very end to the display of the code on the page... –  Chrugel Feb 5 at 12:48
 
This bug with the code-display was just a little naming issue. It should work this way! But is it really ment to include the js-code on a php-file ? And in the very end (everything works- the whole program) after some seconds it turns to a plain white page - how to stop this final "jump" ? –  Chrugel Feb 5 at 12:58
 
But is it really [meant] to include the js-code [in] a php-file? Yes, that's how this approach works: echo out the snippet I provided into your HTML directly, ideally in your <head> section. I can't tell what is causing your white page - check your JS console in your browser to see if you have JS errors. –  halfer Feb 5 at 13:53
show 2 more comments

do like this

<?php
    include_once('../resources/init.php');

    $query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
    $qlen = mysql_query("SELECT COUNT(1) FROM `results`");
    $len = mysql_result($qlen, 0);

    $user_a = array();
    $solu_a = array();
    $time_a = array();

    while($row = mysql_fetch_assoc($query)){

       array_push($user_a, $row['useranswer']);
       array_push($solu_a, $row['solution']);
       array_push($time_a, $row['time']);
    }

    $cd_result = array($user_a, $solu_a, $time_a);
    $cd_answer = json_encode($cd_result);
    echo json_encode ($cd_answer);  // encode in json format
?>

and in ajax:

$.ajax({
  type: "GET",
  url: "test.php",
  dataType: "json",
  data : {anything : 1},
  success:function(data){ 
    var x = jQuery.parseJSON( data ); // parse the answer
    // if you want in an array format then just use eval()
    x = eval(x);
    alert(x);
}
});
share|improve this answer
 
I guess the 'url:' should be my 'dbquery.php' ? And the $.ajax() can be just placed within the $(document).ready() ? –  Chrugel Feb 5 at 10:52
 
yes. is it working for u.. –  sourcecode Feb 5 at 10:59
 
I think there is a comma missing before 'success:' too - but anyway - doesn't work yet. I am also wondering whether I should place the ajax() in the ready() or in the function actually in need of the array. –  Chrugel Feb 5 at 11:11
 
if you are placing the ajax in function, then it will run only on calling that function .But if you are putting it in ready, then it will get executed at DOM ready , it depends on your need what you want! –  sourcecode Feb 5 at 11:14
 
Ok - I created a new testproject: 1. empty html-file (just with src to jquery & js plus an empty body), 2. new js-file: just $(document).ready(function(){}) with your .ajax() in it. 3. url: to the same dbquery.php. Result: no alert. What am I missing? –  Chrugel Feb 5 at 11:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.