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

What steps should be taken to showcase user input in a newly created task?

I am struggling to display the user input list, but it seems like I might be missing something here: const createTask = () => { const id = createId() const task = elements.input.value; const date = elements.cal.value; if(!task && ...

What are the steps to effectively utilize my search bar alongside Google Custom Search?

Here is the HTML code for my form: <form action="#" class="searh-holder"> <input name="se" id="se" type="text" class="search" placeholder="Search.." value="" /> <button class="search-submit" id="submit_btn"><i class="fa fa-sea ...

Experiencing difficulties with using the javascript alternative to jQuery.ajax()

Here is a JavaScript Object: const data = { name: "John", age: 30, } const jsonData = JSON.stringify(data); The AJAX Request below successfully passes the data: $(function(){ $.ajax({ url:'two.php', ty ...

Troubleshooting issues with environment variables in Next.js version 12.2.2

I tried following the steps outlined in the official documentation, but I'm encountering an issue. Here is what I did: next.config.js const nextConfig = { reactStrictMode: true, swcMinify: true, env : { MORALIS_ID: 'moralisId', ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...

Transform the Dataset<Row> in the Dataframe to JSON format, specifically targeting certain columns. Then, reverse the process by converting the JSON string back into a Dataframe

I have a dataframe and need to make a call to a Rest API for each record. Assuming the Dataframe has the following structure: |----|-------------|-----|---------| |UUID|PID |DEVID|FIRSTNAME| |----|-------------|-----|---------| |1111|12345678910 ...

Unable to set a value of type 'String?' to a variable of type 'String?.Type'

Having trouble resolving this error: Here is the code snippet causing it: func setInfo(json: JSON) { self.name = json["name"].string self.email = json["email"].string let image = json["picture"].dictionary let imageData = image?["data"]? ...

Tips for implementing AJAX to incorporate a form into your website:

I've created a new.html.slim page containing a form _form.html.slim = form_for (@text_input), remote: true do |f| .field = f.text_field :title ... new.html.slim h1 new text_input == render 'form' ... a.btn type='button&ap ...

What strategies can be implemented to decrease the initial loading duration of a YouTube iframe video?

What are some techniques we can use to decrease iframe loading time? Is it possible to implement lazy loading for YouTube iframe videos? I experimented with initially hiding the iframe and displaying an image instead. However, when the user clicks, it req ...

Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping. I tried solving it with margins and paddings but believe there must be a simpl ...

Utilizing Cucumber for passing arguments between two Java methods

I am new to using Cucumber and I'm struggling to grasp how to transfer data between different methods. While I have seen examples of using data tables in features, my specific issue arises when I try to pass a Map within an ArrayList from one method t ...

Why is the PHP response always 0 even though AJAX JSON data is being sent correctly during Wordpress plugin development?

There seems to be a simple issue here that I'm missing. The data is being sent correctly according to Firebug in the NET tab (NET tab-> Post -> Parameters). However, the PHP function does not even echo simple text. This is the PHP code: add_ac ...

Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug ...

Utilizing AngularJS to dynamically inject HTML content into $scope

In my possession are the following files: index.html //includes instructions for passing arguments to the btnClick function in app.js <div ng-bind-html="currentDisplay"></div> app.js app.factory('oneFac', function ($http){ var htm ...

Show the complete JSON data on the webpage

I'm trying to remember how to display all the data within an ng-repeat using $index, but it's not coming back to me. Usually, when I've done this in the past, it just displays everything in the HTML of the page like: array: [ { animal: "dog ...

Unable to display MongoDB collection in React application

I've been working on showcasing my projects using React and Meteor. I have two collections, Resolutions and Projects. The issue I'm facing is that while I can successfully display the Resolution collection on the frontend, I'm struggling to ...

Creating a SVG polygon using an array of points in JavaScript

Consider the following array containing points: arr = [ [ 0,0 ], [ 50,50 ], [ 25,25 ], ]; I would like to create an SVG polygon using this array. Initially, I thought the code below would work, but it doesn't: <polygo ...

Transferring PHP session variables from jQuery and Ajax to the PHP gratitude page

I've been mulling over this puzzle for quite some time now. My approach involves utilizing jQuery AJAX POST method to transmit form data using session variables from home.php to thankyou.php. Subsequently, the user is redirected (window.location.href ...

Execute a JavaScript function on the server every 5 minutes

I'm seeking guidance on a situation that has prevented me from finding a solution. I have a basic JS script that uses AJAX to fetch data from an API and save it. My goal is to move this script to a server and execute it every 5 minutes, not on the cl ...