Search code examples
phpjqueryajaxslim-3

How to get the Response from PHP to AJAX?


To receive the response object from my PHP server I thought you could just put the name of the variable into the success function and work on it. Unfortunately this doesn't work. Is there anything which is wrong with my code? I'm using a framework called Slim 3 for the PHP server.

This is my AJAX function:

$.ajax({
    type : "POST",
    url : "http://server/authenticate",
    contentType : "application/json",                                                  
    data: '{"username":"' + username + '", "password":"' + password + '"}',     
    success : function(data) {
        console.log(response)             // response is not defined
        console.log(response.status)      // response is not defined
        console.log("Test")               // Works!
        console.debug(data)               // Nothing, blank line 
        console.debug(data.status)        // undefined       
    }
});

My PHP function:

public function authenticate($request, $response)
{             
    ...

    return $response->withStatus(200)->withHeader('Set-Cookie', $token);
    //return $response;

}

In general my success function works but I wanted to put an if inside it to really check that the statuscode is 200. But as I showed above, there comes undefined. And if I check my browser via F12, I can see that the status code gets transmitted correctly, e.g. 200.

success: function(data) {
    if(data.status == 200) {
        // ...
    }
}

Solution

  • One way would be to return a JSON object from a PHP array:

    $content = ["foo" => 'bar', ...] ; //Any data you wish to return
    return $response->withJson($content);