How to update an array Javascript from and array JSP - java

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]);
}
}

Related

get JSON instance to jsp through calling AJAX

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.

HTML from servlet response using ajax is not being executed in JSP page

My problem is kinda weird. I have a JSP page that calls servlet using JQuery/ajax on combobox change. Everything works fine, I get the response but html is displayed as text. Other thing worth mentioning is when I call servlet directly by URL, everything is fine.
Servlet response code:
for(int i=0;i<tabstr.length;i++){
wyjscie.println(i+": "+tabstr[i]+" <br>");
}
JSP ajax call:
$('#com2').change(function() {
$.get('filtr', function(responseText) {
$('#result').text(responseText);
});
});
result is an ID of a DIV inside JSP page. I've done some servlets without ajax in the past and I didn't encounter this problem before. Any idea how to deal with it?
you have to set as html not text try this
$('#result').html(responseText);
I think your server doesn't specify the mime type of the response. So you have to specify it or you can specify dataType in you ajax call.
$.ajax({
url : "myUrl",
dataType : "json",
data : {
param1 : value1,
}
});
ajax api:
dataType: The type of data that you're expecting back from the server. If none
is specified, jQuery will try to infer it based on the MIME type of
the response...

How to validate a form with the Play Framework 2 using javascript, i.e. jquery.ajax, and pass the rendered response to the view?

I am using The play framework 2.1.3 and have a question concerning form validation using jquery and ajax. I have followed the advice in this post (http://franzgranlund.wordpress.com/2012/03/29/play-framework-2-0-javascriptrouter-in-java/) for setting up JavaScript routing and that part is working great! I need help with the second part, returning a rendered form containing error messages and displaying it on my page. I have created the following example to illustrate my problem.
The routes file looks as follows:
# AJAX calls
POST /validateForm controllers.Application.validateForm()
# JavaScript Routing
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
The Application Controller looks as follows:
private static Form<User> form = Form.form(User.class);
public static Result validateForm() {
Form<User> boundForm = form.bindFromRequest();
if (boundForm.hasErrors()) {
return badRequest(user_form.render(boundForm));
} else {
return ok();
}
}
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter("jsRoutes", controllers.routes.javascript.Application.validateForm()
));
}
Without getting too technical, I am using Twitter Bootstrap to render my forms so I have created the following view element (see this post for more information Form validation and form helper) which is rendered by the validateForm action and returns it to the calling jquery.ajax() .
#(userForm: Form[User])
#import helper._
#implicitFieldConstructor = #{ FieldConstructor(twitterBootstrapInput.f) }
#form(routes.Application.createUser(), 'id -> "createUserForm") {
<fieldset>
<legend>New User</legend>
#inputText(userForm("name"), 'class -> "form-control", 'placeholder -> "First Name")
#inputText(userForm("surname"), 'class -> "form-control", 'placeholder -> "Last Name")
<button id="createUserBtn" type="button" class="btn">Create User</button>
</fieldset>
}
I am using jquery and my javascript file looks as follows. For the purposes of this question, assume validation fails and a badRequest is returned.
$("#createUserBtn").click(function() {
jsRoutes.controllers.Application.validateForm().ajax({
type: "POST",
data: $("#createUserForm").serialize(),
success: function(response) {
// something here
},
error: function(response) {
$("#createUserForm").html(response);
}
});
});
Without going into too much detail on the view, I correctly include the JavaScript file in the view and there is an element called #createUserForm.
The communication between client-side and server-side seems to be working great, however, I am unable to load the rendered view element contained in the response onto the page through .html(response). So, how does one accomplish this? Where have I gone wrong? I am fairly new to many of these concepts and would appreciate any helpful input. Thanks.
UPDATE:
Two changes changes will allow this code to work beautifully. (1) Since we are replacing the entire form, including the button, we need to make use of the jQuerys .on() to handle the button click event. (2) Calling responseText property will correctly return the html contained within the result.
$(document).on("click", "#createUserBtn", function() {
jsRoutes.controllers.Application.validateForm().ajax({
type: "POST",
data: $("#createUserForm").serialize(),
success: function(response) {
// something here
},
error: function(response) {
$("#createUserForm").html(response.responseText);
}
});
});
Any comments? How would you do this better?

Display java list data in jsp after jsp is displayed

I am new to Java EE programming. Following my understanding on jsp. Corret me if I am wrong
- JSP pages are converted to servlet first then to html and resulted html page is displayed in browser.
Now suppose jsp page is displayed in browser i.e now it is html page and I have a java List which have names or some sort of data that I want to print on the currently loaded page. I can get the List object using ajax but the how will I display it on html as html cant render java collections.
Correct me wherever I misunderstood the flow or basic concepts.
Thanks.
You could use ajax (using jQuery would be easy) to make a call to your Servlet
function callMe(){
$.ajax({
type: "POST",
url: "/someServlet",
data: { param1: "val1" , param2: "val2" }
}).done(function( data) {
//TODO
});
}
Now on Servlet, in doPost(), Use Gson to generate JSON representation for your collection
String parameter1 = request.getParameter(param1);
String parameter2 = request.getParameter(param2);
//call to service to generate the collection
//for example List<Employee>
List<Employee> employees = someService(parameter1, parameter2);
//using google's gson
Gson gson = new Gson();
String json = new Gson().toJson(employees);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Now we have response in javascript function as a array of javascript objects, So modify it to
}).done(function( data) {
//some processing for display
var len = data.length
for (var i=0; i<len; ++i) {
var employeeFirstName = data[i].firstName;
var employeeLastName = data[i].lastName;
//set it to some DIV, or do the processing you want
}
}
});
Also See
How to call a java method from jsp by clicking a menu in html page?
You need to send the contents of your list as text to the user's browser (which is what normally happens).
A convenient format for transferring the contents of the list between the browser and the server is JSON, due to its simple readability with JavaScript and easy generation on the server.
You can then display the returned text in whatever way you like using JavaScript.
A JSP is compiled into a java servlet class, which can handle HTTP requests. When the servlet is deployed to an application server HTTP requests are passed to the servlet for handling: an HTTP response is generated which normally contains some HTML, a status code, etc.
So it's the java code in the servlet which loops over your list and presumably generates the appropriate HTML to render that list in a browser.
Whether or not it's an AJAX request or not doesn't really matter. Rather than rendering a full HTML page, the AJAX request would probably be handled by a different servlet, which generates only a partial page - perhaps just the <ul><li>...</li></ul> to render your list. The javascript in your HTML page can then take care of updating the user interface by replacing the old version of the list.

How to pass javascript variable value to java class

I want to submit data from a html page to java class. I am using javascript to get data from html page, now I want to send this data to java class to save this data to db. I am using ftl template to generate html so I cant use jsp here. Please give an example using either javascript of ajax or jquery.
thanks.
You can use jquery to send an ajax request to your Java servlet.
$.ajax({
type: "POST",
url: "/app/servlet/",
data: {name : "John", location : "Boston"},
success: function(msg){
alert( "Data Saved: " + msg );
}
});

Categories

Resources