1

I am trying to send and then get data from PHP on my server, but I don't think it sends the data.

My js code:

angular
    .module('h2hApp', [])
    .controller('mainCtrl', ['$scope', '$http', function(scope, http) {

        scope.initGames = function() {
            http({
                method: 'POST',
                url: 'apis.php',
                data: {
                    url: someUrl
                }
            })
                .success(function(data) {
                    console.log(data);
                });
        };

        scope.initGames();
    }]);

and my PHP file:

<?php
    $url = $_POST['url'];
    echo file_get_contents($url);
?>

The only thing I get in response is that error:

Notice: Undefined index: url in /my/path/apis.php on line 2

I made this working using jQuery but with AngularJS it doesn't seem to work. I'm new to Angular and I read some other problems like this. I tried things like adding headers and other things but nothing worked.

4 Answers 4

5

You can be forgiven for thinking that your PHP script should be expecting data in the $_POST variable as encoding your data as a query string has traditionally always been the default mechanism.

Angular however encodes the message body as a JSON object by default. As mentioned you could use the params instead however in the long run I'd argue that it's more flexible to conform on the server-side. For example you can read and decode the message body as follows:

<?php
    $data = json_decode( file_get_contents('php://input') );
    echo $data->url;
Sign up to request clarification or add additional context in comments.

Comments

2

It should be 'params', not 'data'. See http://docs.angularjs.org/api/ng/service/$http#usage

4 Comments

Tried that. Still the same :(
What do you see in your browser's network log when the function "initGames" is being executed?
@iceless params are sent as part of the api url - i.e. the variable would be in $_GET['url'] instead of post.
@Emmissary Yes, using $_GET['url'] works fine with params. Thank you both!
2

Be sure to set the HTTP header, sort of like this:

$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

More info on using Post from AngularJS to PHP

Comments

1

You can use http.post() method -

Try this the code -

http.post('apis.php', {
                    url: someUrl
                })
                .success(function(data) {
                    console.log(data);
                });

1 Comment

The post method is just a helper function. His approach is not inherently wrong.

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.