Why won't imploding Post work?

131 Views Asked by At

I tried

JAVASCRIPT

str_objects = "some multiline text";

xmlhttp=new XMLHttpRequest(); 
xmlhttp.open("POST", "127.0.0.1/index.php", false); 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("str_objects="+encodeURIComponent(str_objects));

PHP

$str_map = $_POST["str_objects"];

file_put_contents("map.txt", $str_map );

and :

JAVASCRIPT

str_objects = "some multiline text";

xmlhttp=new XMLHttpRequest(); 

xmlhttp.open("POST", "127.0.0.1/index.php", false); 

 xmlhttp.send(str_objects);

PHP

$str_map = file_get_contents('php://input');
file_put_contents("map.txt", $str_map );

The output file "map.txt" remains empty in both cases.

3

There are 3 best solutions below

4
AudioBubble On

you're not passing any post variables so $_POST is empty?

Try the following:

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

More info:

http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

0
Tim Seguine On

HTTP POST data has a specific format. You give variable names and their content.

you can replace your last line in your javascript with:

 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("str_objects="+encodeURIComponent(str_obejects));

then you should get the data in your PHP script.

In the first line we are telling it to send a header with the data that tells the server it is urlencoded key value pairs. Otherwise the server won't know how to interpret it.

In the send line we send the data itself, using the function encodeURIComponent to properly encode the content for transmission, giving it the name str_objects.

On the php side your data will be stored in $_POST["str_objects"]

0
Jan Schejbal On

You are posting raw data, not urlencoded or multipart form data, thus $_POST will not be populated.

You can:

  • Change the JavaScript part to send urlencoded or multipart data
  • Use file_get_contents('php://input') to get the raw data

The latter is probably preferable in your situation.