Skip to content

Get Data with Pure JavaScript (XMLHttpRequest)

I will show you how to get data by using pure JavaScript (VanillaJS) in this tutorial. I am going to make a XMLHttpRequest to an endpoint, handle the response and display the data received. The data received in a request can be in any format (XML, JSON, HTML, MP3, MP4), I am going to get HTML-data in this tutorial.

XMLHttpRequest (XHR) objects is used in JavaScript to interact with servers. XMLHttpRequest can be used for all type of data, it is not just XML as the name implies. HTTP defines several methods that describes the action that will be performed on the server. GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT and PATCH are methods that might be present in server methods. If we want to get data, we are only allowed to call server methods that is declared as a GET-method. CORS must be enabled on the endpoint in order for us to be able to make request from JavaScript.

This code has been tested and is working with Google Chrome (75.0.3770.100), Mozilla Firefox (67.0.4) and Microsoft Edge (42.17134.1.0), without any polyfill. It works in Internet Explorer (11.829.17134.0) with a polyfill for XMLHttpRequest. If you want to support older browsers, check out our post on transpilation and polyfilling of JavaScript.

HTML-Template

@using Annytab.Repositories
@using Annytab.Models
@inject IGroupRepository group_repository
@{
    // Get a group
    Group group = ViewBag.Group;
    IList<TeamInGroupStanding> teams = this.group_repository.GetTeamsFromXml(group.data_content);
    Int32 rowCounter = 0;
}

@*Get teams in the group*@
<a href="@("https://www.hockeytabeller.se/home/group/" + group.page_name)" rel="nofollow" class="annytab-ht-not-hover">
    <div class="annytab-ht-table">
        <div class="annytab-ht-row">
            <div class="annytab-ht-col-th-normal">RK</div>
            <div class="annytab-ht-col-th-wide">Lag</div>
            <div class="annytab-ht-col-th-normal">GP</div>
            <div class="annytab-ht-col-th-normal">TP</div>
        </div>

@for (int j = 0; j < teams.Count; j++)
{
    @if (teams[j].name == "")
    {
        <div class="annytab-ht-row">
            <div class="annytab-ht-col-line"></div>
            <div class="annytab-ht-col-line"></div>
            <div class="annytab-ht-col-line"></div>
            <div class="annytab-ht-col-line"></div>
        </div>
    }
    else
    {
        rowCounter++;
        <div class="@(rowCounter % 2 != 0 ? "annytab-ht-row-main" : "annytab-ht-row-alt")">
            <div class="annytab-ht-col-normal">@((rowCounter).ToString())</div>
            <div class="annytab-ht-col-wide">@teams[j].name</div>
            <div class="annytab-ht-col-normal">@teams[j].games</div>
            <div class="annytab-ht-col-normal">@teams[j].points</div>
        </div>
    }
}
    </div>
</a>

Web-API Method

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using Annytab.Repositories;
using Annytab.Models;

namespace Hockeytabeller.Api
{
    /// <summary>
    /// This class handles groups
    /// </summary>
    [Route("api/groups/[action]")]
    public class GroupsController : Controller
    {
        #region Variables

        private readonly ILogger logger;
        private readonly IGroupRepository group_repository;

        #endregion

        #region Constructors

        /// <summary>
        /// Create a new controller
        /// </summary>
        public GroupsController(ILogger<GroupsController> logger, IGroupRepository group_repository)
        {
            // Set values for instance variables
            this.logger = logger;
            this.group_repository = group_repository;

        } // End of the constructor

        #endregion

        #region Get methods

        // Get html by page name
        // GET api/groups/get_overview_as_html/shl
        [HttpGet("{id}")]
        [Microsoft.AspNetCore.Cors.EnableCors("AnyOrigin")]
        [ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Any)]
        public IActionResult get_overview_as_html(string id = "")
        {
            // Get a group
            Group group = this.group_repository.GetOneByPageName(id);

            // Create view data
            ViewDataDictionary view_data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
            view_data.Add("Group", group);

            // Return a partial view
            return new PartialViewResult { ViewName = "Views/home/_group_table.cshtml", ViewData=view_data, ContentType="text/html" };

        } // End of the get_overview_as_html method

        #endregion

    } // End of the class

} // End of the namespace

JavaScript

The code below is used to make a XMLHttpRequest to get HTML-data from a Web-API method. The data received is displayed below the code. Use Chrome DevTools to check responses and logs.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test</title>
    <style>
        .annytab-ht-not-hover {
            text-decoration: none;

        }

        .annytab-ht-table {
            display: table;
            width: 100%;
            padding: 0px;
            margin: 0px;
            font-family: Arial, Helvetica, sans-serif;
            background-color: #ffffff;
            color: #000000;
            overflow: hidden;
        }

        .annytab-ht-row {
            display: table-row;
        }

        .annytab-ht-row-main {
            display: table-row;
            background-color: #ffffff;
        }

        .annytab-ht-row-alt {
            display: table-row;
            background-color: #f0f0f0;
        }

        .annytab-ht-col-th-normal {
            display: table-cell;
            padding: 4px;
            color: #3d3d3d;
            border-bottom: 1px solid #9e9e9e;
            border-top: 1px solid #9e9e9e;
            font-size: 14px;
            line-height: 18px;
            vertical-align: middle;
            text-align: center;
            width: 20%;
        }

        .annytab-ht-col-th-wide {
            display: table-cell;
            padding: 4px;
            color: #3d3d3d;
            border-bottom: 1px solid #9e9e9e;
            border-top: 1px solid #9e9e9e;
            font-size: 14px;
            line-height: 18px;
            vertical-align: middle;
            text-align: left;
            width: 40%;
        }

        .annytab-ht-col-line {
            display: table-cell;
            height: 1px;
            background-color: #000000;
            padding: 0px;
        }

        .annytab-ht-col-normal {
            display: table-cell;
            padding: 4px;
            font-size: 12px;
            line-height: 12px;
            word-break: break-word;
            vertical-align: middle;
            text-align: center;
        }

        .annytab-ht-col-wide {
            display: table-cell;
            padding: 4px;
            font-size: 12px;
            line-height: 12px;
            word-break: break-word;
            vertical-align: middle;
            text-align: left;
        }
    </style>

</head>

<body style="width:100%;font-family:Arial, Helvetica, sans-serif;padding:20px;">

    <div class="hockeytabeller.se" data-group="shl"></div>

</body>

</html>

<script>
    // Initialize when DOM content has been loaded
    document.addEventListener('DOMContentLoaded', function () {
        var elements = document.getElementsByClassName('hockeytabeller.se');
        for (var i = 0; i < elements.length; i++) {
            get_group(elements[i]);
            }
        }, false);

    // Get a group
    function get_group(element)
    {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://www.hockeytabeller.se/api/groups/get_overview_as_html/' + element.getAttribute('data-group'), true);
        xhr.onload = function ()
        {
            // Success status codes can also be 201, 202, 203, 204 and more
            if (xhr.status === 200)
            {
                element.insertAdjacentHTML('beforeend', xhr.response);
            }
            else
            {
                // Log error information
                console.log(xhr.status + " - " + xhr.statusText);
            }
        };
        xhr.onerror = function ()
        {
            // Log error information
            console.log(xhr.status + " - " + xhr.statusText);
        };
        xhr.send();

    } // End of the get_group method
</script>

Response

<a href="https://www.hockeytabeller.se/home/group/shl" rel="nofollow" class="annytab-ht-not-hover">
	<div class="annytab-ht-table">
		<div class="annytab-ht-row">
			<div class="annytab-ht-col-th-normal">RK</div>
			<div class="annytab-ht-col-th-wide">Lag</div>
			<div class="annytab-ht-col-th-normal">GP</div>
			<div class="annytab-ht-col-th-normal">TP</div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">1</div>
			<div class="annytab-ht-col-wide">Lule&#xE5; HF</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">106</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">2</div>
			<div class="annytab-ht-col-wide">F&#xE4;rjestad BK</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">92</div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">3</div>
			<div class="annytab-ht-col-wide">R&#xF6;gle BK</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">92</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">4</div>
			<div class="annytab-ht-col-wide">Skellefte&#xE5; AIK</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">90</div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">5</div>
			<div class="annytab-ht-col-wide">HV 71</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">89</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">6</div>
			<div class="annytab-ht-col-wide">Djurg&#xE5;rdens IF</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">88</div>
		</div>
		<div class="annytab-ht-row">
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">7</div>
			<div class="annytab-ht-col-wide">Fr&#xF6;lunda HC</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">85</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">8</div>
			<div class="annytab-ht-col-wide">&#xD6;rebro HK</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">85</div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">9</div>
			<div class="annytab-ht-col-wide">IF Malm&#xF6; Redhawks</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">77</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">10</div>
			<div class="annytab-ht-col-wide">V&#xE4;xj&#xF6; Lakers HC</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">70</div>
		</div>
		<div class="annytab-ht-row">
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">11</div>
			<div class="annytab-ht-col-wide">Link&#xF6;ping HC</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">65</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">12</div>
			<div class="annytab-ht-col-wide">Bryn&#xE4;s IF</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">60</div>
		</div>
		<div class="annytab-ht-row">
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
			<div class="annytab-ht-col-line"></div>
		</div>
		<div class="annytab-ht-row-main">
			<div class="annytab-ht-col-normal">13</div>
			<div class="annytab-ht-col-wide">Leksands IF</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">49</div>
		</div>
		<div class="annytab-ht-row-alt">
			<div class="annytab-ht-col-normal">14</div>
			<div class="annytab-ht-col-wide">IK Oskarshamn</div>
			<div class="annytab-ht-col-normal">52</div>
			<div class="annytab-ht-col-normal">44</div>
		</div>
	</div>
</a>

Leave a Reply

Your email address will not be published. Required fields are marked *