I get the JSONOject from my bean in my helper class.
Inside helper
public JSONObject init() throws Exception{
// initializations codes are here
JSONObject json = JSONObject.fromObject(bean);
return json;
}
Then I need to access above JSONObject inside a jsp calling through ajax request when loading the jsp(to assign javascript variable like bellow)
inside jsp
$(document).ready(function(){
var VAR_JSON = // need to get the JSON through AJAX
});
previously I had a code like this.
<script type="text/javascript">
var VAR_JSON = <%=helper.init()%>
</script>
how can I achive this by AJAX ?
thanks in advance..!!
First of all, stop thinking JSP. The JSP is (part of) what executes on your server when a request is being handled. That in turn returns a response to the browser (usually a webpage); your JavaScript (and therefore your AJAX request) run in the user's browser on that webpage, not in your JSP.
jQuery provides a function specifically designed for getting JSON through an AJAX request; it's called jQuery.getJSON(). You'd use it something like this:
<script type="text/javascript">
$(document).ready(function() {
var VAR_JSON;
function yourFunction() {
// do something with VAR_JSON here
}
$.getJSON('yoururl.do', function(response) {
VAR_JSON = response;
yourFunction();
});
});
</script>
It's important to note that you can't do var VAR_JSON = $.getJSON() because the function is asynchronous, and therefore doesn't return the JSON (it returns something else - see the documentation linked above). You instead need to provide a callback function that will execute when the asynchronous request returns a successful response, which will then set your variable and call another function that uses it.
Also note that you won't need to call something like JSON.parse() because jQuery does that for you; you've told it you're expecting JSON back so it parses that string to get the resulting object or array, which is then in turn passed as an argument to the callback function.
Related
I need to update a javascript array everytime there is and event, like a click intercept with JQuery. I need that new value from JSP array come into an array javascript.
I know there are solutions like this Passing array from .jsp to javascript function.
The problem is quite different: code linked run only once, when I need to update every time I intercept an event.
I can understand that problems is inside the translation from Servlet to HTML, it seems: once the Jsp variable take value the first time than they became "static code" and it can't change.
Could you suggest me some alternative or solution?
function update_coordinate_javascript()
{
<%
for (int s: mycord.getXY()[0]) {
%>
xyscript.push(<% out.print(s); %>);
<%
}
%>
}
$("#myB").click(function(){
$.ajax({
type: "POST",
url: "readXY.jsp", // Some elaborations
data: {incrementa:true},
dataType: "html",
success: function(msg)
{
alert("Ok");
},
error: function()
{
alert("Fail");
}
});
update_coordinate_javascript();
return false;
});
}
You cannot mix Javascript and JSP like you're trying in the update_coordinate_javascript function, because Javascript runs client-side and JSP server-side.
What you are doing in that function is printing the values that the JSP has in mycord at the time it runs on the server-side. You are printing those into the Javascript function (view source to confirm) and thus you are printing out Javascript code basically. And once you've done that, you have a Javascript function with a hardcoded list. So every time you call that function you're just populating the same hardcoded list.
Instead: The JSP you are calling in Ajax should print the array to the response either as JSon, XML, or as a string with a certain character reserved to be used as a separator, and Javascript should parse that.
$.ajax({
type: "POST",
url: "readXY.jsp", //print array as JSON, XML, or CSV-like text there
data: {incrementa:true},
dataType: "html", //change this to JSON, XML, or text as needed
success: function(msg)
{
//msg here is the response from the JSP you are calling,
//so whatever you print to response there
//is in this variable
alert("Ok");
update_coordinate_javascript(msg); //parse the msg in there
},
error: function()
{
alert("Fail");
}
});
Then obviously you need to take the JSP scriplet code out of update_coordinate_javascript and change it to Javascript code that parses the msg parameter which is passed in. How you will do that will depend on how you decide to format the output from the JSP you are calling in Ajax (i.e. whether you have it return CSV-like text, XML, HTML, or JSON).
So if you go with CSV, it could be as simple as:
function update_coordinate_javascript(msg)
{
var mycords = msg.split(",");
for(var i=0; i<mycords.length; i++)
{
xyscript.push(mycords[i]);
}
}
What I'm trying to do today is to directly call a Javascript function from a JSP Servlet response. What does that mean? Here's the code:
Servlet, This is contained in myServlet.java
// Takes an XML already previously parsed as a string as input
CharSequence confirm= "something";
if (xml.contains(confirm)) {
// Carry on
// If it is contained we needn't go further
} else {
// "couldn't find confirms content
errorMessage = "Does not contain confirm";
// "If ^ quit this servlet"
request.setAttribute("rol", this.rol);
request.setAttribute("user", this.user);
request.setAttribute("errorMessage", errorMessage);
forwardToJSP(request, response, "/myJSP.jsp");
}
Now In Javascript I already have defined a function I want to be called. It is something along these lines:
Javascript, This is contained in myJSP.jsp
<script language="JavaScript" type="text/JavaScript">
// Assume all document.getElementById calls are properly implemented,
// they call real variables that exist elsewhere, but not shown
// here due to irrelevance.
window.errorExists = function() {
var errorExists = document.getElementById("terror");
errorExists.setAtribute("terror", "Does not contain confirm");
if (errorExists.attributes == "Does not contain confirm"){
if(confirm("Cannot find content, do you wish to add it?")){
anotherFunctionCall();
} else {
// Don't do anything
}
}
}
</script>
Now, in simple terms what I want to do is to call my Javascript function from the aforementioned JSP. I think cannot do so with work arounds such as:
PrintWriter out = response.getWriter();
out.println("<tr><td><input type='button' name='Button' value='Search' onclick=\"searchRecord('"+ argument + "');\"></td></tr>");
Because the other function wouldn't be called, also there's an update to Javascript variables.
How would one go around this?
Any and all help is greatly appreciated.
You can call that method in onload parameter of body of JSP page.
As you are already calling a JSP page using Forward method, your JSP page is getting loaded when you call it. You can call your method in body tag of JSP page as follows:
<body onload="YourMehodName()">
alternatively, you can put this script at the bottom of your JSP which will get called on loading of your page.
I'm on a jsp page and I am doing an ajax call to a servlet which in return provides full html code to be displayed on page. It works fine but looks cluttered in servlet file to have multiple printWriter.write(...) lines with html code in it. It becomes hard to maintain as I have to create a large html code via servlet. Is there any other proper/better way to do this? I have cmobination of write html lines and logic in servlet and it will be hard to separate them.
The ajax call in jsp page:
$.ajax({
type: 'POST',
url: 'myServlet',
data: requestData,
dataType: "text",
}).done(function(responseData) {
$(divId).html(responseData);
});
Some code from servlet class:
.....
String username = user.getName();
if (username != null && !username.trim().isEmpty())
username = username.substring(0, username.indexOf(" "));
else
username = "";
printWriter.write("<span id=\"username_"+i+"\" style=\"display: none;\">"+ username +"</span>");
printWriter.write("<form action=\"\" method=\"post\" name=\"userClickForm_"+i +"\" id=\"userClickForm_"+i +"\">");
printWriter.write(" <input type=\"hidden\" name=\"userId\" value=\""+userId +"\"/>");
printWriter.write("</form>");
......
The main reason of mixing html code and business logic is I have to provide div id based on conditions and loop structure.
You should use some form of template or transformation technology. Since you're using jQuery and JSPs this can be either a server-side JSP or a client-side jQuery template plugin.
Early JSP MVC patterns take this form:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// read inputs
String foo = request.getParameter("foo");
// perform business logic
SomeResults results = new SomeDataSource().lookupDatabase(foo);
// place results into scope
request.setAttribute("results", results);
// dispatch to JSP to render results
request.getRequestDispatcher("result.jsp")
.forward(request, response);
}
This approach can be used with an AJAX call.
Alternatively, you can respond with JSON or XML data and parse this in the JavaScript, then use a JavaScript template engine to do something similar to the logic performed in the JSP.
You can avoid that by using MVC framework like STRUTS or SPRING.
Use xml rather than html on servlet and on jsp use success attribute of ajax call using jquery.... In my case its working, bt i have used type as 'GET'.
$.ajax({
url: ,
data: ,
type: ,
dataType: 'xml',
async: true,
success:function(xmlDoc)
{
var message = xmlDoc.getElementsByTagName("message");
message = message[0].firstChild.data;
}
});
And in Servlet use::
res.getWriter().write("<response><message>abcdefg</message></response>");
You should use JSP's. It will be on different pair of servlet/jsp request, not the request initiating ajax call.
I want to send a JSP page which consists of some divs and table as part of AJAX response from spring framework, is there any way to send JSP as a response of AJAX call
Sending JSP by AJAX makes no sense, it is basically the HTML generated by a JSP that is sent over to the browser through AJAX, as rightly pointed out by the lost.
You do not need any server-side coding for this. All you need is to write some JavaScript on client-side to receive your HTML asynchronously. For this, I would recommend using some JavaScript framework like jQuery, otherwise, it would make your life hell.
Assuming that the page you want to access by AJAX has the link http://domain:port/mypage.htm. First you need to include jQuery in your base JSP (JSP in which former page has to load by AJAX):
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
Then you need to call jQuery's AJAX function:
$(document).ready(function(){
$.ajax({
type:"GET",
url: "http://domain:port/mypage.htm",
success: function(data) {
// Now you have your HTML in "data", do whatever you want with it here in this function
alert(data);
}
});
});
Hope it helps!
Yes, there's no magic to this though. In your Java AJAX handler just return a forward or redirect to the JSP page you want. The response will then be available as the responseText in your AJAX callback.
You can use JSP to generate just the elements you need as a sort of incomplete HTML fragment then returns this from your server-side handler. Then in your JavaScript callback you can insert the fragment into your existing HTML like this
element.innerHTML = resp.responseText
//element is the parent you want to insert to
//resp is the parameter supplied to your callback
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 1 year ago.
I am trying to create a web application using the MVC design pattern. For the GUI part I would like to use JavaScript. And for the controller Java Servlets.
Now I have never really worked with JavaScript, so I'm having a hard time figuring out how to call a Java Servlet from JavaScript and how to get the response from the Servlet.
Can anybody help me out?
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World! in the JavaScript alert.
You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
The code here will use AJAX to print text to an HTML5 document dynamically
(Ajax code is similar to book Internet & WWW (Deitel)):
Javascript code:
var asyncRequest;
function start(){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open('GET', '/Test', true); // /Test is url to Servlet!
asyncRequest.send(null);
}
catch(exception)
{
alert("Request failed");
}
}
function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
{
var text = document.getElementById("text"); // text is an id of a
text.innerHTML = asyncRequest.responseText; // div in HTML document
}
}
window.addEventListener("load", start(), false);
Servlet java code:
public class Test extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException{
resp.setContentType("text/plain");
resp.getWriter().println("Servlet wrote this! (Test.java)");
}
}
HTML document
<div id = "text"></div>
EDIT
I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):
document.location = 'path/to/servlet';
Where your servlet-mapping in web.xml looks something like this:
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});