Hashey100
Hashey100

Reputation: 984

getJSON need help passing values

I am trying to use getJSON to load the ids that are stored into a database, i am passing the values from PHP to JavaScript by echoing it out. I am trying to alert the value that i passed through but it didn't work

The PHP and JavaScript are on the same page. Any guidance would be appreciated

I printed the JSON file and it is in this format

 Array
(
    [0] => 213
    [1] => 214
    [2] => 215

)

PHP

$result = mysql_query("SELECT * FROM address");

$arra = array();

while ($row = mysql_fetch_array($result)){

    $arra[] = $row['id']; 

}

Javascript

<script>

var test= <?php echo json_encode($arra); ?> 

var url = test;
$.getJSON(url, function(data) {
      alert(url);
})

</script>

Upvotes: 1

Views: 240

Answers (2)

D.Hussain
D.Hussain

Reputation: 132

Make new php file called "Data.php" and make it return your JSON data.

<?php

     $con =  mysql_connect('localhost', 'root', '');
    mysql_select_db('test');

   $result = mysql_query("SELECT * FROM address ORDER BY id DESC");

$arra = array();


while ($row = mysql_fetch_array($result)){

    $arra[] = $row['id']; 


}

echo json_encode($arra);

?>

Then where you call your $.getJSON, Do:

$.getJSON(data.php, function(data) {
      alert(data);
})

Upvotes: 1

codefreak
codefreak

Reputation: 7131

url is json object in your case. It should be url of a page! something like this should work:

$.getJSON("<?=$_SERVER["PHP_SELF"]?>", test, function(data) {
      alert(data);
})

Upvotes: 0

Related Questions