How can I send raw text using xmlhttp request?
I am trying to send text of a field textarea
to a PHP file using ajax, the text contains HTML characters and does not need to be encoded.
Using FormData
it works great but is not supported in version 9 and later! I tried to send data as string
by setting requestHeader
to text/plain;charset=UTF-8;
or multipart/form-data
, but it didn't work! the code i am using:
var string = '<td clas="tdClass">some text<?php echo $contents; ?></td>';
var data = new FormData();
data.append("data" , string);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
What's an alternative way to do this in IE 9?
Yes, it can be done by changing headerRequest
and data
as follows:
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
if(typeof(FormData) == 'undefined'){
var boundary = '---------------------------' + (new Date).getTime(),//boundary is used to specify the encapsulation boundary of a parameter
data = "--" + boundary + "\r\n";
data += 'Content-Disposition: form-data; name="data"\r\n\r\n';//here we specify the name of the parameter name (data) sent to the server which can be retrieved by $_POST['data']
data += string + "\r\n";
data += "--" + boundary + "--\r\n";
xhr.open( 'post', 'writeCode.php', true );
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
}else{
var data = new FormData();
data.append("data", string);
xhr.open( 'post', 'writeCode.php', true );
}
xhr.send(data);
source to share
If usage FormData
works right for you, then in situations where you cannot use it, in fact all you have to do is replace your last line:
xhr.send("data="+encodeURIcomponent(string));
I think the other respondents were confused that you were asking that the text "not be encoded". Form data is usually encoded to be sent over HTTP, but then decoded by PHP when it arrives at the server, completely transparently: you get exactly the original text, no matter what special characters it may contain. (Assuming you are interpreting the PHP string as UTF-8).
So, following your example, if your PHP file contains:
$data = $_POST['data'];
Then the content of the PHP $ data variable will be the string ' <td clas="tdClass">some text<?php echo $contents; ?></td>
'. This is the same as if you used the method FormData
.
source to share
Since, well, it looks like it's pretty simple. Here are some more examples.
Just send a random text
// just text
var dest = "http://requestb.in/qwb9y3qw";
var xhr = new XMLHttpRequest();
xhr.open("POST", dest, true);
var myText = "foobar";
xhr.send(myText);
Place JSON Object
// post json
var dest = "http://requestb.in/1908jrv1";
var xhr = new XMLHttpRequest();
xhr.open("POST", dest, true);
var myObject = {};
myObject.prop1 = "foo";
myObject.prop2 = "bar";
xhr.send(JSON.stringify(myObject));
source to share