-1

I've got a PHP array...

<?php
$tweets = array(
    '1' => array(
        "title" => "title",
        "challenge" => "challenge",
        "answer" => "answer",
        "type" => "type",
        "class" => "class",
     ),
/* .... */
)
?>

That I need to go fetch data from using AJAX and for the life of me, I can't get the data that I need.

What I've got right now is...

var challenge = 10;
var tweets = <?php echo json_encode($tweets); ?>;

$('.cur_race_title').html(tweets[challenge]['title']);
$('.cur_race_challenge').html(tweets[challenge]['challenge']).addClass(tweets[challenge]['class']);
$('.cur_race_answer').html(tweets[challenge]['answer']);
$('.tweet-submission').addClass(tweets[challenge]['type']);

(Note: the challenge number is a variable that changes)

Using PHP's json_encode, I get an array of all of the values in the PHP file (which is included earlier on the file) and then use the challenge ID to populate the data.

The downside is that this shows the data for the entire array - I'd like to only show the data for the single challenge defined by the ID above.

Any help would be greatly appreciated.

Thanks!

pistou
  • 2,799
  • 5
  • 33
  • 60
robbclarke
  • 749
  • 3
  • 9

1 Answers1

1

I wouldn't recommend generating JavaScript variables with PHP tags.

Use: http://api.jquery.com/jquery.getjson/

$.getJSON("myurl.php", function(JSON){
   //do something
});

PHP Side: Returning JSON from PHP to JavaScript?

    header('Content-type: application/json');
    echo json_encode( $myArray[ $myId ] );
Community
  • 1
  • 1
Stevanicus
  • 7,561
  • 9
  • 49
  • 70