jquery ajax- get response string from a function - java

I am unable to get the string response from the java function to the ajax call. I am using structs2 . I have wrote a java function that returns a string. the function works properly. but there are some unknown error in the ajax call.
following is my jquery ajax call
<pre>
function saveMyId(){
$.ajax({
url : contextPath+'/action/setMyId',
data: {
myCode:$("#myCode").val(),
myId:$("#myId").val()
},
type : 'post',
async: false,
success : function(data) {
alert(data);
if(data=="success"){
$( "#dialog" ).dialog("close");
$('#myId_Validator').text("");
}
else{
$("#myId").val("");
$("#myId_Validator").val("ID Already exists. Please Choose different one")
}
},
error: function (request, status, error) {
alert("Something went wrong. Please try again later");
}
});
and my java function is
public String setMyId() throws SQLException {
IdAllocationVO idAllocationVO = new IdAllocationVO();
MyIdServices myIdServices = new MyIdServices();
logger.debug("set My Id , myCode :"+this.myCode);
idAllocationVO.setMyCode(myCode);
idAllocationVO.setMyId(myId);
int response= myIdServices.getMyIdCount(myId);
System.out.println("response:"+response);
if(response==0){
myIdServices.setSenderId(idAllocationVO);
return "success";
}
else{
return "fail";
}
}
I am using structs 2
and the structs.xml tag is
<action name="setMyId" class="com.id.myIsservice.struts.IdAction" method="setMyId">
</action>
The function setMyId() is working correctly. I have checked everything by printing each line. But my issue is the ajax call gets the result as an error. so it alerts the error message "Something went wrong. Please try again later". Why it is so?

there are three steps you can try to use for finding the reason:
1、If your ajax call is correct?
firebug or other page dubugger can show you~
2、When the 1st step is correct, check the java function to see if it gets the request from page and responses the right result to page
IDE debug tools will help you~
3、Check what results are got by page
through firebug you can see the response details, like 'status' and others..., findout if the string has been got~
PS:
I see, your java code throw exceptions directly without using try/catch. It's not a good way for users' use~ I suggest you to add try/catch code, with whith maybe help you find error quicker~

Related

Getting a null response when calling a php site function from java in android

I'm trying to call a php function on a site that I have from an android application.
I'm using this to get my response: https://github.com/koush/ion
Here is my php code which is located at : Link
It's used to connect to a database i have on that site.
The php file just returns all the entries in the database as HTML text shown under the php code (Not sure if this is the proper way to get data from a database).
The Database entries get their own tags so I can handle them later in the app.
<?php
include('dbconnect.php');
if (isset($_GET['Tabela'])) {
DobiPodatke($_GET['Tabela']);
} else {
ECHO '<error>Ni selekcije</error>';
}
function DobiPodatke($Tabela)
{
$sqlget = "SELECT * FROM " . $Tabela;
ZazeniQuery($Tabela, $sqlget);
}
function ZazeniQuery($Ime, $Query){
$sqldata = mysqli_query($GLOBALS['dbcon'], $Query) or die('<error>error with fetching data</error>');
ECHO '<' . $Ime . '>';
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
switch($Ime){
case 'Sola':
ECHO '<vnos><Kratka_Oznaka>' . $row['Kratka_Oznaka'] . '</Kratka_Oznaka><Ime>' . $row['Ime'] . '</Ime></vnos>';
break;
case 'Stroka':
ECHO '<vnos><Ime_Stroke>' . $row['Ime_Stroke'] . '</Ime_Stroke></vnos>';
break;
case 'Sola_Smer':
ECHO '<vnos><ID_Sole>' . $row['ID_Sole'] . '</ID_Sole><ID_Stroke>' . $row['ID_Stroke'] . '</ID_Stroke><Stevilo_mest>' . $row['Stevilo_mest'] . '</Stevilo_mest></vnos>';
break;
}
}
ECHO '</' . $Ime . '>';
}
?>
HTML Response:
HTML
Now in order for this to work I need to supply the php function parameter on which table i need infromation from so I call it like this:
https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola
Tabela beeing the variable I need to pass in otherwise the php does a die()
In the example above I called the php file with "?Tabela=Sola" at the end to get all table entries in the table "Sola".
While this works in the browser, it does not in my application.
Now in my android application I use the Ion library/class to get my response from a website in pure HTML code. It works with a regular website since I can get the whole HTML code from the site.
It however does not work on my php site since i get a null result.
The link variable in the following code is:
https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola
Java code that connects to the website and returns the result:
private static void ParseDBFront(String link, Context context){
Ion.with(context).load(link).setLogging("MyLogs", Log.DEBUG).asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.i("LOG", "LOG: " + result);
}
});
}
And the response I get from the above code when running is:
I/LOG: LOG: null
All i need is for the java code to return the HTML code but I have no idea why it won't return the html code.
I'm guessing that i'm parsing my variable in the wrong way.
I appreciate any feedback or solutions to this problem.
Managed to figure it out myself.
There was no problems with the code as is, the problem was the way i wrote the URL of my php file.
Original link:
private static final String DBLink = "www.illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=";
And how I fixed it:
private static final String DBLink = "https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=";
That "www." / "https://" difference is all that caused my program to return a null response for some reason.
I don't know why but the problem is gone.

ajax calling the wrong servlet

weird problem here I can't seem to solve.
I'm working in Eclipse Java EE, I have a servlet called Process (mapped to /process)
There is a link to process
Checkout
Within process is a doGet method, verifying there is a user logged in, which redirects to a checkout page. (this works) The checkout page contains items, each with an individual input, and I have a seperate doPost method which updates the DB.. obtaining the input to update as follows
<input id='ID created in servlet' value='decided in servlet'>
followed by
<button id="update">Button</button>
I have the following JS
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : 'process',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
So, two questions I guess.
First, this is sending a request to a different servlet, in a different project. However when accessed using a doGet, it works. (I have different code for a doPost) Is there any reason it's not recognizing the doPost method within my Process.java file? What could cause it to search for another servlet?
Second, I know what to do once I get the data in the servlet, but I don't know how to actually access the data. It's passed through jquery in 'data:', then how would I access it in the servlet?
First Question:
If i have understood right, Your problem is that "when you try to send a post request using AJAX (inside a jquery function), you are not hitting the desired servlet".
Solution: You need to append the name of your project to the url.
So lets say your servlet is placed in project named "SomeProject" and the servlet is mapped to url named "servletProcess".
So your jQuery should look something like this:
var json = [];
$('#update').click(function(){
$('.items').find('input').each(function(){
var tmp = "{id:" + $(this).attr('id') + ",quantity:" + $(this).val() + "}";
json.push(tmp);
});
$.ajax( {
url : '/SomeProject/servletProcess',
type : 'POST',
data : json,
dataType : 'json',
success: function(data) {
alert("success");
}
});
});
This should fix the problem :)
Second Question: try this Similar Query

How to pass javascript variable in jsp page to another java file?

Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?
This is Checkbox Function:
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
//passThisVariableToAnotherJavaFile-isChecked
}
else {
//passThisVariableToAnotherJavaFile-isNotChecked
}
};
This is Java File:
public class CheckBoxEvent{
if(isChecked) {
//then whatever
} else if (isNotChecked) {
//then no whatever
}
}
I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.
Thank You
How to pass the variables in the javascript function to another java file without passing it through url for security concern?
You have two options here and in both the cases you need to send the value to the server for processing :
An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
Submit the form using POST.
Read here When do you use POST and when do you use GET?
In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.
when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is
the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form

Return JSONObject from servlet throws exception

I have a servlet to which I am posting data from ajax(jquery) call.
$('form').submit(function() {
var URL = "ProjectHandler";
var dataString=$(this).serialize();
$.ajax({
type: "POST",
url: URL,
data: dataString,
// dataType: json,
success: function(data)
{
alert(data.error);
}
});
return false;
});
I have commented dataType beacause when I uncomment it, it doesnt make ajax call, rather, the form is submitted with default mode i.e. the servlet is loaded
JAR's I have added to the project 1. json-lib-2.2.2-jdk15.jar 2. apache-commons-lang.jar 3. ezmorph-1.0.jar
first it threw exception filenotfound which was part of apache-commons package so included apache commons, after that I got exception of filenotfound which was part of ezmorph-1.0.jar, so I added that also. Now I am getting
java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
Code in servlet doPost:
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
json.put("error", true);
json.put("errorDesc", "wrong title");
out.print(json);
I hope I have cleared the scenario, any help would be appreciated.
Thanks
It looks like you are missing the commons-logging.jar. Add it to your classpath.
Can you drop json-lib? If yes do it! Honestly there is no reason to use this library...the fact that it requires you to add tons of dependencies prooves it.
I would suggest you try Genson library http://code.google.com/p/genson/. It has the advantage to be easy to use but powerfull, extensible, all in one and fast.
It would allow you to deserialize/serialize directly to pojos, no need to use all those JsonObject/Arrays... You can also directly use its streaming API if you need something close to manual json in term of performances.

Form submit and HttpServletRequest

I'm facing this problem with regards to Forms and Requests. I'm using sencha and javascript to create a webpage that POSTs a form to a java web application which pulls data from a database and formats it before returning a html page to the client.
The problem I'm facing is that for some reason, while the form does get filled(checked using the debugger in chrome), the java program does not recognise the parameter within the form, and instead reads it as null.
I'm following the method of setting the form from an old java program, which works, however it fails for mine. Does anyone know how I can solve this or where I might be doing wrong?
I've included the javascript and java codes where I decide which page to return below.
Javascript handler for function call to submit form:
var MenuA = function() {
simple.getComponent('flag').setValue('MenuA');
simple.getEl().dom.action = './Soap';
simple.getEl().dom.method = 'POST';
simple.submit();}
Java code to decide choice of page:
if (request.getParameter("flag").matches("MenuA")) {
choice = 2;
} else if (request.getParameter("flag").matches("MenuB")) {
choice = 3;}
FormPanel Code:
var simple = new Ext.form.FormPanel({hidden:true,standardSubmit:true,
items:[
{xtype: 'textfield', hidden: true, name : 'password', label: 'Password', id:'password'}
,{xtype: 'textfield', hidden: true, name : 'user', label: 'user', id:'user'}
,{xtype: 'textfield', hidden: true, name: 'flag', label: 'flag', id: 'flag'}]})
Your
request.getParameter("flag").matches("MenuA");
method is looking for a form element whose name is "flag".
Since your form may not contain the flag field so it assumes it to be null.
So, to overcome you can add an input field to the form with name "flag" and put put your desired value in it.
I think this should work for you.
Nevermind. Found the problem. I didn't realise the form was not being sent properly. Sorry for the trouble!

Categories

Resources