2

I am trying to make a post request from my angular js, as below

    var postData={
            firstName:'VenuGopal',
            lastName:'Kakkula'
    };
    postData=JSON.stringify(postData);
    $http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .success(function (data,status,headers,config) {
            alert('Success' + data); 
        })
        .error(function (data, status,headers,config) {
            // uh oh
            alert('error' + status + data);
        });

I am not sure how to read this POST DATA in my PHP REST webservice.

 <?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
    $result=json_decode($_POST['firstName']);
    deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
    header("HTTP/1.1 $status $statusmsg");
    $response['status']=$status;
    $response['status_message']=$statusmsg;
    $response['data']=$data;
    $json_response=json_encode($response);
    echo $json_response;
}

?>

I tried the below options

json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])

None of them returned the data, Its always returning the error Undefined index: firstName in F:\xampp\htdocs\Blog\posttest.php on line 10

Can anybody help me how I can read the POST request data sent in php file.

2 Answers 2

0

Most likely it is because you are submitting JSON data which is not automagically populated into the $_POST variable per standard form data.

The work around is to manually parse the input into a variable for use.

Example:

<?php
  $args = json_decode(file_get_contents("php://input"));
  echo $args->firstName;
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Getting an error "Use of Undefined constant file on line 9"
Indeed. I had typo'd file_get_contents to file.get_contents should be working now.
0

You can also solve this problem without changing code in server and use $_POST the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.