简体   繁体   中英

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, eg 200 .

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

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);

Using withJson() , your response is converted to a valid json-response, and it also automatically sets the PHP header for you.

From the documentation,

The Content-Type of the Response is automatically set to application/json;charset=utf-8 .

This means that, as long as the variable you pass to withJson() is an array, that method should be all you need - you don't have to worry about setting headers or json-encoding any further, as such

$data = array(...);
return $response->withJson($data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM