Different way of processing the GET request in Javascript

||
Posted 1 year, 4 months ago
||
Views 148
||
3 min read
0 reactions

We are going to discuss about the different way of processing the GET request in JAVASCRIPT. We can use this approach to get the data from Django, PHP, REST API (basically all backend framework)

Lets assume, we have the /todo/api/ URL where it will all list of given tasks which we added,

Now we can add , basic HTML in order to process this,

<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
    integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  <title>Hello, world!</title>
</head>

<body>
  <div class="container">
    {% block content %}
    {% endblock content %}
  </div>


  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
    integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
    crossorigin="anonymous"></script>
  {% block js %}

  {% endblock js %}
</body>

</html>

In this example, I am using the Django backend framework to get the data,

Now, we need to add the place holder to load the list of tasks dynamically

so, i am going to extends my base.html ,

{% extends 'todo/base.html' %}
{% block content %}
<h1> Todo List </h1>
<br>


<br>


<div id='todo'>
   
</div>

{% endblock content %}
{% block js %}
{% endblock js %}

Now, its time to add the JS to load the content into <div id='todo'></div> here.

First Approach,

Its old method, but still its supported to GET the data,

const todoElement = document.getElementById("todo") // get an html element
    todoElement.innerHTML = 'Loading...' // set new html in that element
    const xhr = new XMLHttpRequest()
    const method = 'GET'
    const url = "/todo/api/"
    const responseType = "json"

    xhr.responseType = responseType
    xhr.open(method, url)
    xhr.onload = function () {
        const serverResponse = xhr.response
        let finalTodoStr = ""
        var listedItems = serverResponse.response
        for (i = 0; i < listedItems.length; i++) {

            var currentItem = "<div class='mb-4'><p>" + listedItems[i].name + "</p></div>"
            finalTodoStr += currentItem
        }
        todoElement.innerHTML = finalTodoStr
    }
    xhr.send()

Second Approach:

Using jquery for loop method,

 $.ajax({
        url: '/todo/api/',
        type: 'GET',

        success: function (data) {
            const serverResponse = data
            let finalTodoStr = ""
            var listedItems = serverResponse.response
            for (i = 0; i < listedItems.length; i++) {
                var currentItem = "<div class='mb-4'><p>" + listedItems[i].name + "</p></div>"
                finalTodoStr += currentItem

            }
            todoElement.innerHTML = finalTodoStr
        }
    });

Above method is more convenient if you want to stick with Jquery 

Third approach:

This is also using Jquery but more specifically using each function

	const todoElement = document.getElementById("todo")
    $.ajax({
        url: '/todo/api/',
        type: 'GET',

        success: function (data) {
            const serverResponse = data
            var listedItems = serverResponse.response
            // console.log(listedItems)
            let finalTodoStr = ""
            $.each(serverResponse.response, function (k, v) {
                var currentItem = "<div class='mb-4'><p>" + v.name + "</p></div>"
                finalTodoStr += currentItem
            })
            todoElement.innerHTML = finalTodoStr

        }
    });
	

Last Approach:

This is ES6 javascript style using FETCH API. I like this approach as it is more easy to write,

	   const todoElement = document.getElementById("todo")

    fetch('/todo/api')
        .then(response => response.json())
        .then((data) => {
            console.log(data.response);
            let finalTodoStr = ""
            data.response.forEach(elem => {
                console.log('foreach', elem);
                var currentItem = `<div class='mb-4'><p> ${elem.name}</p></div>`
                finalTodoStr += currentItem
            })
            todoElement.innerHTML = finalTodoStr
        })

I hope you like this. Happy Coding !!!


0 reactions

Discussion


Actively looking for JOBS
Joined on April 15, 2020


Latest Videos


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message