Parameter is not passing from extjs grid to servlet page - java

In my application I am passing parameters from grid to servlet page. But in servlet it is coming as null. Any idea what is wrong in my code..
Note: From this servlet page I am taking data for another grid.
Function to pass parameter:
function callAjaxToCheckSession(selected)
{ alert(selected);
Ext.Ajax.request({
url: 'YieldCurveServlet',
method:'POST',
headers: {'application/json'},
params: {
YCSET_ID: selected
},
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}
In this I am getting value in an alert. and same value in http header (request payload YCSET:value). But in servlet it is coming as null.
Here is my servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String val = request.getParameter("YCSET_ID");
System.out.println(val);
Here is header Part:
Request Method:POST
Status Code:200 OK
**Request Headers**
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:21
Content-type: text/html
Cookie:JSESSIONID=5621DF422D5E54A4EFFD29E5868A40FE
X-Requested-With:XMLHttpRequest
**Request Payload**
YCSET_ID=SPREAD_CURVE
**Response Headers**
Content-Length:56
Content-Type:text/html
Date:Tue, 24 Dec 2013 12:48:13 GMT
Server:Apache-Coyote/1.1
Any suggestion to fix this issue?

You have to get the value send as parameter in the request with the getParameter function, so uncomment the line :
String val = request.getParameter("YCSET_ID")

request.getParameter("parameter_name"); works for query string parameters and form data. To get JSON data serverside from a request try this:
BufferedReader buff = request.getReader();
String json = buff.readLine();
if (!json.startsWith("[")) {
json = "[" + json + "]";
}
The if part works when you have a single value on your array and it looks more like an object. That way you can treat it as an array always.

Related

angular send post request but servlet keep showing nul value

i have angular controller which triggered with ng-click:
app.controller('showAllWorkersContoller', function($scope, $http){
$http.get("/SafetyManager/workers").success(function(response){
$scope.workers = response;
$scope.workerInfo = function(id){
$http({
url: '/SafetyManager/workers',
method: "POST",
data: { 'ID' : id },
}).success(function(response){
$scope.info = response;
});
};
});
});
and when i check on chrome debug it sends in form data: {'ID':"1"} (or any other id num according to the worker i click on)
but when the Servlet get the request:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post request to Workers (get worker by id )");
String id = request.getParameter("ID");
System.out.println("this id is: " + id);
}
its print :
post request to Workers (get worker by id )
this id is: null
how can i get the ID value in the servlet?
The data that you post will not be available as a request parameter, it is in the request body.
You can use a reader to read content from body.
Refer: Getting request payload from POST request in Java servlet
You have to use req.getAttribute(name) to get body content.
Refer this blog:
Difference between getAttribute() and getParameter()

Cannot display response of HTML servlet in Ajax and qTip2

I am trying to display text (or html) that is received from a servlet response in a qTip2 tooltip within a jsp. I have almost everything working and have verified with Firebug that the servlet is being invoked and text is being returned, but when I try to use the 'html' (or data) variable in my ajax call, I get an error: HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy.
I've tried displaying the html in a JavaScript alert, and this is what displays: [object XMLDocument].
Here is the sequence of events:
1.User clicks on a section of HTML text, which has a link defined that points to the servlet and passes parameters
2.The ajax invokes the servlet which does some processing and returns text or html
3.The text is displayed as a tooltip with qTip2
How can I properly handle the response from the servlet and manipulate the text that is received from it?
Ajax call:
$(".ajax_link").click(function(e) {
e.preventDefault();
var $this = $(this);
var link = $(this).attr('href'); //Gets link url
$.ajax({
type: "GET",
url: link,
cache: false,
}).done(function(html) {
$this.qtip({
content: {
text: html //<--this causes error above
//text: "<table><tr><th>Team</th></tr></table>" <--this works fine
}
});
$this.qtip('toggle', true);
});
});
Servlet Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("inside doGet");
String var1 = "<table><tr><th>Team</th></tr></table>";
//var1 = request.getParameter("var1");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(var1);
out.flush();
out.close();
}
pass dataType as html in ajax request
i.e.
$.ajax({
type: "GET",
url: link,
cache: false,
dataType : "html"
}

My Titanium Post Works, how do I display in Java Servlet?

Hi im trying to send data from my titanium app to my Apache Web Service. The snippet of titanium code works as the output to the console is success. Now what im trying to do is when the post is sent, display the contents of the post on the web service page. Is my doPost correct?
Titanium Snippet
button.addEventListener('click', function(e) {
var params = {
"places" : {
Country : textCountry.getValue(),
Capital : textCapital.getValue()
}
};
var xhr = Ti.Network.createHTTPClient({});
// function to deal with errors
xhr.onerror = function() {
Ti.API.info('error, HTTP status = ' + this.status);
alert('Error Sending Data');
};
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
};
xhr.open("POST", 'http://130.206.127.43:8080/Test');
//set enconding
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(params));
});
Java Servlet/Apache Tomcat Snippet
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String jsonData = request.getParameter("json");
response.setContentType("applicaiton/json");
PrintWriter out= response.getWriter();
out.println(jsonData);
out.close();
}
18/02/205
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
Ti.API.info('json' + this.responseText);
};
[INFO] : success, HTTP status = 200
[INFO] : json = null
Set a breakpoint in the xhr.onload and look at the variables that are present before your write your log.
You are looking for the this.responseText, which will have the response from your call to the Java servlet. I mainly use WCF and C# and if I don't setup the WCF service specifically to clean-up the output, it will add the function name to the response.
Generally, my onload looks like this.
xhr.onload = function(){
var result = JSON.parse(this.responseText);
Ti.API.log(result);
}
* Look closer at your Java Servlet return type. It is a VOID return type so no data will be returned to the http call. *
http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Network.HTTPClient

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

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