2

I would like to send data using the jQuery Ajax API:

var myData = {"param1" : $('#txtParam1').val(), "param2" : $('#txtParam2').val()};

$.ajax({
    url: 'DataService.php?action=SomeAction',
    type: 'POST',
    data: myData,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function(result) {
    alert(result.Result);}
});

When I tried to retrieve this data with PHP using

    $param1 = $_REQUEST['param1'];

$param1 is showing null and print_r($_REQUEST) is only showing action = SomeAction ..

How do I retrieve the posted data on a PHP page?

2

3 Answers 3

9

since you're sending the ajax as "contentType: 'application/json'", you need to fetch the request body with php://input like so:

$request = file_get_contents("php://input"); // gets the raw data
$params = json_decode($request,true); // true for return as array
print_r($params);
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$params = json_decode( $_POST['param1']);

And then check what you have got:

var_export( $params);

Or you can use a foreach loop:

foreach( $params as $param)
{
    echo $param . '<br />';
}

You are using POST, method, dont use REQUEST because it is also less secure.

2 Comments

@Nav Ali: try removing the dataType: 'json' line from your code and then see.
can get the data when I removed content-type
1

Try using

$param1 = $_POST['param1'];

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.