Search code examples
phpangularjsangularjs-http

angular js keep showing me undefined value when i use http post


i'm trying to pass a value to a php file using Post when i do that and i want to read the value from php as json it keeps telling me it's undefined. I don't know where is the mistake

this is my angular.js code

var myApp = angular.module("myApp", []);
myApp.controller("mainController",['$scope','$http','$interval', function($scope, $http, $interval) {
  var url = "user_check.php";

  $scope.lost = "well doe";
  var val = "come on ";
  $interval(function(){
  $http.post(url,{val:val})
    .success(function(data) {
      console.log(data.name);
    })  
    .error(function(data) {

    });

  },0.4)
}]);

and this is my php file

<?php 
if(isset($_POST['val '])){
$data['name']="rose";

    echo json_encode($data);
}
?>

Solution

  • From the Docs:

    $_POST

    An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

    PHP Manual - Reserved variable - $_POST

    The AngularJS framework does POST request with application/json as the HTTP Content-Type.

    Instead use:1

    $data = json_decode(file_get_contents('php://input'), true);
    

    For more information, see