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? 😉
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
PUTandGETaction method.web.xml
testServlet.java
and main part NewFile.jsp
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 isPOSTdefault encryption is this.POST.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 withGETyou should addxmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded");code for encryption and remove theurlparameter fromsend()method.function eliminaUtente(id) {
Note: I try this code in firefox, i create xmlHttpRequest object. For all browser(include IE6) sure you know use: