user10098815
user10098815

Reputation:

AngularJs - PHP POST issue

I am trying to make a post request with angularjs to php. The post response is always 200 OK and the returned 'data' variable in the response is empty always. I am kind of new at this as you can see, what am I doing wrong here?

AngularJs code:

$scope.postData = function(){
    $http.post('send.php', $scope.data).then(function(response){
      console.log(response);
    });
  }

PHP:

$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->fullName)){
  $error["fullName"] = "Your name is required";
}

if(empty($form_data->email)){
  $error["email"] = "Your email is required";
}

if(empty($form_data->message)){
  $error["message"] = "Message is required";
}

if(!empty($error)){
  $data["error"] = $error;
} else {
  $data["message"] = "Ok";
}

Upvotes: 1

Views: 42

Answers (1)

Masivuye Cokile
Masivuye Cokile

Reputation: 4772

You need to echo data back to the client, in your code you not returning anything back hence the response is empty.

<?php
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->fullName)){
  $error["fullName"] = "Your name is required";
}

if(empty($form_data->email)){
  $error["email"] = "Your email is required";
}

if(empty($form_data->message)){
  $error["message"] = "Message is required";
}

if(!empty($error)){
  $data["error"] = $error;
} else {
  $data["message"] = "Ok";
}

echo json_encode($data); // return data back to the client

Upvotes: 1

Related Questions