Possible Duplicate:
Taking .get json string, turn into array?
Im using the following to retrieve a string from php, i would like to know how to make my string into an array.
Jquery
$.get("get.php", function(data){
alert(data);
//alert($.parseJSON(data));
}, "json");
the commented out section seems to have no effect, so I cant really tell what I am doing wrong, could someone please advice?
PHP
<?php
$username="root";
$password="root";
$database="testing";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$name= $_GET['name'];
$query="SELECT * FROM tableone ";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$array = array();
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"firstname");
$last=mysql_result($result,$i,"lastname");
$date=mysql_result($result,$i,"date");
$ID=mysql_result($result,$i,"id");
$array[$i] = $first;
$i++;
}
echo json_encode($array);
?>
Output:
["James","Lydia","John"]
asked Apr 13, 2012 at 15:59
James Dunay
2,7348 gold badges41 silver badges66 bronze badges
-
3You already asked this question. Please edit that one rather than starting a new one.Rory McCrossan– Rory McCrossan2012年04月13日 16:02:43 +00:00Commented Apr 13, 2012 at 16:02
-
That's the third time you basically ask the same question: stackoverflow.com/questions/10143361/… Update your original question, comment on answers and wait... maybe you also have to revise some jQuery, JavaScripts basics.Felix Kling– Felix Kling2012年04月13日 16:05:25 +00:00Commented Apr 13, 2012 at 16:05
1 Answer 1
$.getJSON("get.php", function(data) {
// data is already an array => you can loop to get individual elements
// for example
$.each(data, function(index, element) {
alert(element);
});
});
Also make sure that in your PHP file you have set the proper Content-Type response header top application/json.
answered Apr 13, 2012 at 16:02
Darin Dimitrov
1.0m277 gold badges3.3k silver badges3k bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
xdazz
Isn't this just same as
$.get('get.php', function(data){}, 'json'); ?Darin Dimitrov
@xdazz, absolutely the same. It's shorter.
James Dunay
but see that just returns me single letters, and you have
(element, index) backwards. I would like to know how to get the different names as full objectsSeanCannon
But they're not objects. They're strings.
James Dunay
ahh well then maybe my PHP is messed up, how might i get them in as string objects, instead of single characters so that i might select them?
default