The current status of the XmlHttpRequest object is 0

In my JavaScript file, I have an AJAX call where I need to pass the user's ID as a parameter for deletion:

function deleteUser(id, name){
if (confirm("Are you sure you want to delete user "
    + name
    + "?")) {
var xmlHttp2 = new XMLHttpRequest();
xmlHttp2.open("POST", "DeleteUser", true);
xmlHttp2.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded");
var params2 = "id=" + id;
xmlHttp2.send(params2);
xmlHttp2.onreadystatechange = function() {
    if (xmlHttp2.readyState == 4) 
    {
                    alert(xmlHttp2.status);  <-----------this prints always 0!
        if (xmlHttp2.status == 200) //
        {
            alert("User deleted!");
        } else {
            alert("An error occurred while communicating with server.");
        }
    }
};

} }

Within the corresponding servlet named DeleteUser, the following code is implemented:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String id = request.getParameter("id");
    System.out.println(id);
    String query = "delete from user where user_id=" + id;
    System.out.println(query);
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Connection con = DriverManager
                .getConnection("jdbc:mysql://localhost/Database?user=root");
        PreparedStatement prest = con.prepareStatement(query);
        prest.executeUpdate();

        response.setContentType("text/plain");
        PrintWriter ajaxWriter = response.getWriter();
        ajaxWriter.print("ok");
        ajaxWriter.flush();
        ajaxWriter.close();

        con.close();
    } catch (Exception e) {
        e.printStackTrace();
        response.setContentType("text/plain");
        PrintWriter ajaxWriter = response.getWriter();
        ajaxWriter.print("ko");
        ajaxWriter.flush();
        ajaxWriter.close();
    }

}

I'm facing some issues and can't seem to figure out what's wrong. Can someone assist me with this problem? ;)

Answer №1

I experimented with your code and made some modifications to explain what I did and what I learned from it. I delved into sources about the XMLHttpRequest object and the onreadystatechange event. I successfully implemented both the PUT and GET action methods in your example.

In the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <servlet>
        <servlet-name>testServlet</servlet-name>
        <servlet-class>com.test.testServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>testServlet</servlet-name>
        <url-pattern>/test/*</url-pattern>
    </servlet-mapping>

</web-app>

In testServlet.java:

package com.test;

import java.io.IOException;

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

public class testServlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        /*super.doPost(req, resp);*/
        String strId = req.getParameter("id");
        System.out.println(strId);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        //super.doGet(req, resp);
        String strId = req.getParameter("id");
        System.out.println(strId);
    }
}

and the main part NewFile.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
... (truncated for brevity) ...

Overall, while working on this code, I discovered that specifying the encryption type in the POST method as

application/x-www-form-urlencoded
is unnecessary, as it defaults to that value. Moreover, understanding the significance of the async parameter in the open() method allowed me to experiment with different responses from the server.

... (truncated for brevity) ...

Answer №2

spelling mistake?

alert(xmlHttp2.status); <-----------this consistently displays 0! It now says "2'

Answer №3

The issue arose when I needed to insert the value "false" in the following line:

xmlHttp2.open("POST", "EliminaUtente", FALSE);

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

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

Ensure that cookies intended for cross-site contexts are marked as Secure to enable their setting across different sites

When using nookies in Next.js on browsers with Chromium, an error is occurring as mentioned in the title and the cookie is not being saved properly. The website is securely hosted with SSL/HTTPS. Have already attempted: - sameSite = None - secure = tru ...

Building a card carousel component in Vue JS

Struggling with creating a unique card slider using Vue JS? After exploring npm packages like Vue Carousel 3D and Vue Slick, I haven't found the ideal slider for my project. My specific card slider setup is showcased below: https://i.sstatic.net/GiNc ...

There has been an unexpected error: TypeError - The function Item.replace does not exist in the autoComplete plugin

I am currently using the jQuery plugin autoComplete from , and I encountered an error while trying to implement their ajax request. The error message displayed is: item.replace is not a function at object.renderItem $.fn.autoComplete.defaults = { ...

divide a lengthy string into several dynamic divisions

I am attempting to divide a lengthy string into multiple dynamic divs once the height of the div reaches a certain limit. Below is the code that I believed would achieve this: $(document).ready(function () { var arr = longishstring.split(' ' ...

What is the process of shifting an object to the initial chunk and transferring the oldest item to a new chunk using JavaScript?

I need to update an array of data in Vue.js every time new data is received from Pusher. Reactivity is important to me, as I want to avoid reloading all the data from the server whenever an event is triggered. Here's the specific condition I need to ...

Updating a slider based on the values of two other sliders can be achieved by implementing a

I am working on a project that involves three input sliders. I need the third slider to display the product of the values from the first two sliders. Additionally, I want the value of the third slider to update dynamically whenever the values of the first ...

What is the best way to change a double-quoted integer into an integer?

Can anyone help me convert this to an integer? "'10'" Appreciate any assistance. ...

What is the process for retrieving information from a database in Django when the submit button is clicked?

Is there a way to retrieve database objects in HTML only when the submit button is clicked, instead of loading them automatically on page load? Currently, I have an AJAX script running on a form that displays text entered in a textbox onto the HTML when th ...

Express.js does not display console.log messages while routing

Just starting to explore Express and its middleware functions. var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.param ...

Guide on building a library of React Native components

Can you provide guidance on building a React Native component library? I am looking to incorporate it with this command: npm install ...

The build process of Android Studio/Gradle encounters an error where a Parcelable class is reported as "missing" in a Java file

I recently encountered an issue with my service that uses multiple AIDL files. I added a custom object to one of the AIDL files and included its corresponding .aidl file with the parcelable declaration. However, during the build process, I received an erro ...

Tips for preventing window.location from becoming relative to the file

Despite my best efforts, I couldn't figure out why this issue was occurring or how to resolve it. Here is the code in question: window.location.href=("www.google.com"); The intended functionality of this code is to redirect to google.com, but inst ...

What is the best way to invoke an AngularJS function from within a regular JavaScript function

Exploring the world of AngularJS for the first time and seeking guidance on calling a function to retrieve items in different controllers. Incorporating CSV file loading using AngularJS. var Mymodule = angular.module('Mymodule', []); Mymodule.f ...

Delete any excess space that is currently covered by an image

While trying to implement a tab menu on my website by following this guide, I encountered an issue. The content box appears to be too long and is overlapping with the image. Can someone advise me on how to remove this extra space? For reference, you can v ...

Java - Sending Data to PHP but Not Receiving Any Parameters

Currently, I am facing an issue while attempting to send an IP address from a Java program to a PHP file hosted online. The problem lies in the fact that the PHP file is not properly receiving the IP address. Below is the Java code snippet: try { ...

The aggregation in Java using MongoTemplate does not return the group value as expected

I am facing an issue in my Spring Controller where I am struggling to retrieve the correct result of a MongoDB aggregation using MongoTemplate. Here is the code snippet from my Controller class: Aggregation aggregation = Aggregation.newAggregation( ...

Removing files from Dropzone.js uploaded form

For my project, I am utilizing dropzone.js and faced with the task of deleting files from the plugin upload zone (rather than the server) after they have been uploaded. My goal is to revert back to displaying the "Drop files here or click to upload" text o ...

What is the most effective way to extract an array of #tags from a given string using parsing methods?

I have a string that looks something like "#tag1 #tag2 #tag3 not_tag1 not_tag2 #tag4" (note the varying number of spaces between tag2 and tag4). I'm trying to extract just the tag1, tag2, and so on from this string. These tags are simil ...

Encountered an internal error while trying to access the "Compute launch button tooltip" feature in Eclipse Kepler. This issue arises due to a java.lang.IllegalArgumentException after

Everything was working smoothly with my projects in Eclipse Kepler until I decided to download TestNG. Suddenly, I found myself unable to click on the Run button for my code. Every time I attempted to run or even hovered over the run button, an error messa ...