Here you will learn how to requesting / making an AJAX call with GET and POST method. Below is the minimum code required for a successful AJAX call with both GET and POST method. I’m using PHP for processing data, but you may use ASP, JSP or any other server side scripting language for that.
Files needed
- Making AJAX Call with GET Method
- index.html
- script.js
- ajax.php
- Making AJAX Call with POST Method
- index.html
- script.js
- ajax.php
- Download All files together – 3.08 KB (password is w3epic.com)
Making AJAX Call with GET Method
index.html
<html> <head> <title>Requesting or Making AJAX Call with GET Method - w3epic.com</title> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Requesting or Making AJAX Call with GET Method</h1> <h2>by Arpan Das - <a href="http://w3epic.com">W3Epic.com</a></h2> <button id="load">Load with AJAX - GET method</button> <div id="update"></div> </body> </html>
script.js
window.onload = function () { document.getElementById("load").onclick = function () { var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE var url = 'ajax.php?var=hello world'; xhr.open('GET', url, false); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send(); } }
ajax.php
<?php if (isset($_GET['var'])) { echo $_GET['var']; } else { echo "var is not set"; } ?>
Making AJAX Call with POST Method
index.html
<html> <head> <title>Requesting or Making AJAX Call with POST Method - w3epic.com</title> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Requesting or Making AJAX Call with POST Method</h1> <h2>by Arpan Das - <a href="http://w3epic.com">W3Epic.com</a></h2> <button id="load">Load with AJAX - POST method</button> <div id="update"></div> </body> </html>
script.js
window.onload = function () { document.getElementById("load").onclick = function () { var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE var url = 'ajax.php'; xhr.open('POST', url, false); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send('var=hello world'); } }
ajax.php
<?php if (isset($_POST['var'])) { echo $_POST['var']; } else { echo "var is not set"; } ?>
If you have any problem, please comment below.
If you really like this article, please like, share and comment.
Thank you!