Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9263575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T13:37:08+00:00 2026-06-18T13:37:08+00:00

I have this ajax call from a javascript file and I want to pass

  • 0

I have this ajax call from a javascript file and I want to pass as a parameter the id of the user that I want to delete:

function eliminaUtente(id,nome){
if (confirm("Sei sicuro di voler eliminare l'utente "
    + nome
    + "?")) {
var xmlHttp2 = new XMLHttpRequest();
xmlHttp2.open("POST", "EliminaUtente", 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("utente eliminato!");
        } else {
            alert("An error occurred while communicating with server.");
        }
    }
};

}
}

in the correspondant Servlet called EliminaUtente i have this code:

  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 utente where idutente=" + id;
    System.out.println(query);
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        Connection con = DriverManager
                .getConnection("jdbc:mysql://localhost/Spinning?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 can’t understand where is the problem…can you help me please? 😉

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T13:37:09+00:00Added an answer on June 18, 2026 at 1:37 pm

    I try your code and change a little bit i want to explain what did i and what i learn from it.I read some source. First i read XMLHttpRequest object and onreadyState event.
    I implement your example both PUT and GET action method.

    web.xml

    <?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>
    

    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 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>
    </head>
    <body>
        <input type="button" value="Submit" onclick="eliminaUtente('1')" width="100%" />
    </body>
    <script language="javascript" type="text/javascript">
        function eliminaUtente(id) {
    
            var xmlHttp = new XMLHttpRequest();
            var url = "test/NewFile.jsp?id=" + id;
            xmlHttp.open("POST", url, true);
            xmlHttp.send(url);
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    alert("utente eliminato!");
                } else {
                    alert("An error occurred while communicating with server.");
                }
            };
        }
    </script>
    </html>
    

    with this way i write the parameter 1(i hardcode it in jsp file method invoke) and write it to console, the first thing in here the difference your code and mine i remove the xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); because if the method type is POST default encryption is this.

    enctype = content-type [CI]
    This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file".
    
    • So no need to enctype default is OK for POST.
    • And this is open method signature open(method, url, async, user, password) here async is the parameter which means if it is false don’t wait a response from server implement the other line when response is come it will run. If it is true wait until response is come. Actually i try bot of them and it is worked.
    • Lastly i try it with GET. If you want use it with GET you should add xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); code for encryption and remove the url parameter from send() method.

      function eliminaUtente(id) {

          var xmlHttp = new XMLHttpRequest();
          var url = "test/NewFile.jsp?id=" + id;
          xmlHttp.open("GET", url, true);
              xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded");
          xmlHttp.send();
          xmlHttp.onreadystatechange = function() {
              if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                  alert("utente eliminato!");
              } else {
                  alert("An error occurred while communicating with server.");
              }
          };
      } 
      

    Note: I try this code in firefox, i create xmlHttpRequest object. For all browser(include IE6) sure you know use:

    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");
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a javascript file and I want to call a function on the
I have a web service that returns this string via the jQuery $.ajax() call
A situation I ran across this week: we have a jQuery Ajax call that
I'm having problems trying to call a Javascript function from an enqueued javascript file
I have this function handling ajax calls: function ajaxPost (divNode, parameters, file) { if
If I want to call a server function from JavaScript to retrieve a name
Currently, I have a Javascript file (running on the client) that I call a
On my main page I have this jquery code which does an ajax call
I have a jQuery AJAX call with type:'GET' like this: $.ajax({type:'GET',url:'/createUser',data:userId=12345&userName=test, success:function(data){ alert('successful'); }
I have the following ajax call var prev_sibling = $(this).prev().attr(value); var next_sibling = $(this).next().attr(value);

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.