Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need some assistance in fixing this issue.

Here is the Ajax code snippet-

 <script language="javascript" type="text/javascript">  
  var xmlHttp  
  var xmlHttp

  function showSubCategory(str){
      if (typeof XMLHttpRequest != "undefined"){
      xmlHttp= new XMLHttpRequest();
      }
      else if (window.ActiveXObject){
      xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
      }
      if (xmlHttp==null){
      alert("Browser does not support XMLHTTP Request")
      return;
      } 
      var url="jsp/subcategory.jsp";
      url +="?count=" +str;
      xmlHttp.onreadystatechange = stateChange1;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
      }

      function stateChange1(){   
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){   
      document.getElementById("subcat").innerHTML=xmlHttp.responseText   
      }   
      } 

This is the main jsp page that contains the dropdown lists--

 <table>
     <tr>
<td align="right" width="10%">Category </td>
<td>
   <select id='category' name="adv.categoryNo" onchange="showSubCategory(this.value)">  
       <option >Select the Category</option>  
     <%
Class.forName("com.mysql.jdbc.Driver").newInstance();  
Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","user","pwd");  
Statement stmt1 = con1.createStatement();  
ResultSet rs1 = stmt1.executeQuery("Select * from categories");
while(rs1.next()){
    %>
    <option value="<%=rs1.getString(2)%>"><%=rs1.getString(2)%></option>  
    <%
}
    %>
    </select>                                  
     </td>
    </tr>

   Second drop down list 


    <tr>
      <td align="right" width="10%">Subcategory <span class="mandatory">*</span>: </td>
       <td>
         <div id='subcategory'>  
         <select id='subcat'  name='subcategory'>  
         <option >Select the Subcategory</option>  
         </select>  
         </div>
    </td>
    </tr>

Below is the subcategory jsp file called by Ajax.

<%@page import="java.sql.*"%>
 <%
  String category=request.getParameter("count");  
   String buffer="<select name='adv.subCategoryNo'><option >Select the Subcategory</option>";  
 try{
  Class.forName("com.mysql.jdbc.Driver").newInstance();  
  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","user","pwd");  
  Statement stmt = con.createStatement();  
  ResultSet rs = stmt.executeQuery("Select * from subcategories where     categoryName='"+category+"' ");  
   while(rs.next()){
   buffer=buffer+"<option value='"+rs.getString(3)+"'>"+rs.getString(3)+"</option>";  
   }  
    buffer=buffer+"</select>";  
    response.getWriter().println(buffer); 
    }
   catch(Exception e){
    System.out.println(e);
    }
   %>

Oddly, changing the parameter in the following Ajax function from "subcat" to "subcategory", which is the ID of the div containing the second dropdown list, allows it to work properly in IE and other browsers.

function stateChange1(){   
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){   
      document.getElementById("subcat").innerHTML=xmlHttp.responseText   
      } 

If I go with the above solution, I face challenges with JavaScript form validation for the Subcategory select box using the following JS code.

 function madeSelectionCity(){
  var subcat = document.getElementById('subcat');
if(subcat.value == "Select the City name"){
    alert("Please select a subcategory first");
    subcat.focus();
    return false;
}else{
    return true;
}
 }

I hope I have explained my question clearly. Please let me know if you need any further clarification. Thank you.

Answer №1

Revise the following line of code (found in subcategory.jsp called by ajax):

 String buffer="<select name='adv.subCategoryNo'><option >Select the Subcategory</option>";  

to:

 String buffer="<select id='subcat' name='adv.subCategoryNo'><option >Select the Subcategory</option>";  

Also include this line of code (in subcategory.jsp called by ajax):

response.setContentType("text/html");

For the webpage (main page), the HTML should be:

<div id='subcategory'>
 </div>

The AJAX (main page) code should be:

function stateChange1(){   
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){   
      document.getElementById("subcategory").innerHTML=xmlHttp.responseText   
      } 

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

Encountering issues with installing @vue/cli on Linux Ubuntu

Currently facing an issue while attempting to install the Vue CLI on Ubuntu (WSL). After running both yarn add global @vue/cli and npm install @vue/cli --global, it seems like the commands were successful. However, upon checking the version using vue --v ...

JavaScript Function or Object: A Guide to Returning

Currently, my code is functioning as expected. However, I am curious if there is a way to modify my function so that it can be declared as an object even when no parameters are provided. Below is the mixin function in question: import Page from "@/models ...

Is it possible to store a JWT token in local storage when working with Next.js?

We are considering using Next.js for our application, with a focus on client-side rendering for data fetching. The API we will be interacting with is external and requires authentication to access specific user dashboard content. While the homepage will ...

Close specific child python processes as needed, triggered by a jQuery event

Having trouble managing child processes independently without affecting the main parent process in a web client using jQuery? Look no further. Here's my scenario: I've got a Flask server hosting a basic webpage with a button. Clicking the button ...

Sending an array to Ajax

public List<double> GoogleGeoCode(string address) { address = "Stockholm"; string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address="; dynamic googleResults = new Uri(url + ad ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes. To gather this information, individuals need to indicate whether they have made a purchase. I ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

The responsiveness of the bootstrap 5 dropdown <ul> container is lacking and is exceeding its designated width

I am encountering an issue where the sub menu container is not responsive and is extending beyond its designated container. Below is the code I used, which was sourced from the official Bootstrap website: <li class="nav-item dropdown"> ...

What is it about this JavaScript code that IE8 seems to have a problem with?

Encountered an error in IE8 that has been causing trouble for me SCRIPT65535: Unexpected call to method or property access. load-scripts.php, line 4 character 25690 After removing a .js file from the code, the error disappeared. By commenting out f ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

Numeric value along with two characters following the decimal place

Imagine I have this number: 25297710.1088 My goal is to add spaces between the groups of digits and keep only two decimal places, like this: 25 297 710.10 I tried using the following code snippet: $(td).text().reverse().replace(/((?:\d{2})&bso ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

Is there a way to update my profile picture without having to constantly refresh the page after uploading it?

Here is the code for my profile page. I am considering using a callback along with another useEffect function, but I'm unsure. Please help me in finding a solution. For now, let's ignore all the code related to deleting, saving, and handling ingr ...

The excessive use of Selenium Webdriver for loops results in multiple browser windows being opened simultaneously, without allowing sufficient time for the

Is there a way to modify this code so that it doesn't open 150 browsers to google.com simultaneously? How can I make the loop wait until one browser finishes before opening another instance of google? const { Builder, By, Key, until } = require(& ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

Comparing document.getElementById and the jQuery $() function

Is this: var contents = document.getElementById('contents'); The equivalent to this: var contents = $('#contents'); Considering that jQuery is present? ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

Leveraging Parameters from URL in Javascript

I'm facing an issue with my area shape, the href="/kosmetikstudios/deutschland/Bayern" tag seems to be causing a problem. I want to utilize the parameter "Bayern" (which is the last parameter in the URL). I need this to be dynamic. Below is my JavaS ...

Navigate to a new tab with a parameter in AngularJS

Is there a way to open a new tab using state.go with parameters? This is the state configuration: .state("view", { url: "/view", templateUrl: 'app/components/view/view.html', controller: 'viewController', params: { ...