jode jode - 5 months ago 44
Javascript Question

Cannot get $_SESSION variable correctly from angularjs

I'm using angularjs, now I want get a php session variable, so I've create a php file called session.php and inside have this content:

$_SESSION['phone'] = '55551864';
return json_encode($_SESSION['phone']);


from angularj, I've this request:

$http({
method: 'GET',
url: 'session.php'
}).then(function successCallback(response)
{
var phone_number = JSON.stringify(response);
alert(phone_number);
}, function errorCallback(response) {
alert("error happean!");
});


the alert display this content:

{"data":"","status":200,"config":{"method":"GET","transormRequest":[null],"transoformResponse":[null],"url":"session.php","headers":{}},"statusText":"OK"}


I just want return 55551864 what happean?

Answer

The $http response object has these properties

  • data{string|Object} – The response body transformed with the transform functions.
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.
  • statusText{string} – HTTP status text of the response.

So what you are looking for is response.data. As pointed out in the comments you should use echo instead of return. It does not make sense to JSON encode a single string, just echo out the string. Then there is no need to decode it on the client.

$_SESSION['phone'] = '55551864';
echo $_SESSION['phone'];
...
var phone_number = response.data;
Comments