DEV Community

Hamid Haghdoost
Hamid Haghdoost

Posted on

Simple exercise for Javascript Ajax

I have about 4 years of experience working as private tutor of programming. About five years ago I published a blog post in my website in Persian language about entitled "Private Laravel Tutor" and people started to call me. I always love teaching people and it was a good opportunity.
After a while the number of student raise up and today I have two sessions per day in average and most of my previous students are working around the world.
Today I had a JS session about Working with AJAX. I post the content of the codes for beginner friends at this community.

Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learning Ajax</title>

    <link rel="stylesheet" href="css/app.css">
    <button class="btn" id="load">Load Posts</button>
    <button class="btn" id="clear">Clear Posts</button>
    <div id="posts">

    <script src="js/app.js"></script>
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode
body {
    margin: 0;

#posts {
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;

.post {
    width: 25%;
    margin: 20px;
    border: 3px solid rgb(36, 220, 91);
    padding: 10px;

.post:hover {
    border: 3px solid rgb(0, 0, 0);

.post h1 {
    font-family: cursive;

.btn {
    padding: 10px;
    margin: 10px;
    background-color: rgb(36, 220, 91);
    color: black;
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode

document.getElementById("load").addEventListener("click", function () {
    url = "";

function sendAjax(url) {
    let http = new XMLHttpRequest();
    http.onload = function () {
        let posts_element = document.getElementById("posts");
        let posts = JSON.parse(this.responseText);

        posts.forEach(function (post) {
            let div = document.createElement("div");
            div.className = "post";

            let h3 = document.createElement("h3");
            h3.textContent = post.title;

            let p = document.createElement("p");
            p.textContent = post.body;

    };"GET", url);

document.getElementById("clear").addEventListener("click", function () {
    let posts_element = document.getElementById("posts");
    posts_element.textContent = ''
Enter fullscreen mode Exit fullscreen mode

If you are looking for a tutor, feel free to contact me :)

Top comments (0)