Invoking servlet using Ajax

I have created a JSP file with Javascript functions and AJAX calls to invoke a servlet (ReadprojectInfo).

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function displayProject()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    
    xmlhttp.open("GET","ReadProjectsInfo",true);
    xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange= function ()
    {
        if (xmlhttp.readyState==4)
        {
        if (xmlhttp.status == 200)
        {
        var time = xmlhttp.responseText;
        //alert(time);
        document.getElementById("center").innerHTML=xmlhttp.responseText;
        }
        }
    }
    xmlhttp.send(); 

//document.getElementById("center").innerHTML=Date();
}

</script>


<link rel="stylesheet" type="text/css" href="css/start.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learning CSS</title>
</head>
    <body>
    <div id ="headerLink" class="HeaderLink" >
        <button id="adminLink" class="AdminLink" href='DNE.jsp'>Home</button></div>
        <button id="projectButton" class="ProjectButton"  onclick="displayProject()" >Projects</button>
    </div>
    
        <div id="center" class ="Center"><p>Click Project</p></div>
    </body>
</html>

The code for the servlet is shown below:

package excelExchange;

import java.io.IOException;
import java.io.PrintWriter;

import javaFiles.Dog;
import javaFiles.Person;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ReadProjectsInfo {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
    doGet(request, response);
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException{
        //String var1= request.getParameter("var");
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.write("Hello from servlet !!");
        out.println("Hello");
        
    }

}

This is what my web.xml configuration looks like:

    <servlet>
    <servlet-name>projectInfo</servlet-name>
    <servlet-class>excelExchange.ReadProjectsInfo</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>projectInfo</servlet-name>
    <url-pattern>/ReadProjectsInfo</url-pattern>
  </servlet-mapping>

Upon clicking the "Project" button, nothing seems to happen. I would appreciate any assistance in resolving this issue.

Answer №1

Remove the following lines:

xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
and also remove: if (xmlhttp.status == 200) { ... to test if it resolves the issue

Answer №2

To make your code work, ensure that you are extending the HttpServlet in your class as shown below:

public class ReadProjectsInfo extend HttpServlet{
      ...
}

I suggest removing this line from your code:

xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

By doing so, your code should function properly.

Answer №3

Here is the full URL of the servlet class to try out:

xmlhttp.open("GET","http://localhost:8080/excelExchange/ReadProjectsInfo",true);

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

The Highcharts plugin is currently not able to render the data

I have been extracting data from the mtgox api and after analyzing my console, I can confirm that all the data is being properly delivered to my chart. Nevertheless, I am facing difficulties in getting the data to actually display on my chart. Any assist ...

Attaching this to the event listener in React JS

After delving into a beginner's guide on React JS, I encountered a slight hiccup. The issue revolves around a simple problem within the button element; specifically, an event handler that requires passing an argument. This handler serves the purpose o ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Solving the issue of jQuery setInterval blocking asynchronous ajax requests

Upon submitting a form, the utilsSubmit function is called. This function sets variables and initiates another function to read a file. If the file does not exist, it will display "Connecting to device...". Once the file is found, the content should be dis ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...

Unable to persist information in Firebase's real-time database

I'm having trouble saving data to my firebase database. Although I don't see any errors on the site, the data in firebase remains null and doesn't change no matter what I do. Here is the code snippet. HTML <html> <head> ...

npm ERROR: Unable to install the package named "<packageName>" because it conflicts with an existing package of the same name

Currently, I am attempting to incorporate the jsonfile package into my project. However, I am encountering a couple of errors: An issue arises when attempting to install a package with the same name as another package within the same directory. (Despite ...

Modifying the calendar from a 7-day week to a 5-day week

I am currently in the process of developing a 7-day calendar (Sunday to Saturday) which is functioning well. However, I am interested in adding an option to switch it to a 5-day calendar (Monday to Friday). I was wondering if there is a way to modify the e ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Cannot POST to /profiles/flash/. GET request is also disallowed for /profiles/flash/

Here I am attempting to incorporate a follow toggle button in a Django template using Django and jQuery AJAX, but encountering an error. Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/ I'm unsure where I might be goi ...

Using PHP and JavaScript to keep track of file modifications

Being a beginner in PHP and Javascript, I recently created a basic Clock application using Javascript which worked out successfully. Now, I have a file that will automatically change its content. For example, it might look something like this: "12h15: eat ...

Scope isolation prevents variables from being accessed in higher levels of the scope chain

In my search for answers, I came across some similar questions on SO: Isolate scope variable is undefined unable to access rootscope var in directive scope However, my question presents a unique scenario. I am facing an issue with a directive that has a ...

Guide on how to clear and upload personalized information to Stormpath

After receiving JSON data from my client, I am looking to store it in Stormpath's custom data using node.js with express.js: I have set up a basic post route: app.post('/post', stormpath.loginRequired, function(req, res){ var data = req.b ...

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...

Angular does not recognize the function element.sortable

I'm attempting to utilize ui.sortable in order to create a sortable list. Despite following the instructions provided at https://github.com/angular-ui/ui-sortable, I am still encountering an issue and receiving the following error message: TypeError: ...

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

Randomly switch out the wordpress header image at designated intervals

I have a custom header image on my website that displays 6 random images each time the site is visited. I am attempting to change this group of images while the user is browsing my site. Here is the code I am using: function show_banner(){ document.ge ...

Why is React App showing up twice on the webpage?

After successfully creating a React app based on Free Code Camp's Drum Machine project that passed all tests on Code Pen, I encountered an issue when transferring the code to Visual Studio. Surprisingly, the app now fails one test (#6) even though it ...