AJAX open does not accept Servlet - javascript

I am currently making a small program using AJAX. I want to send a JSON String to a Servlet, but it doesn't work. In my browser I get the error "Uncaught TypeError: Cannot read property 'open' of undefined"
I'm guessing that this means, that it can't find the Servlet in the following line:
xmlHttp.open("POST", "../JSONServlet", true);
However, I have made similar programs before and never had this problem, so I don't know what to do to make it work.
My html and js files are in Web Pages/ex06 and my Servlet is in Source Packages/servlets/JSONServlet, however I've tried moving it somewhere else (even though I have made programs that worked like this), but it didn't help.
This is the html and javascript:
var xmlHttp;
window.onload = initAjax();
function initAjax() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE6 or older
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (ex) { // noch ältere MS Produkte
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (ex) {
}
}
}
}
function doJSON1() {
var car = new Car("Mercedes", "SLK", 2012); // car erstellen
var carAsJSON = JSON.stringify(car); // json-String machen
alert("Car object as JSON:\n " + carAsJSON);
xmlHttp.open("POST", "../JSONServlet", true); // here is the problem
xmlHttp.onreadystatechange = handleObjectRequest;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON); // json-String senden
}
function handleObjectRequest() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
jsontext = xmlHttp.responseText;
alert(jsontext);
var benz = JSON.parse(jsontext);
var output = benz.brand + " " + benz.model;
document.getElementById("serverResponse").innerHTML = output;
}else{
alert("nope");
}
}else{
alert("...");
}
alert("state change");
}
function Car(brand, model, year, color) {
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
}
<input type="button" value="JSON-Object senden&empfangen" onclick="doJSON1();"/>
This is the method in my Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStreamReader isr = new InputStreamReader(request.getInputStream());
try {
Gson gson = new Gson();
// auto aus request erstellen
Car car = gson.fromJson(isr, Car.class);
// anderes auto schreiben
Car car2 = new Car("audi", "tt", 2014);
gson.toJson(car2, out);
} catch (JsonSyntaxException e) {
Gson gson = new Gson();
String[] winter = gson.fromJson(isr, String[].class);
String[] summer = {"Jun", "Jul", "Aug"};
out.println(gson.toJson(summer));
}
out.flush();
out.close();
}
My Car class is a simple data class with getters and setters, a default constructor, a custom constructor, and a toString.

You need to have an instance of the XMLHttpRequest() to use the open() method, so add the following line of code:
var xmlHttp = new XMLHttpRequest();
Before you use the open() method like so:
xmlHttp.open("POST", "../JSONServlet", true);
EDIT: - You also have a typo as pointed out by #james before i did, in you're initAjax function you have a variable xmlhttp were as you're global variable is xmlHttp , both are not the same.

Related

Troubleshooting AJAX XMLHTTP object creation

Troubleshooting this function and having trouble finding an error with it as the ajax stuff is all copy-pasted from a guide I'm following:
function updateStuff() {
// Data validation for a text var called val
var xmlHttp ;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
xmlHttp = false;
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error : Cannot create xmlHttp object");
else{
alert("Worked");
//xmlHttp.open("GET","update.php?val="+val,true);
//xml.onreadystatechange = handleServerResponse;
//xmlHttp.send();
}
}
}
Right now I'm just trying to get the "Worked" alert to display at the end of the if-statement. I know the JS is all linked correctly because if I take all the ajax out the data validation works properly with alerts.
In order to troubleshoot this, try:
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
console.log(e.name + " " + e.message);
xmlHttp = false;
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
console.log(e.name + " " + e.message);
xmlHttp = false;
}
}
The idea to figure out what the errors actually are. Once you are out of the try / catch, you loose track of what went wrong.

Unable to POST JSON object from Javascript to a Servlet via AJAX

I am trying to POST a JSON object to a servlet via AJAX. However, the object is null in the servlet. I am unable to figure out what's wrong with this code.
JAVASCRIPT
function submitValues(event, val1, val2)
{
var xmlHttpObj = new XMLHttpRequest();
if(window.XMLHttpRequest)
{
xmlHttpObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");
}
var jsonObject = submitTheValues(event, val1, val2);
alert("json is:" +jsonObject);
var json = JSON.stringify(jsonObject);
alert("json after stringify:" +json);
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/json");
xmlHttpObj.send(json);
}
SERVLET
String jsonObj = request.getParameter("json");
If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode.
xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");
xmlHttpObj.send('json='+encodeURIComponent(json));

error ajax and Jena

When I try to call Jena using AJAX in my servlet I get this error:
java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at fr.objective.blogomatic.semantic.web.ServletAjax.doGet(ServletAjax.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my Jena code:
class classUsingJena {
public void execute(){
String queryString = PREFIXES
+ " Select ?label "
+ " where {"
+ " ?description j.5:entity-label ?label ." + " } ";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out,results, query);
qe.close();}
}
It's running fine, but when I call this function using servlet I get the error described previously.
This is my servlet code:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String service = req.getParameter("service");
classUsingJena jena= new classUsingJena() //bug
return;}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
#Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
urlAjax = config.getInitParameter("urlAjax");
}
My java script code that runs fine:
$("#Analyser").click(function(){
var article = $("#TxtArea").val();
ajaxFunction("acteur",article);
console.log(article);
});
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction(valeur,txt) {
if(xmlhttp) {
xmlhttp.open("GET","ajax?service=ajax&valeur="+valeur+"&text="+txt,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
$("#J").text("");
parseXml(xmlhttp.responseXML);
}
else {
//alert("Error during AJAX call. Please try again");
}
}
}
function parseXml(xml)
{
$(xml).find("nom").each(function()
{
$("#J").append($(this).text() + "<br />");
});
}
In the pom I had declared the old version of Arq 1.8.7 instead of 2.8.7. Now it's running fine.

Newbie AJAX Qn: request.send(information)

I am completely new to AJAX hence this question. I want to send some information from my javascript code to my servlet.
function getDetails() {
vals = document.getElementById("name").value;//works: vals does get inputted value
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "ValidateUser.do";
request.open("POST", url, true);
request.onreadystatechange = displayDetails;
//How do I send the value of "vals" to my servlet?
request.send("name="+vals);
}
When I run req.getParameter("name") on my servlet, I always get no value even though "vals" does contain the inputted value. So my question is- how do I access this value from my servlet?
EDIT:
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
FURTHER EDIT:
Servlet code: I want the println statement to print out the name.
//shortened: this method is called by a ControllerServlet
public Object perform(HttpServletRequest req, HttpServletResponse resp) {
//retrieve customer from database
model = SeekerCustomer.getCustomer(req.getParameter("name"));
System.out.println(req.getParameter("name"));
}
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
function postReq(){
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
}
else{
alert("An error has occured making the request")
}
}
}
var vals = document.getElementById("name").value
var parameters="name="+vals
mypostrequest.open("POST", "ValidateUser.do", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
In the servlet access vals using:
request.getParameter("name");

IE8 is breaking my AJAX... FF is fine

Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.

Categories

Resources