0

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

5
  • Any errors in the console section .,, Try parsing to to json .. Sets= $.parseJSON(data) Commented Oct 17, 2012 at 20:10
  • No, the console just returns an empty []. Commented Oct 17, 2012 at 20:13
  • How does cards look like before being sent back from the server Commented Oct 17, 2012 at 20:15
  • Your code is fine. I just tried with this fiddle and it is working fine provided that your php is emitting correct json. jsfiddle.net/tariqulazam/KZLnk What is the issue actually? Commented Oct 17, 2012 at 20:18
  • This is a mysql database. the database is static. the output of the php could be seen at magicdb.comli.com. I think my getJSON part is wrong?? Commented Oct 17, 2012 at 20:23

1 Answer 1

2

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

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.