Attempting to include form input in the URL for a GET request

I'm trying to figure out how to include an object at the end of my URL, but for some reason $year isn't getting added to the GET request.

    <input type = "text" id="year">
            <input type = "submit" id="btn">
    
    <script >
    
    document.getElementById("btn").addEventListener("click", function() {
           
            var $year = document.getElementById("year");
            request = new XMLHttpRequest();
            request.open("GET", "https://mudfoot.doc.stu.mmu.ac.uk/node/api/halloffame?year="+$year, true);
            request.send(null);
    
            
        }
        return val;
      }

Answer №1

To retrieve the value of a selected element, use the value() function after getElementById.

<input type="text" id="year">
<input type="submit" id="btn">

<script>
    document.getElementById("btn").addEventListener("click", function () {
        var $year = document.getElementById("year").value;
        request = new XMLHttpRequest();
        const reqUrl = "https://mudfoot.doc.stu.mmu.ac.uk/node/api/halloffame?year=" + $year
        console.log("reqUrl: ", reqUrl);  
        request.open("GET", reqUrl, true);
        request.send(null);
    })
</script>

Answer №2

Consider this approach:

document.getElementById("btn").addEventListener("click", function()
{
  var $year = document.getElementById("year").value;
  request = new XMLHttpRequest();
  request.open("GET", "https://mudfoot.doc.stu.mmu.ac.uk/node/api/halloffame?year=" + $year, true);
  request.send(null);
}

The issue may have been that you were not retrieving the value of the input field, but rather just selecting the element.

You were using:

document.getElementById("year")
which returns the element. Instead, use
document.getElementById("year").value
to get the value from the text box.

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

Middleware Error: JSON.stringify cannot serialize circular data structure

Here is a middleware function that increments the id of a new object added to an array: let lions = [] let id = 0 const updateId = function(req, res, next) { if (!req.body.id) { id++; req.body.id = id + ''; } next(); }; After pos ...

A double click is required to enable the connected mouse press/release action

I have a section of code that is giving me some trouble: $('.toggle_box').each(function (){ var timeout, longtouch; $(this).bind('mousedown', function() { timeout = setTimeout(function() { longtouch = tru ...

jQuery Side Panel with built-in back button support

I'm currently developing a portfolio website and I want to implement a feature where clicking on one of my projects will trigger a side panel to slide in from the right. The panel should cover 100% width and height of the viewport. I also want users t ...

How can I securely display raw HTML code in a textarea for CKeditor usage?

What specific character should I substitute in order to securely 'print' raw HTML code from a database into a textarea that can be edited with CKeditor? Alternatively, is there a recommended alternative method for populating a CKeditor textarea ...

Encountering a blank page and error message on Vue JS while attempting to generate a JSON file within the

Recently, I encountered a peculiar problem while working on my Vue project using Vue UI in Visual Studio. Before connecting my API, I wanted to prototype and experiment with fake data. So, I decided to create a JSON file in the assets folder to store my m ...

ways to transmit text data to the server without triggering form submission through ajax

In my form, there is a textbox for entering a username along with a submit button. Before submitting the form, I want to send the entered username to the server to check if it has already been taken by another user. I came across a helpful tutorial on how ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

Generate a unique JavaScript object without any redundancy

I am in the process of creating a JavaScript object that needs to be processed through a PHP API. The structure should resemble the following: [{ 'targetId': 'roof', 'color': 'red' }, { 'targetId': ...

Avoid activating automatic save feature in Material UI data grid

After creating a data-grid and attempting to add records, I encountered an issue where pressing the TAB key automatically saved the data when focusing on the save button without manually pressing enter. How can this behavior be prevented so that manual con ...

Issue with CodeIgniter 2.1 form_validation library when using ajax

Previously, I had a form that would either display an error if validation failed or submit the data to the DB table successfully. Everything was running smoothly. Now, my goal is to achieve the same functionality using AJAX, but for some reason, the valid ...

Horizontal Scrolling Menu for Dynamic Page Navigation

My goal was to create a smooth-scrolling one-page website that scrolls horizontally. One feature I wanted was a menu that smoothly slides into view whenever a new page is in focus along with the horizontal scrolling. I found an example of a scrolling scr ...

Combine all clicks into a single document instead of creating separate documents for each click

Every time I click, a separate document is created in the database. How can I ensure that all clicks are stored under the same document within a collection? Any suggestions on modifications to my code or commands to run in the terminal would be greatly app ...

Add a CSS class to the main document via an iframe

Is there a simple method to apply a CSS class that is specifically defined in the head of an iframe to an element located in the main document? Can this be done without having to resort to using JavaScript to copy the class from the iframe's head to ...

What is the best way to handle a single promise from a shared listener?

I am working on implementing an event listener that will receive events from a server whenever a specific task is completed. I want to structure each task as a promise to create a more organized and clean workflow. How can I resolve each task promise by i ...

saving selected values to the database

I have updated the question, thank you for your help. The code seems to be working fine but I need some assistance with increasing the booked count in the database when the user clicks "Confirm Choices." Additionally, if the user selects a booked image, ...

JavaScript function to add or remove a class upon clicking

Currently experiencing an issue with my accordion functionality. I have successfully implemented code that allows for toggling one heading open at a time, but I am struggling to add an open/close image beside each heading. At the moment, when a heading is ...

AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService. angular .module('someModule') .service('documentViewer', DocumentViewer); /* @ngInject */ function Do ...

Having trouble retrieving data from Laravel's JSON response object

This is one of the weirdest bugs I've come across in my coding experience. When a user submits a reply through AJAX in my controller, I'm returning a JSON response to retrieve the ID of that reply. $reply = Status::create([ 'body' ...

Connections between Ember and mongo databases

Currently, I am exploring the most effective approach for my Ember App. I am dealing with two separate models: events and bookings. In my database, I have structured them in a completely independent manner. Schemas: Events: attributes: date : ...

Validating forms in React with Material-UI using hooks

Currently, I am working on a Next.js project that utilizes Material-UI as the primary UI framework. For validation purposes, I am implementing a React hooks form. Within my main component, I have the form structure with separate child components for vari ...