Reputation: 361
This has been asked a lot, but I kind of cant do it alone, new to php and mediocre with jquery. So, this is my php file
<?
include("dbinfo.inc.php");
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT ID, NAME FROM sets";
$result=mysql_query($query);
while ( $results[] = mysql_fetch_object ( $result ) );
array_pop ( $results );
$cards = json_encode($results);
echo $cards;
mysql_close();
?>
This is the way the resulting json looks :
[{"ID":"1","NAME":"Abundant Growth"},{"ID":"2","NAME":"Aggravate"},{"ID":"3","NAME":"Alchemist's Apprentice"},{"ID":"4","NAME":"Alchemist's Refuge"},{"ID":"5","NAME":"Amass the Components"},....
For one reason or another, I would like to have my js code in separate js file. I try to access the data with this code:
var Sets = new Array();
jQuery.getJSON("php/mainDB.php", function(data) {
Sets=data
})
and I hope that Sets will be defined as an array of objects ( the same thing I get with Sets = Please, help me fix my code, and please post code example. I wont mind if I get an answer using $.ajax() answer, too. Might be helpful in the future :)
Upvotes: 0
Views: 634
Reputation: 272
I suspect it has to do with asynchronous loading. I would define the Sets variable within the getJSON call:
jQuery.getJSON("php/mainDB.php", function(data) {
var Sets = new Array();
Sets=data;
alert(Sets[0].NAME);
})
(See a similar issue here: Persistence within jquery .getJSON())
Upvotes: 2