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

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

Related

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

Not able to receive parameters using Postmapping in Rest Controller

My Ajax code looks like this
$.ajax({
type : 'post',
url : url,
async : false,
data: {'txToClose': '1234,5678','sno':'0195'},
contentType : "application/x-www-form-urlencoded; charset=utf-8",
dataType : "json",
success : function(result,status,xhr){
console.log(result);
}
});
The txToClose value 1234,5678 will be coming from a textbox as comma separated string. The user will type them as comma separated.
Im trying to receive them in controller as
#PostMapping("/txToClose")
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response) throws BBException
{
logger.info("Called txToClose controller");
ResultDto resultDto = new ResultDto();
String txToClose= request.getParameter("txToClose");
String sno= request.getParameter("sno");
logger.info("Transactions to close :"+txToClose+", Serial Num :"+sno);
}
Output is
Transactions to close :null, Serial Num :null
What am I missing here?
You're posting your data as request body, which of course using request.getParameter() will give you null. getParameter() was used to retrieve value from URL parameter.
I'm not quite experience with SpringMVC but try to change your method parameter into
public ResultDto txToClose(#RequestBody ResultDto resultDto ) throws BBException
{
logger.info("Called txToClose controller");
String txToClose= resultDto.getTxtToClose();
String sno= resultDto.getSno();
logger.info("Transactions to close :"+txToClose+", Serial Num :"+sno);
}
I assume your ResultDto is same as your JSON format.
remove the line
contentType : "text/plain; charset=utf-8",
or use default contentType
contentType : "application/x-www-form-urlencoded; charset=utf-8",
It should work.
I solved the issue by adding #RequestBody ObjectNode json in the signature.
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response,#RequestBody ObjectNode json) throws BBException
{
logger.info("Called txToClosecontroller");
ResultDto result = new ResultDto();
String txToClose= json.get("txToClose").asText();
}

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

Handle JSON Array posted from Ajax in Struts 1.3

I build the JSON Object like this:
var key = //some calculated key
var key = //some calculated value
var list = {item: []};
list.item.push({
"key" : key,
"value" : value
});
Then I send the array like this:
sendData = function() {
$.ajax({
url :'<html:rewrite action="/sendData"/>',
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {"list":list.item},
success:function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
How can I retrieve in my action the JSONArray/JSONObject and handle it?
I've tried this:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String list = request.getParameter("list"); //null, I supposed to find a string formatted like json
return null;
}
Even GSON library is allowed!
You will get significant improvement if you convert your object to string when sending it as parameter.
data : {list: JSON.stringify(list.item)}

jquery ajax call returns error on successful call to a servlet

I have a servlet that adds a user to a file on the server side.
I invoke it with a jqueries ajax call.
I can see on the server that the method is being called correctly and my user is added, but the error callback is being invoked on the jquery call. All the status text says is error.
Using firebug the response seems to be empty. Why can I not get a success jquery callback?
//Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String responseStr = "";
if(action.equals("addUser"))
{
responseStr = addUser(request);
}
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().println(responseStr);
}
private String addUser(HttpServletRequest request) throws IOException
{
Storage s;
s = Storage.load();
String name = request.getParameter("name");
String imageUrl = request.getParameter("imageUrl");
User u = new User();
u.setName(name);
u.setImageUrl(imageUrl);
s.addUser(u);
s.save();
return "success";
}
.
//javascript code
function addUser() {
var name = $('#name').val();
var imageUrl = $('#imageUrl').val();
var url = "http://ws06525:8080/QCHounds/QCHoundServlet?action=addUser&name=${name}&imageUrl=${imageUrl}";
url = url.replace("${name}", name);
url = url.replace("${imageUrl}", imageUrl);
$('#result').html(url);
$.ajax({
url: url,
success: function( data ) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
});
}
Aaargh! Feel like an idiot. It's a cross site scripting issue.
I was testing the call to the server from the html file on disk so my browser address was
file://projects/myproject/content/Users.html <<< Fail
instead of:
http://myboxname:8080/appname/Users.html <<< Works
The actual code is fine...
use this for learn what is the problem, it will be better for get solution i think
error: function(e){
alert(JSON.stringify(e))
}
For one thing the string "success" isn't valid json. If your ajax query is expecting json, that would fail it.
What if you returned "{ \"success\": true }" ?
EDIT
It looks like from your ajax call that the response shouldn't be json, why is your return content type json?
If it is true that firebug shows no response, your problem must be in the java code that writes the response.

Categories

Resources