Retrieving and delivering JSON data using AJAX, Javascript, and HTML

Struggling to integrate open data information from a website onto an AJAX form using JS and HTML. The source I'm trying to use is this link.

Here's my HTML form:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset=utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AJAX Assignment</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css"> 
    <script src="ajax.js"></script>
  </head>
    <body>
      <div class="container">
      <h1 class="title">Winnipeg's Plow Schedule</h1>
      <h2 class="subtitle">Search the history of the City of Winnipeg's Snow Plow schedule'.</h2>
      <form class="box" id="searchform"> 
      <div class="field">
        <label class="label">Search for Plow Zone by Zone Letter</label>
      </div>
      <div class="field has-addons"> 
        <div class="control is-expanded"> 
          <input class="input is-full-width" name="common-name" id="common-name"> 
        </div> 
        <div class="control"> 
          <button class="button is-primary" type="submit" id="submit">Search</button> 
        </div> 
      </div>
      </form><br>
      <h2 class="explanation subtitle"></h2> <br> 
      <div id = "div1">
        <table class="table is-fullwidth is-hoverable trees">
          <thead></thead> 
          <tbody></tbody>
        </table> 
      </div>
      <br>  
         
     <p> Plow data provided by the <a href="https://data.winnipeg.ca/">City of Winnipeg Open Data catalogue</a>. </p> 
   </div>       
      </div> 
    </body>

</html>

Javascript code used:

    function fetch(){

    let commonName = document.getElementById("common-name").value.toLowerCase(); 
    const apiUrl = 'https://data.winnipeg.ca/resource/tix9-r5tc.json' +
                `$where=common_name LIKE '%${commonName}%'` +
                '&$order=shift_start DESC' +
                '&$limit=100';
    const encodedURL = encodeURI(apiUrl);

    fetch(encodedURL)
    .then(function(result) {
      return result.json(); // Promise for parsed JSON.
    })
    .then(function(data) {

        let body = document.getElementByTagName("tbody")[0];
      
        let headingRows = document.createElement("tr");
        body.appendChild(headingRows);

        let nameHead = document.createElement("th");
        nameHead.innerHTML = 'Zone';
        headingRows.appendChild(nameHead);

        let startHead = document.createElement("th");
        startHead.innerHTML = 'Shift Start';
        headingRows.appendChild(startHead);

        let endHead = document.createElement("th");
        endHead.innerHTML = 'Shift End';
        headingRows.appendChild(endHead);

        for (let i = 0; i< data.length; i++) {
            let createRows = document.createElement("tr");
            body.appendChild(createRows);

            let createName = document.createElement("td");
            createName.innerHTML = data[i].plow_zone;
            createRows.appendChild(createName);

            let createStart = document.createElement("td");
            createStart.innerHTML = data[i].shift_start;
            createRows.appendChild(createStart);

            let createEnd = document.createElement("td");
            createEnd.innerHTML = data[i].shift_end;
            createRows.appendChild(createEnd);
       } 

    });
  }

  function load(){
   document.getElementById("submit").addEventListener("click", 
    function(){fetch()});
  }
   document.addEventListener("DOMContentLoaded", load);

After running the page and searching for the Plow Zone, it produces the following output: https://i.sstatic.net/PWoc8.png

If anyone can spot where the issue lies, your help would be greatly appreciated. It seems like the event listener for the button might not be calling the fetch function correctly or there could be a problem with the Javascript.

Answer №1

The issue in your code arises from a function named fetch(){. Inside this function, you are calling fetch(encodedURL), which results in an infinite recursion. To fix this error, rename your outer function to something different.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After repeated attempts to initialize and destroy, Froala encounters issues when loading a textarea via Ajax

Whenever an EDIT button is clicked to update some Blog Data, it triggers an Ajax call that brings up a textarea for Froala and initiates the initialization process. This sequence works smoothly initially, but after a few cycles of edit/submit (1, 2, or 3 o ...

The JSON response from Ajax is not coming back as anticipated

My attempts to make a basic ajax call are failing; var getPrevious = function(){ console.log('ajaxing'); $.ajax({ type: 'GET', dataType: "json", url: 'http://'+DOMAIN+'/previous', ...

Retrieve static dropdown options from a service rather than directly populating them in the HTML code

Recently, I have been working on this HTML code. <select ng-model="Type"> <option value=""></option> <option value="10D">10 Days</option> <option value="20D">20 Days</option> <option value="30D">30 Days ...

Large objects can cause the animation to come to a standstill during

As I navigate through a large object containing 2000 elements, my react loading spinner comes to a standstill. What strategy should I take to resolve this issue without resorting to using a web worker? Currently, I am utilizing a $.each element to proces ...

Monitoring Logfile in Ruby On Rails 3.1

Within my Ruby on Rails application, I have a set of scripts that need to be executed. In order to ensure they are working properly, the application must display and track the content of logfiles generated by these scripts. To provide more context: I util ...

Is there a way to prevent advertisements from appearing in npm?

As I execute various npm commands, my console gets bombarded with ads promoting different projects and individuals. While I enjoy contributing to open source projects, I believe the console output of a tool should not be used for advertising. Thank you fo ...

Leveraging a standalone Vue project as a node package within another project

I'm facing a challenge in my projects due to architectural changes and am in need of some guidance to move forward. Here is the issue at hand. Situation Originally, I began with a single Vue application that included various components such as queryi ...

What is the best way to eliminate a specific group of characters from a collection of strings in Javascript or AngularJS while avoiding duplicating them?

Imagine I have an array like this: $scope.array = ["ABC", "ABCDEF", "ABCDEFGHI", "ABCAFGKJA"]; Is there a way to transform it into the following format? $scope.array = ["ABC", "DEF", "GHI", "KJ"]; Apologies if my question is unclear, I'm still get ...

Retrieve data from server using Angular and present content on a dedicated webpage

I am currently working on a page that displays all usernames, and when I click on a username, I want to retrieve more information from the server and display it on a separate User page (including first name, last name, etc). However, I am encountering an ...

How can event.target.value and event.target.checked be used simultaneously in React.js?

I have a combination of input fields including text and checkboxes. What is the best way to retrieve all the field values together? Currently, I can only get one value at a time as shown in the example below: handleChange = event => { this.setState( ...

Achieving port forwarding in Node.js with a proxy server: a comprehensive guide

I am currently working on a Node.js project where I need to set up a proxy server to forward requests from one port to another. The code I found online is not working properly, so I may be doing something wrong. I would appreciate any help in providing a w ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...

Surfing the web with Internet Explorer means music downloads rather than streaming

My music website functions properly, however I am experiencing issues when accessing it through Internet Explorer. The internet download manager is downloading music from the site without any problems in Chrome and Firefox. Is there a way to prevent or b ...

securely load HTML form with data stored in MySQL

I have developed a basic HTML/JS math form for performing calculations. To simplify the form, I made it more concise for clarity: function output(){ var value1 = document.getElementById('value1').value; var ...

Include a for loop in the line graph on Google Charts

I need help figuring out how to use a for loop to iterate over data in order to populate my Google Chart. The code snippet below outlines what I've already tried. var line_div = '2016-08-04,4|2016-08-05,7|2016-08-06,9|2016-08-07,2'; var lin ...

What is the best way to tile textures in Three.js without causing distortion?

Despite trying various solutions, I am still facing an issue where my textures appear to be stretched or scaled based on the mesh size. In a bid to seek a resolution, here are some key points to note: All textures have dimensions of 64x64 pixels I have p ...

What is the best method for serializing data associated with the current item in a jQueryUI sortable list?

Currently working with jQueryUI 1.8.14, I am interested in creating a sortable list and saving any changes to item positions in my application database whenever a user adjusts an item's position. To achieve this, my plan is to retrieve and serialize ...

How can I showcase a Google donut chart using an array of data in a React application?

I have created a doughnut chart that is supposed to take an array as data. However, when I input the array, nothing shows up on the chart. How can I create a chart with array data? sum.js ... const arr = []; arr.push({ key: capitalizeEachFirst ...

Retrieve the updated file name from the mini file upload form

I have implemented the Mini AJAX Upload Form from this tutorial to upload files to a server. I made modifications to add a timestamp at the end of the file name. How can I return the updated file name (with the timestamp) back to the client for future refe ...

What is the method for gaining access to variables and functions within bundle.js?

Hello, I am trying to figure out how to access variables in bundle.js. I want to experiment with variables and functions on the client side using JavaScript, but I'm having trouble calling them in index.html or the Chrome console. I use browserify to ...