0

I am making a test application to test angular and php data transfer. But angular is sending data through post method but php is not accepting the data

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
    <script 

src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
    </script>
</head>
<body ng-app="myApp">
<div ng-controller="myctrl">
 <form ng-submit="insert()">
   <input type="text" ng-model="name" name="name" placeholder="name">
   <input type="age" ng-model="age" name="age" placeholder="age">
   <button type="submit">Submit</button>
 </form>
</div>
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.controller('myctrl',function($scope,$http){    


    $scope.insert=function(){    

        $http.post("test.php", {
            'name':$scope.name,
            'age':$scope.age
        }).then(function(response){
                console.log(response);
            },function(error){
                alert("Sorry! Data Couldn't be inserted!");
                console.error(error);

            });
        }
    });
 </script>
</body>
</html>

This is the html code The php code is

<?php


    $data = json_decode(file_get_contents('php://input'));
    $place=$data->name;
    $image=$data->age;
    echo $place;
    echo $image;
    echo "string";
?>

When i access these name and age its giving the error as

"
Notice: Trying to get property of non-object in C:\xampp\htdocs\test\test.php on line 5

Notice: Trying to get property of non-object in C:\xampp\htdocs\test\test.php on line 6
string"

but angular is sending the data data:Object age:"2" name:"abcd" cant identify where is the problem.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Akash Ghosh
  • 23
  • 1
  • 9
  • I am not 100% sure but shouldn't it be $name = $_POST['name']; $age = $_POST['age']; .... – Khan Shahrukh Jul 03 '17 at 19:10
  • "
    Notice: Undefined index: name in C:\xampp\htdocs\test\test.php on line 5

    Notice: Undefined index: age in C:\xampp\htdocs\test\test.php on line 6
    string"
    – Akash Ghosh Jul 03 '17 at 19:24
  • getting this error now. Tried this method also. – Akash Ghosh Jul 03 '17 at 19:25
  • Possible duplicate of [How do I enable cross-origin resource sharing on XAMPP?](https://stackoverflow.com/questions/34872760/how-do-i-enable-cross-origin-resource-sharing-on-xampp) – georgeawg Jul 04 '17 at 01:42

1 Answers1

0

One way to make proper post request to php is through $httpParamSerializerJQLike,

so you can make a post like this:

var data = {
        'name':$scope.name,
        'age':$scope.age
    };
var req = {
      method : "POST",
      url: "http://yourUrl",
      data: $httpParamSerializerJQLike(data),
      headers: {
        'Content-Type': "application/x-www-form-urlencoded"
      }
    };
 $http(req).then(function(resp){//success}).catch(function(error){//error});
georgeawg
  • 48,608
  • 13
  • 72
  • 95