jbwebdesign Posted August 10, 2011 Report Share Posted August 10, 2011 hello, i'm having trouble returning a PHP array into Jquery. I have tried using json_encode but i'm not sure i'm using it correctly. When i use it, i get the following: {"id":"1","cid":"3","collection":"collection 1"}{"id":"3","cid":"3","collection":"Testing"} can someone please tell me if i'm doing something wrong? Here is my PHP code: <?php //lets connect to the database and get some info require("../../../includes/db/config.inc.php"); require("../../../includes/db/Database.class.php"); require('../../../includes/upload/upload.class.php'); //This will include the Upload Class $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); $db->connect(); //Ajax to get sub sub categories $id = $_POST['cat_id']; //this is the id of that category if(isset($_GET['collection'])){ $id = 3; $sql = "SELECT * FROM " . TABLE_COLLECTIONS . " WHERE cid='$id'"; $query = $db->query($sql); while($info = $db->fetch_array($query)){ //lets grab the entire array of info and send it back to jquery echo json_encode($info); } } ?> Here is my Jquery code: <!-- LETS USE AJAX TO GET THE PROPER INFO --> <script type="text/javascript"> $(document).ready(function(){ $("#pcat").change(function(){ var id = $(this).val(); //when the select changes, lets use ajax to get some info $.post("modules/products/ajax.php?collection=1", { cat_id: id}, function(data) { alert("Data Loaded: " + data[0].collection); }); },'json'); }); </script> Quote Link to comment Share on other sites More sharing options...
falkencreative Posted August 11, 2011 Report Share Posted August 11, 2011 while($info = $db->fetch_array($query)){ //lets grab the entire array of info and send it back to jquery echo json_encode($info); } Perhaps instead of echoing out out immediately, you need to create a temporary array to hold the data, do any formatting/processing that you need, and then echo it out using json_encode? You've checked the docs regarding this function, correct? http://php.net/manual/en/function.json-encode.php Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.