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?

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); Commented Jun 30, 2016 at 16:40
  • ok now I get this: "\"555518641\"" Commented Jun 30, 2016 at 16:44

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Okay now working, but I have a question: why I get $http content after the page load?
$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”?
oh yes, I'll try to wait the result

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.