1

I'm devoloping a site that retrieve information about user location (name,lat,lng,address..) from a database with an ajax request performed with jQuery. I have fetched all the results into an associative arrays

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase"; 
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
    die('Could not connect' .mysql_error());

}
mysql_select_db($dbname);

$query = " SELECT * FROM userevent ";
$result = mysql_query($query);
$a = array();

while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
    array_push($a,$row);

}
echo json_encode($a);
mysql_close($conn);

After fetching i get this type of array :

Array
(
    [0] => Array
        (
            [ID] => 3823
            [name] => Erik 
            [lat] => 63.2994
            [lng] => 23.7497
            [title] => b
        )

    [1] => Array
        (
            [ID] => 3824
            [name] => George
            [lat] => 43.2994
            [lng] => 13.4494
            [title] => a

        )
  )

in my .js file i have this :

function loadmap(){
    $.ajax ({
        url:'loaddata.php',
        dataType:'json',
        success: function(data){
           alert(""+data[0]); //DOESN'T WORK ???????
        },
    })
}

How can I read my array now ?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
DaMatt91
  • 544
  • 1
  • 7
  • 18
  • If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Sep 22 '15 at 20:46
  • just set header in your php file: `header("Content-Type: application/json");` jquery detects the content type automatically – Joshua K Sep 22 '15 at 20:49
  • 1
    console.log(data) in your success function to see what you're actually getting back. – devlin carnate Sep 22 '15 at 20:53
  • is alert even firing? need to inspect the actual request in browser dev tools network to see what is actually returned , status etc – charlietfl Sep 22 '15 at 21:10

2 Answers2

1

data is likely coming back as a string, you can use JSON.parse to turn it into JSON.

function loadmap(){
    $.ajax ({
        url:'loaddata.php',
        dataType:'json',
        success: function(data){
           data = JSON.parse(data);
           alert(""+data[0]);
        },
    })
}
tcigrand
  • 2,357
  • 2
  • 14
  • 24
1

Heads up : Use print_r() function for printing out the output of json_encode() php predefined function instead of the native echo.

PHP updated code

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase"; 
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
    die('Could not connect' .mysql_error());

}
mysql_select_db($dbname);

$query = " SELECT * FROM userevent ";
$result = mysql_query($query);
$a = array();

while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
    array_push($a,$row);

}
print_r(json_encode($a));
mysql_close($conn);

You don't need to parse the array in the clientside if you are already using json_encode function. You can Access the array values as a normal javascript object using the dot(.) operator.

Javascript Updated code snippet

function loadmap(){
    $.ajax ({
        url:'loaddata.php',
        dataType:'json',
        success: function(data){
           alert(data.ID); //this one will print the value of ID key in the array
        },
    })
}
Jijo John
  • 1,375
  • 9
  • 21