0

Im having a little confusion why the following is not working.

get.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[] = $first;

    $i++;
}

echo json_encode($array);

?>

jQuery

var arr = new Array();

    $.get("get.php", function(data){
         arr = data;
         alert(arr);
    }, "json");

When I run the following I get a list of names that looks like this

["James","Lydia","John"]

But when I try to single out an entry such as arr[2], i am give just a 'J', why is it that the elements arnt single entries like I would expect?

Can anyone lend a hand?

Thanks!

Update

$.get("get.php", function(data){

     arr = $.parseJSON(data);
     alert(arr);
}, "json");

does not seem to return results?

2
  • It seems the data was not parsed to JavaScript array yet and arr is still a string. Otherwise, alert(arr) would output James, Lydia, John. Commented Apr 13, 2012 at 15:07
  • As a side note - var arr = new Array(); doesn't do anything, since you'll assign another value to that variable afterwards anyway. Commented Apr 13, 2012 at 15:09

4 Answers 4

4

data contains a string of the JSON, so arr[2] will be the third character in the string. You need to use $.parseJSON(data).

4
  • So the question is why does passing the data type argument not work? Commented Apr 13, 2012 at 15:08
  • would this be how I would use it in this instance? arr = ($.parseJSON(data)); Commented Apr 13, 2012 at 15:17
  • Yep, that's correct. No need for the wrapper, though: arr = $.parseJSON(data); Commented Apr 13, 2012 at 15:17
  • Hmmm, it doesnt seem to be working, would you take a look at the updated code in the question? Commented Apr 13, 2012 at 15:20
3

Your PHP is claiming that the JSON is HTML. You need to explicitly say it is JSON to get jQuery to handle it as such automatically.

header("Content-type: application/json");
1
  • Shouldn't it work nevertheless if the data type argument is provided? Commented Apr 13, 2012 at 15:09
0

Send the json header in php via header('Content-type: application/json'); so jQuery should automatically decode your json data.

0

you can't gave the data value to the array.

 $.get("get.php", function(data){
     alert(data[2]);
}, "json");

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.