2

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?

jode
  • 23
  • 2
  • 2
    In your php you need to do `echo` not `return` -> `echo json_encode($_SESSION['phone']);`. I am not familiar with angularjs, but my guess is after fixing the php issue with `echo`, then your number will be in the `data`, so you could do `response.data` -> `var phone_number = JSON.stringify(response.data);` – Sean Jun 30 '16 at 16:40
  • ok now I get this: "\"555518641\"" – jode Jun 30 '16 at 16:44

1 Answers1

1

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;
  • Okay now working, but I have a question: why I get $http content after the page load? – jode Jun 30 '16 at 16:48
  • `$http` is an asynchronous request to the server, meaning the code after it will continue to execute while the web request is being sent and received. See [Easy to understand definition of “asynchronous event”?](http://stackoverflow.com/questions/4559032/easy-to-understand-definition-of-asynchronous-event) –  Jun 30 '16 at 16:50
  • oh yes, I'll try to wait the result – jode Jun 30 '16 at 16:50