0

I'm creating a kind of API system like any social network :D Basically, i created a php page that call with $getJSON method:

This is getuser.php

<?  

include 'config.php'; connect(); 

$get = trim(strip_tags($_GET['id']));

$sql = "SELECT username,id,avatar FROM utenti WHERE id = $get ";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
        $row_set[] = $row;
}
echo json_encode($row_set);

?>

(example id=2)

[{"username":"Firefoxer","id":"2","avatar":"account\/firefoxer\/pic.jpg"}]

And .js function

$.getJSON('getuser.php', {
    id: user
}, function (data) {
    callback = data.avatar
});
alert(callback);

Question is... why it returns undefined object every time ? Code seems right, any ideas ?

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
Mario Rossi
  • 59
  • 1
  • 11
  • it will not work like that because ajax is a asynchronous function and you cannot use it to set a value which will be used outside the call because when the alert is executed the ajax call is yet not completed – Arun P Johny Oct 29 '13 at 09:41
  • i would do it only with $.getJSON method, it's possible ? – Mario Rossi Oct 29 '13 at 09:44
  • you cannot use the `callback` outside the success callback like that... you need to put the alert within the callback function – Arun P Johny Oct 29 '13 at 09:47
  • Btw: Your code is vulnerable to SQL-Injection and the `mysql_*` functions are deprecated. You should use prepared statements and `mysqli_*` or PDO – Joshua Oct 29 '13 at 09:48
  • i cannot use callback if it isn't passed on console.log, right ? – Mario Rossi Oct 29 '13 at 09:55

3 Answers3

0

i am not sure but try to set header as JSON object before your echo like below:

header('Content-type: application/json');
echo json_encode($row_set);
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
0

Since you are getting array of objects, you have to mention the index for data. ie data[0].avatar

$.getJSON( 'getuser.php',{ id: user }, function(data) { 
   callback = data[0].avatar 
   alert(callback);
});
Nauphal
  • 6,194
  • 4
  • 27
  • 43
0

You can only access the data after the callback function has been executed:

$.getJSON( 'getuser.php',{ id: user }, function(data) {
    // now it’s available
    console.log(data);
});
// now it’s not

This is called asynchronous programming, do a search here on SO if this is a new concept for you.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212