How to handle the TypeError when event is undefined

I want to capture a user's postal code in order to retrieve the representatives for that area. To troubleshoot, I am trying to log the postal code and the URL containing the postal code.

$(document).ready(function() {
      //When the user submits a postal code (e.g. K2H6G7)
      $("form").on("submit", function(event) {
          var request = new XMLHttpRequest();
          event.preventDefault();
          var searchWord = $("#search").val(); //Get postal code and add it to URL
          var url = "https://represent.opennorth.ca/postcodes/" + searchWord + "/?format=apibrowser";
          console.log(searchWord);
          console.log(url) request.open('GET', url, true);
          request.onreadystatechange = function() {
            if (request.readyState === 4) {
              if (request.status === 200) {
                //Connect to API, create cards for each politician instance
                var data = JSON.parse(this.response);
                data.representatives_centroid.forEach(representatives_centroid => {
                  const card = document.createElement('div');
                  card.setAttribute('class', 'card');
                  const img = document.createElement('img');
                  img.src = representatives_centroid.photo_url;
                  const p1 = document.createElement('p');
                  p1.textContent = `$ {
              representatives_centroid.party_name
            }
            $ {
              representatives_centroid.elected_office
            }
            $ {
              representatives_centroid.first_name
            }
            $ {
              representatives_centroid.last_name
            }
            ` 
                  const p2 = document.createElement('p');
                  p2.textContent = `$ {
              representatives_centroid.district_name
            }
            ` //Add data to card
                  container.appendChild(card);
                  card.appendChild(img);
                  card.appendChild(p1);
                  card.appendChild(p2);
                });
              } else {
                console.log('error');
              }
            }
          }
          request.send();
        }
        ());
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form">
  <form type="text" class="form-inline" role="form">
    <label for="address" name="postalcode">Enter an address or postal code</label>
    <input id="search" placeholder="Enter an address or postal code" type="text">
    <button id="go">
    <span class="glyphicon glyphicon-search"></span> Find
  </button>
  </form>
</div>

I keep getting the error message "TypeError: event is undefined". Is there something obvious that I'm missing?

Answer №1

Revise how you use the closing brackets

$(document).ready(function() {   

//Make sure to wait for user submission of postal code (e.g. K2H6G7)
$("form").on("submit", function(event) {
    var request = new XMLHttpRequest();
    event.preventDefault();
    var searchWord = $("#search").val();   //Get postal code and append to URL
    var url = "https://represent.opennorth.ca/postcodes/" + searchWord + "/?format=apibrowser";
    console.log(searchWord);
    console.log(url)

    request.open('GET', url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            if (request.status === 200) {

                //Establish connection with API, generate cards for each politician
                var data = JSON.parse(this.response);
                data.representatives_centroid.forEach(representatives_centroid => {
                    const card = document.createElement('div');
                    card.setAttribute('class', 'card');
                    const img = document.createElement('img');
                    img.src = representatives_centroid.photo_url;
                    const p1 = document.createElement('p');
                    p1.textContent = `${representatives_centroid.party_name} ${representatives_centroid.elected_office} ${representatives_centroid.first_name} ${representatives_centroid.last_name}`
                    const p2 = document.createElement('p');
                    p2.textContent = `${representatives_centroid.district_name}`

                    //Fill card with data
                    container.appendChild(card);
                    card.appendChild(img);
                    card.appendChild(p1);     
                    card.appendChild(p2);
                });
        } else {
                console.log('error');
        }
    }
}
request.send();

//The revised closing bracket should be }) instead of }()); 
 // Change from }());  to });
});

});

Answer №2

Can someone clarify the purpose of the "type" attribute in a form?

I believe that the type="text" is specifically for input fields, and instead of focusing on the type attribute, you may need to include an action="/route/" in order to trigger an event and potentially avoid any issues.

Sincerely,-

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

Is there a way to determine in JavaScript whether an HTML element contains no visible data, such as text or images?

In my web application, I have a feature that eliminates specific elements from a webpage. After the initial filtering, I am looking to remove all divs that previously held content but no longer do. For instance, after the first pass, an element may appear ...

What is the method for including the sources directory within the require() scope in npm?

Upon examining my directory structure, the following layout is revealed: package.json /src a.js /test test_a.js The contents of package.json are as follows: { "name": "foo", "scripts": { "test": "mocha" }, "devDependencies": { "mocha ...

Tips for efficiently parsing and converting multiple JSON strings into dataframe rows using R

Greetings to the community, I am a newcomer to stackoverflow and I hope I have presented my problem accurately. I have an R dataframe structured as follows: ID|Product1|Type |Product_JSON_string 1 | Bread |Grocery |{"ID":"1",&quo ...

Handling Asynchronous API Requests with AngularJS

I am facing an issue with displaying data from API in my files foo.js and foo.html. While fetching information asynchronously in foo.js, I store it in an object that should be accessible in foo.html. However, despite receiving the data correctly, I am una ...

Can one jQuery script be used for multiple ajax 'like' buttons?

Hey there! I'm working on an Ajax 'like' button that utilizes jQuery. This button will be utilized multiple times on a single page. I'm looking for a way to streamline the process and avoid including the jQuery script multiple times. Is ...

The width values in the array are constantly shifting upon refreshing

Would it be possible to create an array called slide_widths, which will contain the widths of all the .slide elements? $( document ).ready(function() { var $slider = $('.slider ul'); var slider_width = $slider.width(); var $slides = $(&apo ...

PHP script integration with WHMCS

I've been attempting to add analytic.php into head.tpl in WHMCS, but I keep encountering an error. Analytic.php location: root/analytic.php Head.tpl location: root/whmcs/template/six/includes/head.tpl I read that WHMCS supports Smarty PHP, so I&apos ...

What is the best way to add a new item to an object using its index value?

Can the Locations object have a new property added to it? The property to be added is: 2:{ name: "Japan", lat: 36, lng: 138, description: 'default', color: 'default', url: 'default' } The current Location ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...

Converting JSON data into Java objects

{ "city" : "THAYNE", "loc" : [ -111.011354, 42.933026 ], "pop" : 505, "state" : "WY", "_id" : "83127" } I have been given some JSON syntax and I am looking to convert it into a Java object. Initially, I crea ...

Unable to halt a timer running on an interval, clearInterval() shows its limitations

Today is the first time I am experimenting with using clearInterval(). After exploring various examples and studying the interval documentation, it seems like this function is crucial for stopping an interval. However, I must be missing something. The mai ...

Ensuring that form submissions originate from a specific URL requirement in Laravel and iframe integration

My current project involves creating a service that allows users to submit a form via an iframe on their own website. The challenge is ensuring that the form can only be submitted from the domain listed in their User model. I am aware that this is achieva ...

Tips for centering div content using bootstrap

https://i.sstatic.net/GtIi0.pngI am trying to align 3 divs in a row at the center of the page. <div class="row"> <div class="center"> <div class="col-sm-4" id="ph-container"></div> <div class="col-sm-4" id="do-contai ...

Strategies for structuring CoreData to manage intricate datasets

I am faced with the task of storing JSON data locally using CoreData, which is retrieved from an API call. The challenge lies in the complexity of the JSON structure, as it consists of a main Dictionary with 4 keys, each key containing further nested Dict ...

What is the best method for accessing data from an Array of Objects in AngularJS?

I am trying to call a REST service and display data based on the regInventoryId. I have successfully displayed some objects, but I am having trouble populating the view for SubpartId. Any suggestions or feedback would be greatly appreciated. Here is the c ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

Discovering a way to showcase every event a user is linked to, employing Fullcalendar Rails

Here is the current model structure: class User < ActiveRecord::Base has_and_belongs_to_many :event_series has_many :events, through: :event_series end class Event < ActiveRecord::Base belongs_to :event_series end class EventSeries < Activ ...

Line 16 is encountering issues with statically analysing the 'require(...)' function

Currently, I am working with nextjs and encountering an problem when trying to import 'markdown-toc'. The issue arises while importing markdown-toc in my Next.js project specifically in the file /pages/index.js. import toc from "markdown-to ...

Is there a way to automatically redirect the server URL when a file is modified?

I am currently experimenting with a function that is supposed to only display a message in the console without redirecting the actual URL of my server when a file is changed. watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watche ...

What are some ways to disguise websockets?

I'm currently working on writing a JavaScript client that sends websockets to a node.js/ws server. I've been doing a lot of research and have come across information indicating it's useful, or even required by RFC, to mask all data sent from ...