0

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

3
  • "The return always falls into the error catch but i can find no reported error through firebug. " — The third argument of the error function is the error message. Try looking at it. Commented Jun 8, 2016 at 9:46
  • error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } - to see the eroor Commented Jun 8, 2016 at 9:48
  • echo the result.. don't return it. Commented Jun 8, 2016 at 10:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes! echo should fix it. Never return to an Ajax, always echo
aaaaaarrrrrrrggggghhhhhh why have i got a return there, I'm such a fool! thanks Muhammad.

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.