Donovant
Donovant

Reputation: 3161

AngularJS - how can I send data to the php page with $http.post?

I can't understand why the data object seems doesn't exist at php server side page.

Angular

$http.post("serverside.php", {"data1":"okpass"}).success(function(data, status, header, config){
                console.log(data);// 
                console.log(status);//202 
                console.log(header);//function (c){a||(a=nc(b));return c?a[O(c)]||null:a}
    });

PHP

if( isset($_POST["data1"]) && $_POST["data1"] == "okpass" ){
    echo "It works!";
    exit(0);
}

Upvotes: 0

Views: 698

Answers (2)

James Bell
James Bell

Reputation: 939

In the PHP code, convert the JSON into good old $_POST like this:

//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
  $_POST = json_decode(file_get_contents('php://input'),true);

//now continue to reference $_POST vars as usual

Upvotes: 0

Steve
Steve

Reputation: 20459

Angulars http.post does not send form data, so you cant rely on phps $_POST. It sends json data. You can get the data like so:

$request = json_decode(file_get_contents("php://input"), true);
if( isset($request["data1"]) && $request["data1"] == "okpass" ){
    echo "It works!";
    exit(0);
}

Upvotes: 1

Related Questions