calling servlet from php page using ajax - java

i am trying to get response from servlet page and displaying alert on success. but its show me error always. i am not able to figure it out.
My ajax code:
$(document).ready(function() {
$("#srch").click(function() {
var txt1 = $("#store-qsearch").val();
alert(txt1)
$.ajax({
url : 'http://localhost:8080/searchengine/SearchDataServlet',
data : 'val='+txt1,
type : 'GET',
success : function(response) {
alert("Success");
// create an empty div in your page with some id
},
error: function(){ alert("error");
}
});
});
});
My servlet code:
public class SerachDataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String searchkey = request.getParameter("val").toString();
SearchInput searchinput = new SearchInput();
searchinput.searchkeys = searchkey;
System.out.println(searchkey);
SearchParser searchparser = new SearchParser();
searchparser.searchData(searchkey);
PrintWriter output = response.getWriter();
output.println("successs");
}
}

change this line data : 'val='+txt1, to data: { val: txt1},
see this for example

Related

How to send and catch parameter from JavaScript (AJAX request) to Servlet

I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.
I searched how to do it on Ajax and according to:
How to send parameter to a servlet using Ajax Call
I used: url: "InformationServlet?param=numberOfPlayers"
But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
you can see that the attributes size is zero
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
Engine engine = (Engine)getServletContext().getAttribute("engine");
String responseJson = "";
if(request.getAttribute("numberOfPlayers") != null)
{
String numberOfPlayers = "";
numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
responseJson = numberOfPlayers;
}
out.print(responseJson);
} finally {
out.close();
}
}
JavaScript (AJAX request):
function getNumberOfPlayersAndPrintSoldiers()
{
$.ajax({
url: "InformationServlet?param=numberOfPlayers",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(numberOfPlayers) {
var r = numberOfPlayers;
}
});
}
Edit:
you probably want to use getParameter and not getAttribute
Moreover, please pay attention to the order of parameter name and his value:
request.getParameter("param");
instad of:
request.getParameter("numberOfPlayers");
because the url form contains parameter name first and then the parameter value. for example:
myurl.html?param=17
and if more parameters needed then use the separator & sign
myurl.html?firstName=bob&age=5

Can't receive response from servlet in Jsp file

I am trying to send some query from jsp file to servlet via post method and then get some modified result from servlet to jsp file.
I am able to complete first part successfully, but I cannot receive the response in jsp file.
Servlet post method is:-
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONObject js = <some method to get json>;
System.out.println(js); //works fine
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(js.toJSONString());
}
And my jsp code is:
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + response);
});
}
</script>
The output is:
How can i get that json string ?
you are getting json as response need to stringify it.
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + JSON.stringify(response));
});
}
</script>

Passing custom objects from servlet to Jquery

i have a servlet my goal is to return a customer object from the process request, where i can then access this object in my jquery. Does anyone know how i can go about doing this?
e.g. myObject.getMethod()
Servlet Code:
Customer loginResult;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
//request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
out.println(loginResult);
} finally {
out.close();
}
}
JSP CODE:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "get",
data: dataf,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
Can someone please assist me in resolving this issue, thank you for your help in advance.
Since you want to handle an ajax request using a Servlet, the best bet you have is writing the data of your custom object into the response. The easier way I found to accomplish this is using JSON. There are lot of libraries that handles JSON conversion from objects to Strings and vice versa, I recommend using Jackson. This is how your code should look like.
Servlet code:
import com.fasterxml.jackson.databind.ObjectMapper;
#WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {
//Jackson class that handles JSON marshalling
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
//login operation should be handled in POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer loginResult = ...; //process data and get the loginResult instance
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//marshalling the data of your loginResult in JSON format
String json = OBJECT_MAPPER.writeValueAsString(loginResult);
response.getWriter().write(json);
}
}
Javascript code:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "post", //login action MUST be post, NEVER a get
data: dataf,
success: function(data) {
//shows the relevant data of your login result object in json format
alert(data);
//parsing your data into a JavaScript variable
var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
//now you can use the attributes of your loginResult easily in JavaScript
//for example, assuming you have a name attribute in your Customer class
alert(loginResult.name);
}
});
return false;
});
});
</script>
More info:
How to use Servlets and Ajax?
Parse JSON in JavaScript?

How to pass parameters to servlet using Ext.Ajax.request?

I have an extjs form from which I am trying to post parameter using Ext.Ajax.request to the servlet. Call is working and servlet is being called but for some reason parameter's value isn't being send. I'll post my code, can anyone tell me what I am doing wrong. Thanks in advance.
This is the call from ExtJS form:
buttons: [{
text: 'Search',
handler: function(){
var fName = Ext.getCmp("fName").getValue();
Ext.Ajax.request({
url : 'LookUPCustomer',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
params : fName, // this value isn't being passed to servlet
success: function ( result, request ) {
var resultData1 = JSON.parse(result.responseText);
},
failure: function ( result, request ) {
resultData = JSON.parse(xmlhttp.responseText);
}
});
}];
and here is servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// value of fName is null, not being passed from the form
String fName = request.getParameter("fName");
// does some processing....
// print back to the form
response.setContentType("application/json");
out.println(jsArray);
}
The params parameter should be a JSON object with key, value pairs. Here's an example:
params: {
firstName: 'Jeff',
lastName: 'Tester'
}
or to plug in your variable
params: { fName: fName }
As you said, u are using extjs 4.0.7. it uses extraparams.
So you need to code like below
Before sending just validate whether fName contain required value.
Ext.Ajax.request({
url : <URL>,
method: 'POST',
extraParams :{ fName : fName },
success: function ( result, request ) {
var resultData1 = JSON.parse(result.responseText);
},
failure: function ( result, request ) {
resultData = JSON.parse(xmlhttp.responseText);
}
});
Thanks

Spring 3 exception handling using JSON

I have a Controller and I want to get feedback to the user of what went wrong. The error callback is executed but the error message is not sent back to the client.
The JQuery call:
var validateButton = $('#validateSteps');
validateButton.bind('click', function() {
var stepsInput = $(':input').serializeArray();
$.postJSON('validate.htm', stepsInput, function(data) {
alert(data);
var steps = $('#steps');
var i = 0;
for(i=0;i<data.length;i++) {
steps.stepWidget('setValidationStatus', {testStepId: data[i].testStepId, interactionType: data[i].interactionType, validationStatus: data[i].validationStatus} );
steps.stepWidget('setErrorDescriptions', {testStepId: data[i].testStepId, interactionType: data[i].interactionType, errorDescriptions: data[i].errorDescriptions} );
}
return false;
}, {
error: function (XMLHttpRequest, textStatus, errorThrown, data) {
alert("error function");
alert(textStatus);
alert(errorThrown);
alert("Internal Server Error: " + data);
return false;
}
});
return false;
});
The Controller:
#RequestMapping(value = "validate.htm", method = RequestMethod.POST)
public #ResponseBody
List<ValidationBean> validateSteps(
#RequestBody List<Map<String, String>> testCaseInputs,
HttpServletResponse response) throws MalformedMessageException,
MalformedProfileException, XmlException, IOException,
MissingDependencyException, MessageValidationException {
List<ValidationBean> validations = new ArrayList<ValidationBean>();
...
return validations;
}
The Exception Handler in the Controller:
#ExceptionHandler(Exception.class)
public #ResponseBody
String handleException(Exception e, HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return e.getMessage();
}
What I want to show to the user is the String that should be returned by the handleException method. In the error callback the data parameter is undefined.

Categories

Resources