XMLHttpRequest sending XML to PHP server - php

I was wondering if I could send some data from my client-side (2d application using HTML5's canvas) to the server-side in the XML format?
I tried something like this:
function send_xml_data_to_server(xml, url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(xml);
xmlhttp.onreadystatechange = function() {
callback_response_from_server(xmlhttp);
}
}
Because in the informations that I must send to the server-side, it contains a few texts and it doesn't seem to work quite right with the the MIME:
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
But when I'm on the server-side I checked $_POST but there is nothing inside it, the same for $_REQUEST.
So, at the end, I was wondering if it is even possible to send XML data to the server-side PHP using XMLHttpRequest?
Thanks!

There's nothing wrong on the client side, but $_POST contains a parsed set of key/value pairs, but that's not what you're sending to the server. Use something like this:
file_get_contents('php://input');
Then you can parse the string using SimpleXML or whatever you like.

$_POST will be empty if you do not send data as application/x-www-form-urlencoded.
did you try this?
$xml = file_get_contents("php://input");
This way you will capture data in raw format and interpret it according to used mime type.

Related

PHP $_POST is empty, but HTTP_RAW_POST_DATA has all data

I'm just trying to send a POST request with JS to server. But server has empty $_POST array. I could use HTTP_RAW_POST_DATA, but it'll be deprecated in PHP 5.6. Could I have posted data in my $_POST array?
Environment: Chrome, apache2, PHP, AngularJS (I'm using $http.post function).
Debug image (sorry for not attaching image directly - I have no 10 reputation)
The POST data must be in query string or multipart/form-data format to get decoded properly. Your data seems to be JSON, so you have to decode it by yourself:
$_POST = json_decode(file_get_contents('php://input'), true);
$_POST is populated by a request that is of type form-urlencoded or multipart/form-data. Typically it looks like:
foo=bar&ipsum=lorm
So kinda like a GET request.
Since you're posting JSON directly (which is awesome!) you can use:
$request_payload = file_get_contents("php://input");
See the docs for more info.
See by default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
so you can do this when you define your angular module:
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
answer taken from this post by Felipe Miosso.
looks like json data posting directly without any variable try with
$request = file_get_contents('php://input');
print_r($request);
or use a variable on posting data like
data{'myvar': data}
and will get on POST data like
print_r($_POST['myvar']);

Why won't imploding Post work?

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.
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
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"]
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.

how to get string from xmlhttp.send(str) via POST in PHP

My code looks like that:
Client side JavaScript:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST",url + page,true);
xmlhttp.send(str);
I'm missing the code to in PHP side to extract this string, which I assume is in the http post body.
Is it possible to send string array or is this method is restricted for xmls and strings?
You can send any data you like.
Usually, you would encode the data as application/x-www-form-urlencoded:
var data = "foo=" + encodeURIComponent(data) + "&bar=" + encodeURIComponent(more_data);
xmlhttp.send(data);
And then access it via $_POST['foo'] and $_POST['bar'].
If you want to access the raw data, then you can access it via file_get_contents('php://input');
Use setRequestHeader to specify the content type of the data you are sending.
As Canttouchit said, these headers must be send for any POST request:
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // for POST escaped 'form' data
xhttp.setRequestHeader("Content-length", post_str.length);
xhttp.setRequestHeader("Connection", "close");

Server not seeing the JSON sent in javascript ajax request

I'm trying to make an ajax request in straight javascript (jQuery is not available to me) with some JSON parameters.
The javascript:
var params = {'ajax': true, 'albumid': albumid, 'sequencenum': sequencenum};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("GET","viewpicture.php",true);
xhr.setRequestHeader("Content-Type", "application/json")
console.log("sending request");
xhr.send(JSON.stringify(params));
In viewpicture.php, a var_dump($_GET) yields an empty array. What am I doing wrong?
In short, when you make a GET request, .send is expected to have 0 params (or be null).
The only way to send the data through GET would be to append it to the URL itself.
To wit:
If you were sending in form-data, in a POST, the anticipation would be that send would contain the form-encoded data (json for json-data, etc), and the URL would just be the access point on the server.
A GET request is just fetching data from that access point (including query string).
See where I'm going with this?
So if you want this to work in a GET, you need to set your JSON as a property of a query parameter (or turn it into query params/values).
If you want to send in the request body you should use a POST request, however if you need to use a get request you should send the data as key value pairs in the url. e.g. xhr.open("GET","viewpicture.php?data=" + encodeURIComponent(JSON.stringify(params)),true); Then retrieve via $_GET['data'].

XHR request to PHP

Hi i am having problems with an XHR post request.
in javascript:
self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xhr.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
In firebug:
Parametersapplication/x-www-form-urlencoded
{"u":"andrepadez","m":"\n...
JSON
m
"sfdsfsdfdsfdsf"
u
"andrepadez"
Source
{"u":"andrepadez","m":"\nsfdsfsdfdsfdsf"}
In .NET, I post this to an .ASHX, and in the ProcessRequest i do:
StreamReader sr = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);
javaScriptSerializer.Deserialize<MyClass>(message);
and I have no problems.
I don't know how to get the data in PHP, either $_POST and $_REQUEST are empty arrays.
Any help please?
thanks
You've not set a field name for the data being sent. PHP requires data coming in via POST to be in a fieldname=value format. _POST is an array like any other, and every value stored in a PHP array must have a key (which is the form field name).
You can try retrieving the data by reading from php://input:
$post_data = file_get_contents('php://input');
But the simplest solution is to provide a fieldname in your XHR call.
You are setting the Content-Type to application/x-www-form-urlencoded, but you are setting the content to json. I'm guessing this is confusing your PHP webserver. Try setting your POST contents to what you tell the server it will be (application/x-www-form-urlencoded) or read the raw HTTP contents in php://input.
If you set the Content-Type to application/x-www-form-urlencoded then naturally PHP will want to parse the POST body. But as the data does not actually constitute form data, it is discarded as invalid.
You need to set the correct CT application/json (actually doesn't matter) so PHP will leave it alone. Then it becomes available as php://input or $HTTP_RAW_POST_DATA

Categories