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"
}
Related
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
Am doing the JAVA code found below, to call the servlet doGet() method from JSP page through AJAX call.
Here is my AJAX call..
Am sending the clicked text captured by ng-click of Angular js as a querystring to Servlet's doGet() method .
In my JSP file,
$scope.requestFunc = function (clickData) {
var urlquerystring = clickData;
jQuery.ajax({
type: 'GET',
url: "/Charts/testExecution/"+"?"+ urlquerystring,
dataType: 'html',
success: function(respnsedata)
{
window.location.assign(respnsedata);
}
});
}
In my Servlet's doGet() method,
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.err.println("In TestExecutionESO servlet..");
String teamnametextfield= req.getParameter("teamnametextfield");
System.out.println("Teamname is.."+teamnametextfield);
try {
dcmanager = DataCollectorManager.getInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String selectedteam= req.getQueryString();
String testexeclistofobjectsjson = null;
if(selectedteam!=null)
{
String release=selectedteam.replace("%20"," ").toString();
testexecutionobjlist = dcmanager.getRallyDcMgr().gettestExecutionobjlist(release);
}
Gson gson = new Gson();
testexeclistofobjectsjson = gson.toJson(testexecutionobjlist);
System.out.println(testexecutionobjlist);
System.out.println(testexeclistofobjectsjson);
req.getSession().setAttribute("testexeclistofobjectsjson", testexeclistofobjectsjson);
resp.sendRedirect("TestExecutionESO.jsp");
}
Am getting the querystring perfectly..After the processing, I will do SetAttribute() and redirect to next JSP page..
Redirect is not working..
Here is my error code,
Failed to load resource: net::ERR_TOO_MANY_REDIRECTS..
http://10.112.81.95:9000/Charts/testExecution/TestExecutionESO.jsp.... Failed to load resource: net::ERR_TOO_MANY_REDIRECTS
Please help me resolve the problem..
how to redirect to next JSP page by doing the setAttribute() .??
resp.sendRedirect("TestExecutionESO.jsp");
This is the culprit in your code. when you call sendRedirect(), it will issue a 302 response containing the location-header, URI of the new resource. When the browser sees this header, it will issue a new request for that new URI.
All of this works well for a synchronous request but in case of AJAX calls, we use an XMLHttpRequest, which will not handle redirects so well.
I'd suggest you to use a RequestDispatcher instead to forward to the JSP like this
RequestDispatcher rd = req.getRequestDispatcher("path-to-ur-jsp");
rd.forward(req,res);
for example :
i have a js like :
$.get('Test_Controller.html',function(response){
alert(response);
});
and in my Test_Controller.html servlet i have :
request.setAttribute("test","testData");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/test.jsp");
requestDispatcher.forward(request,response);
Question is :
why is that the response will always alert the text content of the test.jsp and not the JSON that i passed through the getWriter()
EDIT :
I need to get the :
TestData testData = new TestData();
request.setAttribute("test",testData);
using jQuery's $.get() so the page won't reload, but unfortunately when i didn't do dispatch my response object seems to be null and when i do dispatch and forward, when i alert the response it alerts the text of the page.
You want to write some information from within your servlet back to the client.
Your serlvet could look like this:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/json");
Writer w = response.getWriter();
w.append("... your json here ....");
}
And that's all there is (obviously wiring the servlet to your URL in web.xml). Your $.get() should see whatever you write into the writer.
Note that both what's sent (in Java) and what's received (in Javascript) are TEXT strings. You're responsible to convert your data to readable JSON on the Java side, and to interpret the text as JSON on the Javascript side. The latter can be done like this:
$.get(....., function(data) {
try {
// convert the text to JSON
data = jQuery.parseJSON(data);
} catch (e) {
alert("Problem reading data: "+e);
}
... use the JSON data ...
}
In this case the final response is coming from test.jsp because you have forwarded the request to test.jsp inside that Test_Controller.html. If you want to print that json data to test.jsp then you don't need to forward that request to test.jsp page.Otherwise you can also create that json file inside
test.jsp using scriplet tag like:
<%
request.setAttribute("test","testData");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String json = new Gson().toJson(test);
response.getWriter().write(json);
%>
Happy Coding!!!
Get the object in test.jsp .
<%
TestData testData = (TestData) request.getAttribute("test");
String testDataString = new GSON().toJson(testData);
out.println(testDataString);
%>
Javascipt USE $.getJSON instead of $.get
$.getJSON('Test_Controller.html',function(responseJSON){
alert(responseJSON);
var testData = responseJSON;// Then you can accesss your class values.
$.each(testData,function(key,value){
alert("Key:-"+key+": Value:-"+value");
} );
});
The problem I am trying to solve is having a javascript function that will perform some functions in sequence.
Step 1) Web client/javascript does some functions locally to the browser.
Step 2) The browser calls a java class/application on the webserver which will perform a number of tasks that only the webserver itself (not the client) can perform.
Step 3) Have the results of step two added to the webpage and displayed in the browser without reloading all the HTML
N.B. Step 2 may take several minutes and it is ok for the client to be essentially inactive during this time.
I'd appreciate any advice or walk throughs/tutorials that may be relevant.
Kind Regards
Use jQuery to perform an asynchronous HTTP request(AJAX)
function YOURFUNCTION(){
//Calls servlet
$.post('ServletName',{parameter:value,parameter2:value2,...},function(results) {
//displays results returned from servlet in specific div(resultsDiv)
$('#resultsDiv').html(results);
});
}
You need to include the jQuery library on top of your HTML file as:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
You may find more info here
Simple as that.
i hope this concise explanation will give you an overview and the understanding you expect.
PART A
SERVER SIDE
In your web server application on your server, if using Java, you are to create a Java servlet class to process data that was submitted from client browser via script or form and to provide dynamic content such as the results of a database query from the client.
Read more on Servlets from:
http://docs.oracle.com/javaee/5/tutorial/doc/bnafe.html
http://en.wikipedia.org/wiki/Java_Servlet
What is Java Servlet?
Also read more about how to register your servlet on the server (web.xml for java Projects)
Example of a servlet:
-================-
#WebServlet(name = "MyServlet", urlPatterns = {"/calculator"}, asyncSupported = true)
public class MyServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration e = request.getParameterNames(); // parsing the string from client
while (e.hasMoreElements()) {
String name = (String) e.nextElement();// eg. "command" from ajax
String value = request.getParameter(name); // eg. getSum
if (value.equals("getSum")) {
// Instantiate a java class and call the method
// that performs the addition and returns the value
Calculator calc = new Calculator();
String answer = (String) calc.getSum();
if (answer != null) {
// Set contentType of response to client or browser
// so that jQuery knows what to expect.
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
// return answer to ajax calling method in browser
out.print(answer);
out.close();
}
}
} // END While LOOP
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// include method if you call POST in you ajax on client side
}
}
a Java Class for calculations on your server path
public class Calculator {
public int getSum() {
return 10+15;
}
}
-
PART B
CLIENT SIDE – Your Browser
-======================-
You have to visit jQuery website, download and add the jQuery ajax script to your project. “jquery-ui.min.js” is sufficient for this purpose. Add this script to your html or jsp file using the following line:
<script src="resources/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
Within your external javascript file or inline javascript include a function to call the servlet and get the sum as follows:
function getSum(){
$.ajax({
type: 'GET', // type of request to make. method doGet of the Servlet will execute
dataType: 'text', // specifying the type of data you're expecting back from the server
url: 'calculator', // the URL to send the request to. see annotation before class declaration
data: "command="+"getSum", // Data to be sent to the server (query string)
// if request fails this method executes
error:
function(e){
alert('Error. Unable to get response from server');
},
// when request is successful, this function executes
// display the data from server in an alert
success:
function(result){
if(result) {
alert(result);
}
}
});
}
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.