Performing an XMLHttpRequest in the same JSP file using Javascript

I am working on a JSP file that contains three dropdown boxes labeled "countries", "regions", and "cities". My goal is to populate the regions based on the selected country, and the cities based on the selected region. I have managed to achieve this using Java and Javascript parameters on the same page, however, every click on the dropdown lists results in the page refreshing, which I want to avoid.

The data for "countries", "regions", and "cities" is retrieved from JSON data within the Java code "<%...%>" on the same page.

I attempted to utilize AJAX for this process but was unable to find a functional example for passing parameters. If necessary, I am willing to split the page into smaller JSP files such as "countries.jsp", "regions.jsp", and "cities.jsp", but I need assistance with passing parameters between them. I am seeking guidance and practical examples of implementing JSP Ajax with parameters, without relying on jQuery. My aim is to accomplish this using pure JS.

I welcome your suggestions and any examples you may have for implementing JSP Ajax with parameters.

Answer №1

To start off, consider dividing the content into regions.jsp and cities.jsp (assuming countries remain consistent). Then, establish a function that captures the selected values from countries using the OnChange event and transfers them to your regions.jsp. Here's an example:

<select name-"countries" id-"countries" OnChange="getRegions();"><option> ...</option></selct>

Subsequently, incorporate JavaScript to facilitate the Ajax call, without the need for jQuery.

            var requestObj = false;

            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                requestObj = new ActiveXObject("Microsoft.XMLHTTP");
            }

            function getRegions()
            {
                var select = document.getElementById('countries');
                var currentCountry = select.options[select.selectedIndex]; 
                if (requestObj) {
                    requestObj.open("GET", "/ajax/regions.jsp?country=" + currentCountry);
                    requestObj.onreadystatechange = function ()
                    {
                        if (requestObj.readyState == 4 && requestObj.status == 200) {
                               var options = parseJSON(requestObj.responseText);
                             for( var i=0; i<options.length; i++) { 
                                  document.getElementById("regions").appendChild("<option value='" + options['id'] + "'>" + options['text'] + "</option>");
                             }
                        }
                    }
                    requestObj.send(null);
                }
            }

Quite nostalgic working without jQuery, right? Does this explanation clarify things?

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

Issues with React Native imports not functioning properly following recent upgrade

Hey there, I’ve been tasked with updating an old React-Native iOS project from version 0.25.1 to 0.48.0. However, I’m encountering several compiler issues and struggling to navigate through the code updates. The project includes an index.ios.js file s ...

Utilizing Jackson to deserialize a serialized final class

Here is a value holder class for users: package entities; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.i ...

What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to a ...

Transferring information from Python to JavaScript and receiving a response

Currently, I am working on sending JS data, particularly images that have been collected by a Python file. My goal is to send these images from Python to JS so that JS can perform a certain action (which I will be coding). Afterwards, the final result ne ...

Nuxt - Dynamically manage routes while utilizing server-side rendering functionality

Hello! I have a question for you: I have: a Nuxt app set up with target: 'server' in the nuxt.config.js an API that provides me with a template associated with a given path (for example, /person/maxime will return template: PersonsSingle) a vue ...

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Leveraging the import statement within lib.d.ts to enhance Intellisense functionality in Visual Studio Code

Looking to streamline my JavaScript project by utilizing custom global variables and harnessing the power of VSCode intellisense for auto completion. Here's what I'm aiming for: See example of auto completion for 'lol' After some sear ...

The data from the Ajax request failed to display in the table

JavaScript Code

$(function (){ $.ajax({ type : 'GET', url : 'order/orders.json', dataType : 'JSON', success: function(data) { /*var trHTML = ''; $.each(orders, function (i, item) { ...

Using VueJS to perform a filtering operation on the JSON data when a button is clicked

I need to implement a filter function for my fetched json data using buttons. When a button is clicked, only the data (in this case book names) that match the clicked button should be displayed while hiding the others until another button is clicked. The ...

Tips for formatting result data when using FullCalendar's eventSources URL

I am looking to retrieve my event data for fullcalendar from a separate URL. I have been following the method mentioned here: https://fullcalendar.io/docs/eventSources $('#calendar').fullCalendar({ eventSources: [ '/feed1.php' ...

Using PHP's mysqli function to generate a JSON array

Currently, I am in the process of learning php/mysql to enhance a website that I am constructing. Initially, everything was functioning as intended but there were numerous vulnerabilities and security flaws with minimal error handling mechanisms. To addres ...

troubleshooting problems with jquery ajax and setInterval

$(document).ready(function() { function refreshBids() { var element = $("#biddingDiv"); element.load("bids.php?id=<?=$userId;?>&init=1&auctionid=<?=$auctionId;?>"+(new Date()).getTime()); } refreshBids(); setI ...

What strategies can be employed to reduce the need for numerous if-else statements in my JavaScript code?

In my input form, users have the ability to make edits. I need to send only the data that has been changed by the user. Currently, I am repeating the same lines of code multiple times to compare and determine what data needs to be sent. Is there a more e ...

What are the steps for incorporating React into an existing website?

Currently, I have a website built with Express and I am looking to incorporate React into specific pages. What is the most effective method to integrate it while utilizing all the resources available through create-react-app? I understand that I can manua ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Payload bytes do not match the expected byte values

I am facing an issue where the image data sent by the user is getting saved on the server in a corrupt state. Here is the structure of my setup: - api . index.js - methods . users.js (I have omitted unrelated files) There is a server.js outside ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Tips for keeping the options menu visible even when the video is paused

As I was creating my own customized Video player, I encountered an issue where I wanted the options bar/menu to disappear when the user became inactive. While I have managed to achieve this functionality, I still require the option bar to remain visible ...