1

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";
}
3
  • 1
    echo json_encode($data) at the end you not returning any data back to the client Commented Nov 29, 2018 at 10:15
  • OMG! Thank you. I feel so stupid right now. Commented Nov 29, 2018 at 10:17
  • 1
    That's programming, these things happen Commented Nov 29, 2018 at 10:18

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.