[Learning]#29 JS: AJAX

Vida Lin
2 min readOct 19, 2021

--

What is AJAX?

"AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language, it just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

AJAX is a developer’s dream, because you can:

  • Read data from a web server — after a web page has loaded
  • Update a web page without reloading the page
  • Send data to a web server — in the background”

by W3C School

Before learning AJAX, we have to know how to build up a web server

Tutorial in Mandarin: Build up web server

Step by step:

  1. Install Chrome Extension Web Server for Chrome, and choose a root folder.
  2. Create an HTML file with a simple context.
  3. Copy and combine the web server URL and the name of our HTML file together.
    Done!!

How does AJAX work?

Usage Scenario: To create a personal blog or whatever main page containing URLs that needs to be transferred to other website.
As mentioned, before this menu page practice, we should create multiple HTML pages so that we can connect through the server. (I created Writing.html and Portfolio.html)

From the example above, AJAX helps request other pages’ data through the server immediately when we click Writing or Portfolio at this Menu page.

<body onload="getData('Writing.html')" style="font-family:Arial">
<div>
<span onclick="getData('Writing.html');">Writing</span>
<span onclick="getData('Portfolio.html');">Portfolio</span>
</div>
<!-- adding a horizontal line -->
<hr/>
<div id="content"></div>

<script type="text/javascript">
function getData(pageName){
//AJAX XMLHttpRequest object: for connecting with the server.
let req=new XMLHttpRequest();
req.open("get","http://127.0.0.1:8887/"+pageName); //setting the connection and URL.
req.onload=function(){ //Use load event to detect when the connection is finished.
// From here, the connection is done.
let content=document.getElementById("content");
content.innerHTML=this.responseText;
};
req.send();//Call the "send" to send out the connection request.
}
</script>
</body>

*Note:Add onload=”getData(‘Writing.html’)” to <body> will present the Writing page's content once we open up the menu page.

Music of Today: Without You by Oh Wonder

Clap/Share/Follow

If you guys find this article helpful, please kindly do the writer a favor — giving 5 clicks at the GREEN area and 10~50 claps at the bottom of this page.

Most important of all, feel free to comment and share your ideas below to learn together!

--

--

Vida Lin
Vida Lin

Written by Vida Lin

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤

No responses yet