What is AJAX ?
- Asynchronous Javascript & XML
- Set of web technologies
- Send & receive data asynchronously
- Does not interfere with current web page
- JSON has replaced XML for the most part
Why XmlHttpRequest (XHR) Object is Used ?
- API in the form of an object
- Provided by the browser’s JS environment
- Methods transfer data between client/server
- Can be used with other protocols than HTTP
- Can work with data other than XML (JSON, plain text)
How to retrieve data from sample.txt files through AJAX?
First of all, you should create an ajax1.html and one sample.txt file. then copy and paste the below codes to view the result. for below code testing. place the file in htdocs folder of xampp and open URL like this: http://localhost/ajax/ajax1.html
ajax1.html
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>ajax example 1 - Get Text Files</title> | |
</head> | |
<body> | |
<button id="button">Get Text File</button> | |
<br> | |
<br> | |
<div id="text" style="color: red; border:2px solid black; margin: 10px;"></div> | |
<script> | |
//Create Event Listener | |
document.getElementById('button').addEventListener | |
('click',loadText); | |
function loadText(){ | |
// Create XHR Object | |
var xhr = new XMLHttpRequest(); | |
// OPEN - type, url/file, async | |
xhr.open('GET', 'sample.txt', true); | |
console.log('READYSTATE: ', xhr.readyState); | |
// OPTIONAL : used for loaders | |
xhr.onprogress = function (){ | |
console.log('READYSTATE: ', xhr.readyState); | |
} | |
xhr.onload = function(){ | |
console.log('READYSTATE: ', xhr.readyState); | |
if(this.status == 200){ | |
// console.log(this.responseText); | |
document.getElementById('text').innerHTML = this.responseText; | |
} | |
else if(this.status = 404){ | |
document.getElementById('text').innerHTML = 'Not Found'; | |
} | |
} | |
xhr.onerror = function(){ | |
console.log('Request Error....'); | |
} | |
// xhr.onreadystatechange = function(){ | |
// console.log('READYSTATE: ', xhr.readyState); | |
// if(this.readyState == 4 && this.status == 200){ | |
// // console.log(this.responseText); | |
// } | |
// } | |
// Sends request | |
xhr.send(); | |
} | |
//readystate values | |
// 0: request not initialized | |
// 1: server connection established | |
// 2: request received | |
// 3: processing request | |
// 4: request finished and response is ready | |
// HTTP statuses | |
// 200: "OK" | |
// 403: "Forbidden" | |
// 404: "Not Found" | |
</script> | |
</body> | |
</html> |
sample.txt
What is Lorem Ipsum? | |
Lorem Ipsum is simply dummy text of the printing and typesetting industry. | |
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, | |
when an unknown printer took a galley of type and scrambled it to make a type specimen book. | |
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. | |
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, | |
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. | |
What is Lorem Ipsum? | |
Lorem Ipsum is simply dummy text of the printing and typesetting industry. | |
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, | |
when an unknown printer took a galley of type and scrambled it to make a type specimen book. | |
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. | |
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, | |
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. |
How to retrieve data from json files through AJAX?
there are some example code for this. so you can check out below:
ajax2.html
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>AJAX 2 - JSON Local</title> | |
</head> | |
<body> | |
<button id="button1">Get User</button> | |
<button id="button2">Get Users</button> | |
<br><br> | |
<h1>User</h1> | |
<div id="user"></div> | |
<h1>Users</h1> | |
<div id="users"></div> | |
<script> | |
document.getElementById('button1').addEventListener('click',loadUser); | |
document.getElementById('button2').addEventListener('click',loadUsers); | |
function loadUser(){ | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET','user.json', true); | |
xhr.onload = function(){ | |
if(this.status == 200){ | |
var user = JSON.parse(this.responseText); | |
// console.log(user.email); | |
var output = ''; | |
output += '<ul>' + | |
'<li>ID : '+user.id+'</li>' + | |
'<li>NAME : '+user.name+'</li>' + | |
'<li>Email : '+user.email+'</li>' + | |
'</ul>'; | |
document.getElementById('user').innerHTML = output; | |
} | |
} | |
xhr.send(); | |
} | |
function loadUsers(){ | |
var xhr1 = new XMLHttpRequest(); | |
xhr1.open('GET','users.json', true); | |
xhr1.onload = function(){ | |
if(this.status == 200){ | |
var users = JSON.parse(this.responseText); | |
//console.log(users.email); | |
var output = ''; | |
for(var i in users){ | |
output += '<ul>' + | |
'<li>ID : '+users[i].id+'</li>' + | |
'<li>NAME : '+users[i].name+'</li>' + | |
'<li>Email : '+users[i].email+'</li>' + | |
'</ul>'; | |
} | |
document.getElementById('users').innerHTML = output; | |
} | |
} | |
xhr1.send(); | |
} | |
</script> | |
</body> | |
</html> |
users.json
[ | |
{ | |
"id": "1", | |
"name":"Chandan", | |
"email":"chandan.cotocus@gmail.com" | |
}, | |
{ | |
"id": "2", | |
"name":"Pradeep", | |
"email":"pradeep.cotocus@gmail.com" | |
}, | |
{ | |
"id": "3", | |
"name":"Amardeep", | |
"email":"amardeep.cotocus@gmail.com" | |
} | |
] |
How to retrieve data from external API through AJAX?
please look the codes of ajax3.html and url of external source i.e : https://api.github.com/users
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>AJAX 3 - External API</title> | |
</head> | |
<body> | |
<button id="button">Load Github Users</button> | |
<br><br> | |
<h1>Github Users</h1> | |
<div id="users"></div> | |
<script> | |
document.getElementById('button').addEventListener('click', loadUsers); | |
//Load Github Users | |
function loadUsers(){ | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', 'https://api.github.com/users', true); | |
xhr.onload = function(){ | |
if(this.status == 200){ | |
var users = JSON.parse(this.responseText); | |
var output = ''; | |
for(var i in users){ | |
output += | |
'<div class="user">' + | |
'<img src="'+users[i].avatar_url+'" width="70" height="70">' + | |
'<ul>' + | |
'<li>ID: '+users[i].id+'</li>' + | |
'<li>Login: '+users[i].login+'</li>' + | |
'</ul>' + | |
'</div>' ; | |
} | |
document.getElementById('users').innerHTML = output; | |
} | |
} | |
xhr.send(); | |
} | |
</script> | |
</body> | |
</html> |
How to retrieve data from database through AJAX?
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>AJAX 5 - Fetch from PHP MySQL</title> | |
</head> | |
<body> | |
<button id="button">Get Users</button> | |
<br><br> | |
<h1>Users</h1> | |
<div id="users"></div> | |
<script> | |
document.getElementById('button').addEventListener('click',loadUsers); | |
function loadUsers(){ | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET','users.php', true); | |
xhr.onload = function(){ | |
if(this.status == 200){ | |
var users = JSON.parse(this.responseText); | |
//console.log(users.email); | |
var output = ''; | |
for(var i in users){ | |
output += '<ul>' + | |
'<li>ID : '+users[i].id+'</li>' + | |
'<li>NAME : '+users[i].name+'</li>' + | |
'</ul>'; | |
} | |
document.getElementById('users').innerHTML = output; | |
} | |
} | |
xhr.send(); | |
} | |
</script> | |
</body> | |
</html> |
users.php
<?php | |
//Create Connection | |
$conn = mysqli_connect('localhost', 'root', '','ajaxtest'); | |
$query = 'SELECT * FROM users'; | |
// Get Result | |
$result = mysqli_query($conn, $query); | |
// Fetch data | |
$users = mysqli_fetch_all($result, MYSQLI_ASSOC); | |
echo json_encode($users); | |
?> |
there are 4 examples explained above for retrieving data from different locations by the help of Ajax. so this example are very easy to understand and apply it to your project easily. so if you hava any confusion then watch this video: Link .
Thanks for supporting us. if you like this blog then share with your friends.
MotoShare.in provides the perfect two-wheeler for every occasion—daily commuting, weekend escapes, tourist exploration, or test-riding your dream bike. Simplify your mobility with us!