Eric Valls
Eric Valls

Reputation: 81

I am not able to send a string correctly from javascript to server

I am trying to send a string to my server using the following script:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.send(data);

However, on the server side, when execute.php is executed,

isset($_POST['name']) 

it returns false. This is the only request to the server.

Why isn't $_POST['name'] set and how to fix it?

Upvotes: 2

Views: 87

Answers (2)

chugadie
chugadie

Reputation: 2873

There are various ways to encode your data when POSTing (MIME types). PHP's $_POST only automatically decodes www-form-urlencoded

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
var data = 'name=John';   

xhr.send(data);

If you send JSON encoded data, you must read the entire post body and json decode it yourself.

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);

xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
var data = JSON.stringify({'name':'John'});

xhr.send(data);

in PHP...

$entityBody = file_get_contents('php://input');
$myPost = json_decode($entityBody);
$myPost['name'] == 'John';

Use your browser's network inspector (f12) to see what is going on.

Upvotes: 1

Xedret
Xedret

Reputation: 1901

Try setting a request header before sending the data:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'execute.php', true);
var data = 'name=John';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);

Upvotes: 1

Related Questions