Site Navigation
AJAX Series: Tutorial #2 - Sending POST requests
written by vegu on 29 Jan, 2007 03:12:03
Sending GET requests via ajax is easy, parameters are simply attached to the url of the request via ? & delimiters.
If you want to send huge amounts of data though this is not sufficient because there is a limit to how long the url string can be. In this case you will want to use the POST method instead.
If you're new to ajax development make sure you read the
previous tutorial where i talk about creating and using the XMLHttpRequest object.
In this example i will assume that the myText variable holds a significant amount of text. A forum post or a blog post or whatever. We will try to send this text string to a php file located on our webserver and have that webserver write the data we send it into a file.
The ajax_new function you see in the first code example is from the first tutorial and simply creates a XMLHttpRequest object, so it's okay to use your own method to get a valid XMLHttpRequest object or you can just copy mine from the previous tutorial.
var myText = 'Lots of text in this variable';
var ajax = ajax_new();
ajax.open('POST', 'writefile.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send("text="+myText);
Okay, this will not do much, and actually produce a server error since the writefile.php script does not exist yet.
So let's create that.
We want it to take the text we send it via our ajax request and store it in a file. So make sure the directory where the writefile.php will be located is writeable by the web-server.
Here is our little php script:
<?
$my_text = isset($_POST['text']) ? $_POST['text'] : null;
if($my_text) {
$fh = fopen('store.txt', 'w+');
fwrite($fh, $my_text);
fclose($fh);
print "Data was successfully written to file!";
}
?>
Okay try it, our AJAX script should send the contents of our myText variable to the PHP script we just created and that in return should write it to the file you specified ('store.txt' in my case).
We can also use the message the php file prints and have our javascript alert it to us when it is done. We simply utilize the onreadystatechange event as we did in the previous tutorial.
ajax.onreadystatechange = function() {
if(ajax.readyState == 4) {
if(ajax.status == 200) {
alert(ajax.responseText);
} else
alert(ajax.statusText);
}
}
Related Posts
Your Comment
Comments
No comments yet.