Matt G
Matt G

Reputation: 51

AJAX error with json_encode array (and verified JSON OK)

Please can someone point me in the right direction with this AJAX and JSON problem. I have a small program that retrieves user information then shoudl return the data back using JSON for use on a webpage. Below is the js and php code.

require_once 'databasefunctions.php';
$userinfo= array();
$username = filter_input(INPUT_GET, 'username', FILTER_SANITIZE_ENCODED);
$users = GetMultipleIntranetRows("SELECT * FROM tthusers WHERE username LIKE '$username'");
if (!empty($users))        
{
    $userinfo['username'] = $users[0]['username'];
    $userinfo['department'] = $users[0]['department'];
    $userinfo['pin'] = $users[0]['pin'];
    return json_encode($userinfo);
    exit();
}
return "";

AND

$(document).ready(function(){

$('#users').on('change', function(){
    var username = this.value;
    var data = {username:username};
    $.ajax({
    //START OF AJAX
    async:false,
    cache:false, 
    type: "GET",
    data: data,
    dataType: 'json',
    url: "getuserinfo.php",
    success: function(results)
    {
        var b = results;
    }, 
    error: function (results){
         var a = results;  
       }
    });
});

});

The return always falls into the error catch but i can find no reported error through firebug. The json data been returned looks like:

{"username":"mark","department":"workshop","pin":2222}

and is verified as ok.

Thanks Matt

Upvotes: 0

Views: 871

Answers (1)

Muhammad Alvin
Muhammad Alvin

Reputation: 1210

In your PHP file, you write:

return json_encode(...);

Is that code inside a function, and the return value of that function is echo-ed to browser?

If the code is not inside a function, try changing return to echo.

Upvotes: 1

Related Questions