Locked lesson.
About this lesson
What's the difference between GET and POST and when should you use them?
Exercise files
Download this lesson’s related exercise files.
AJAX Requests - GET or POST?.docx60.1 KB AJAX Requests - GET or POST? - Solution.docx
60.1 KB
Quick reference
AJAX Requests - GET or POST?
Choosing whether to use GET or POST for your form request method is important.
When to use
Every time you create a web form with AJAX, you'll need to choose GET or POST.
Instructions
GET and POST are very different.
GET is used to send small amounts of data. It's not particulary secure.
Post is used to send large amounts of data. It's much more secure.
Please note: AJAX requires a web server to run. If you want to try this AJAX code on your own, it won't work locally, but it will work on a real website with an active server.
To send data using GET with our AJAX code:
<div id="ajax">
<h2>What can AJAX do right here?</h2>
<button type="button" onclick="someAjax()">Change My Content</button>
</div>
<script>
function someAjax() {
var xhttp = new XMLHttpRequest();
//we still don't really know what this stuff does..
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ajax").innerHTML = this.responseText;
}
};
xhttp.open("GET", "text.txt?firstName=John&lastName=Elder", true);
xhttp.send();
}
</script>
To send data using POST with our Ajax code:
<div id="ajax">
<h2>What can AJAX do right here?</h2>
<button type="button" onclick="someAjax()">Change My Content</button>
</div>
<script>
function someAjax() {
var xhttp = new XMLHttpRequest();
//we still don't really know what this stuff does..
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ajax").innerHTML = this.responseText;
}
};
xhttp.open("POST", fileName.txt, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("firstName=John&lastName=Elder");
}
</script>
Hints & tips
- Choosing GET or POST can be important
- Use GET for small bits of data
- Use POST for large bits of data
Lesson notes are only available for subscribers.