Fixing a form's action attribute when using the GET method

Currently facing a minor issue with my code. To explain, I have a form within my index.html file:

The first page form looks like this:

<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
    <input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
    <button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search"></button>
</form>

With this particular form, I intend to incorporate the OpenWeatherMap API in order to retrieve weather data. My current challenge is as follows: I aim to capture user input from the form, which can be achieved by utilizing, for instance:

var searchInput = document.getElementById("searchInput");

By storing the location in this variable, I wish to append it to the link responsible for fetching data from the API, in the JavaScript code. When a user inputs a location such as New York and clicks Search, the form action should direct them to page2.html, where the weather data can be displayed.

How can I showcase the weather data on page 2, incorporating the location input from page 1? Despite several attempts, I have not had any success. Below are snippets of the JavaScript code:

let units = 'metric';
let searchMethod = 'q';

let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");

if (searchButton) {
    searchButton.addEventListener('click', () => {
        let searchTerm = searchInput.value;
        if (searchTerm)
            searchWeather(searchTerm);
    });
}

function searchWeather(searchTerm) {
    fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`).then(result => {
        return result.json();
    }).then(result => {
        init(result);
    })
}

function init(resultFromServer){
    let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader');
    let temperatureElement = document.getElementById('temperature');
    let humidityElement = document.getElementById('humidity');
    let windSpeedElement = document.getElementById('windSpeed');
    let cityHeader = document.getElementById('cityHeader');
    let weatherIcon = document.getElementById('documentIconImg');

    weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png';

    let resultDescription = resultFromServer.weather[0].description;
    weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);

    temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '&#176' + " C";
    windSpeedElement.innerHTML = 'Winds at ' + Math.floor(resultFromServer.wind.speed) + ' mph';
    cityHeader.innerHTML = resultFromServer.name;
    humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity + '%';
}

The above JavaScript code is intended to fetch weather data. Subsequently, on page 2, the HTML structure is as follows:

<div id = "weatherContainer">
    <div id = "weatherDescription">
        <h1 id = "cityHeader"></h1>
        <div id= "weatherMain">
            <div id = "temperature"></div>
            <div id = "weatherDescriptionHeader"></div>
            <div><img id = "documentIconImg"></div>
        </div>
        <hr>
        <div id = "windSpeed" class = "bottom-details"></div>
        <div id = "humidity" class = "bottom-details">></div>
    </div>
</div>

I anticipated having the weather data displayed on page 2 within these div elements. Any advice or guidance on how to achieve this would be greatly appreciated. Thank you!

Answer №1

Removing the form from page1 since it doesn't exist in page 2

let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");

if (searchButton) {
    searchButton.addEventListener('click', () => {
        let searchTerm = searchInput.value;
        if (searchTerm)
            searchWeather(searchTerm);
    });
}

Replace with:

let searchTerm = new URLSearchParams(location.search).get('location');
searchWeather(searchTerm);

Explanation:

When the form on page 1 is submitted, it will load page 2 like this:

page2.html?location=xxxx

where xxxx is the value of the <input name='location'...

location.search will be ?location=xxxx

The use of URLSearchParams simplifies handling these values compared to older methods that required splitting and decoding.

Answer №2

To retrieve the current form input from the URL on page2.html, simply submit the form. Here is the code for the form:

<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
    
    <input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
    <button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search">Search</button>

</form>

Before making an ajax call on page2.html, you can extract the 'searchInput' (location) value from the URL like this:

<script>
let params = (new URL(document.location)).searchParams;
var searchInput= params.get('location');
</script>

Now, you have the 'searchInput' parameter to use in your API call and fetch the necessary data.

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

Issue with Rails: Content_For not functioning properly when combined with AJAX or when attempting to rehydrate JavaScript files

Currently, I am utilizing ajax to load all my views, and it's functioning perfectly except for one issue. My view pages that are being loaded are not referencing my JavaScript files. Below is an example of my coffee-script: jQuery(function() { Stri ...

The index.html file is missing from the "out" folder when exporting with NextJs

After completing my Next.js app, I decided to use static exporting in order to host the project on my own hosting platform. Since my app is quite simple, I didn't utilize all of the features that Next.js has to offer. However, when I ran the command n ...

What steps can you take to resolve the issue of FirebaseError: When collection() is expected to be a CollectionReference, DocumentReference, or FirebaseFirestore?

I'm currently working on integrating Firebase with next.js, and I've encountered an error in the console that reads: FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore B ...

Configuring select options using API data

I am currently retrieving my options from an API and have created a Const InputResponse to store the data: const inputResponse = [ { key: 'news', value: "news", datagrid:{ w:2, h:9, x:0, y:0, m ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

What is the most effective method for converting all the keys in a nested array of objects to camel case?

I'm looking to convert all keys of my array of objects into camelCase using TypeScript. Here is the data I have: [ { "Name":"Custom property", "Details":{ "Address":"Huston" ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

Is there an easier way to coordinate CSS other than relying on JS?

It seems like I'm continuously resorting to using JavaScript too frequently for tasks that should ideally be achievable with CSS alone. Let's consider a specific scenario I'm tackling: div.outer { height:{Y}px } div.inner { padding-top:{Y} ...

What is the best way to add borders to table cells that have a non-zero value

I am trying to create a table using a function and it currently looks like this: table { border: 1px solid; } td { width: 30px; height: 30px; text-align: center; } <table> <tr> <td>2</td> <td>0</td> ...

Examine every character in the text to determine if it qualifies as a separator

Can anyone assist me with a task I'm working on? I'm trying to write a function that checks the letters of a string. I attempted to use both a for loop and a foreach loop, but I couldn't get it to work properly :( let input = this.tagsFor ...

Incorporating a lasting element into the _app.js file of Next.js

I am currently experimenting with my first Nextjs app and encountering difficulties when trying to incorporate a persistent sidebar. While looking for solutions, I came across Adam Wathan's article on persistent layouts in Nextjs. However, it appears ...

Toggle the collapse of the navigation bar

I'm having an issue with my navbar collapse in HTML. Currently, I am using the code provided at http://pastebin.com/s92VvJr6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav> <div ...

Provide JSON data on a designated pathway

I'm currently working on setting up a basic API that will respond with JSON data when accessed at the path /json The goal is to send back the object {"message": "Hello json"} in JSON format whenever a GET request is made to the /j ...

The absolute positioned div on the same level is impacted by negative margin

I am facing an issue with styling elements in my HTML code. I have a div with the ID of #left that is absolutely positioned, along with two other divs on the right side. Strangely, when I apply margin to the #top div on the right side, it also affects the ...

I'm having trouble accessing this link because it seems to be embedded within a php script. Is there a different method I can

<?php if ($user=='admin'){ echo '<br> <input type="button" value="Modify Users" onclick="window.location.href='modifyusers.php'"><br>'; } ?> This script is the one. It functions properly except for ...

Explore jQuery UI Tabs with remote content, highlighting the active tab with a link to the current page

Back in earlier versions of jQuery UI (<=1.8), when loading tabs, the link for a remote tab would be replaced with a local link. This allowed users to middle-click (or open in new browser tab) on the tab, and it would link back to the current page with ...

Adjusting the background element of a fullpage.js layout during resizing and customization

Is there a way to make the background image responsive on a fullpage.js page, specifically for mobile and tablet devices? How can I ensure that a specific part of the image stays at the center of the page when resizing? For instance, in the provided imag ...

The "Next" button fails to function after a replay has been completed

I created a small quiz app to practice my JS skills. Everything seems to be working fine, except for one issue - when I click on replay, the quiz box shows up but the 'Next' button stops functioning. There are no console errors and I'm strug ...

receiving onPaste or onChange events within a component that generates input fields

My goal is to achieve the following functionality: <MyTextInput onChange={console.log("Change")} /> This particular component serves as a container for <input type="text" /> without triggering any action when text is typed (the purpose of usi ...

The error message "Cannot read property 'properties' of undefined" is being thrown by the leaflet-search plugin

I attempted to implement the leaflet-search feature using a Vue-cli component. However, when I initiate a search, I encounter the following error message specifically related to the leaflet search function: Uncaught TypeError: Cannot read property &apo ...