I'm trying to emulate a multipart/form-data POST form using AJAX and it doesn't work and I don't know why. I have reviewed the traffic a normal request sends (pressing the "submit" button) and my request and can't tell any difference. However, the receiving page insist in not detecting the ajax POST. What's going wrong??
Here is my form:
<code>
<html>
<script>
// http://www.w3schools.com/ajax
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
function submitThis( action_page )
{
var boundary1;
boundary1 = '-----------------------------' + makeid();
xmlhttp.open("POST", action_page, false );
xmlhttp.setRequestHeader( 'Content-Type', 'multipart/form-data; boundary=' + boundary1 );
myPostData = "";
myPostData = myPostData + boundary1 + '\r\n';
myPostData = myPostData + 'Content-Disposition: form-data; name="textarea_post"' + '\r\n\r\n';
myPostData = myPostData + 'message1' + '\r\n';
myPostData = myPostData + boundary1 + '--\r\n';
xmlhttp.send( myPostData );
} // submitThis
// http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript
function makeid()
{
var text = "";
var possible = "0123456789abcdef";
for( var i=0; i < 16; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
</script>
<body>
<h1>Pruebas de iframe</h1>
<form action="test_ajax_post.php" method="post" enctype="multipart/form-data">
<textarea cols="80" name="textarea_post">message1</textarea><br>
<iframe name="iframe_post" width="80%" src="quixote.html">
</iframe><br>
<input type="submit"><br>
<input type="button" value="Send with ajax" onclick="submitThis('test_ajax_post.php')"/>
</form>
</body>
</html>
And here is the page who receives the data "test_ajax_post.html" (pretty simple, tough):
<html>
<body>
<?php
echo "Textarea value: " . $_POST["textarea_post"] . "<br>";
?>
</body>
</html>
The problem is that the response when I click the "submit" button is this:
<html>
<body>
Textarea value: message1<br></body>
</html>
and when I click the 'Send with ajax' button is this (after sniffing it with fiddler):
<html>
<body>
Textarea value: <br></body>
</html>
The value of the textarea is missing. I've checked the result, almost bit by bit, and I can't tell any difference. What am I doing wrong?
Note: using jQuery or a framework is not an option, because I want modify this to post the content of an iFRAME also. This was the first step in something else.
More info: the server is a Windows 2003 running php version 5.3.10. Okay, it is not the best scenario, but I think that the problem is not there. As a client I've used Chrome and Internet Explorer 8.