2

I'm testing angularjs' simple ajax request and it seems to be not working. The request is made, and I'm getting 200, but the data is not passing.

$http({
        url: "myphp.php",
        method: "GET",
        dataType: "json",
        data: {"foo":"bar"}
    }).success(function(data, status, headers, config) {
        console.log(data);
    }).error(function(data, status, headers, config) {
        $scope.status = status;
});

<?php

echo var_dump($_GET);

?>

Same result both with get and post. If I'm trying to access $_GET['foo'] for instance, I'm getting an undefined index exception.

What am I doing wrong?

2
  • 1
    What is the return from PHP? What is the body of the response? Commented Mar 2, 2013 at 4:16
  • plnkr.co/edit/SEezJCY7ngBWy6W0IuJW If that's not satisfying, please explain, if you can, how can I get more info using php5.4's built in http server @CaioToOn Commented Mar 2, 2013 at 13:34

2 Answers 2

2

The problem is that your data is sent to your PHP in a JSON encoded body ({dataType: "json", data: {"foo": "bar"}}). Not as GET/POST parameters.

As you're passing the data in body and your PHP is trying to retrieve in $_GET, you are getting undefined index.

Not sure what the right way in PHP, but it's should be something like this:

$requestBody = file_get_contents('php://input');
$requestBody = json_decode($requestBody);
Sign up to request clarification or add additional context in comments.

Comments

0

Because PHP does not accept JSON 'application/json' you need to update your headers and parameters from angular appropriately.

First, Parameterize your data:

data: $.param({ "foo": $scope.fooValue })

Then, add the following to your $http

 headers: {
     'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
 }, 

If all of your requests are going to PHP the parameters can be set globaly in the configuration as follows:

myApp.config(function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Comments

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.