Loading a popup using ajax - java

I have a jsp page which should load a popup using ajax. The content of the page is determined by form filled by user.
Something like this:
javascript:
ajax('getPage.action', 'content_id', 'form_id');
foo.jsp:
<div id="content_id"></div>
<form id="form_id">
...
</form>
java/spring:
#RequestMapping("getPage.action")
MyController extends AbstractCommandController {
RealDto dto = (RealDto)command;
...
return new ModelAndView("foo", data);
}
The most difficult part for me is how to send the form data easily as an ajax call. Can I use jQuery here? The form changes dynamically so it would be quite bothersome to list all the fields of the form.
Would it help to use Springs XT (which I never have)?

Yes, you can use serialize to trivially convert the form to send the data.
$("#form1").submit(function() {
$.get("/desiredURL", $("#form1").serialize(), function(response) {
// send response data to a popup
}
}
You can use get or post to send the data.
For the popup I like facebox, but there's loads of choices.

jQuery form plug-in can help you easily transform a regular form to an Ajax one. You only need a single line of code:
$("#myform").ajaxForm(
{beforeSubmit: validate, success: showPopup} );

I don't know about jQuery, but for prototype this is easy:
new Ajax.Request('getPage.action', {
parameters: $('form_id').serialize(true),
onSuccess: someMethod
);
Check out the Prototype API docs.
This page has the same information for jQuery: http://docs.jquery.com/Ajax

Related

How send information from forms without submit modal?

Right now i'm using jsp and bootstrap to make my front-end, and i have an option to make a new register inside a modal and this new register needs to be in my behind screen, in the past projects I used angular and it was very easy to do, but now using jsp I haven't any ideia to make it without submit my modal.
Is there a way to make it without submit my modal?
You can use Ajax, that way you can post the form to back-end to make what you need to do and than return the object to front-end.
Seeing your tags you're be able to make like that
Controller:
#Post
public void methodName(final T entity) {
.
.
.
result.use(Results.json()).withoutRoot().from(insertedObject).serialize();
}
Front:
$.ajax({
type : 'POST',
url : 'method url',
data : form.serialize(),
success : function(data){
// data is the object inserted
}
});

How to send response through ajax from servlet back to jsp? [duplicate]

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

how to get data from server without refreshing the page

I am new to web development. My job is to get data from the server and plot them using amcharts every 1 or 2 seconds.
This is what i have so far:
<form id="getdata" role="form" method="post" action=#routes.DataApplication.get_data()>
<input type="text" name="device" id="device">
<input type="text" name="type" id="type">
<button id = "submit" type="submit">Submit</button>
</form>
Once I enter device and type and click the submit button, it will run the Java method get_data(). The method will search the database and return data that matches the device name, but the thing is it will display is the data in another page, for example www.somepage/getdata. The above html is in www.somepage/data page.
I tried using jquery .post() but the thing is it requires an url, I tried passing /getdata to it but didn't work.
My question is: is there a way to save the data we get from the #routes.DataApplication.get_data() action without reloading the page?
By the way, I am using play framework to develop the webpage.
UPDATE
Ok, making some progresses now, I tried using ajax post, but the data return (in console) is like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
Here I got 11 objects. If i don't use ajax post (using the original post form method), I get 11 data points too.
Here is my code:
<script>
$('#driver').click(function(evt) {
var dataabc = $('form').serialize();
console.log(dataabc);
$('#errors').hide();
$.ajax({
type : 'POST',
data : dataabc,
url : '#routes.DataApplication.get_data()',
success : function(data) {
alert("good");
console.log(data);
},
error : function(result) {
setError('Make call failed');
}
});
return false;
});
</script>
What get_data() does is just take the user input data (which is the form) and get corresponding data from the database and return ok(node);. This node is JsonNode
Any help would be appreciated..
Since you are getting an array of objects back in javascript and it is stored in data. You can loop through it and display the content is some div tag.
Example:
Create an empty div to populate the data after a successful ajax call.
<div id="mytextarea"></div>
Then in your ajax success, instead of printing to console you would loop through the array and append the data to the innerHTML of the div tag like so...
var myTextArea = document.getElementById('mytextarea');
for (var x = 0; x < data.length; x++){
myTextArea.innerHTML = myTextArea.innerHTML + data[x].id + '<br/>';
}
Edit 1: I see you know your object's attributes so I updated the code to append just id to the text area.
It will be very helpful to tell us what exactly the url returns in response. Usually that should be XML or JSON.
You can use FireBug or any other developer tools to catch the response and post it here.
IT doesn't decide what to return - it's YOU!
If you'll return for an instance JSON object in your get_data() action, your AJAX will receive a JSON, check yourself:
public static Result get_data(){
ObjectNode node = Json.newObject();
node.put("hello", "world");
return ok(node);
}

How to use struts tag in javascript

I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.

Spring MVC ajax re-rerendering user interface duplication

First of all I am mainly with a JSF background.
I have started recently studying Spring MVC. One thing that is bothering me is the ajax re-rendering when using Spring MVC and JQuery.
Let's imagine that I have defined a complex form in my people.jsp view:
<c:forEach var="person" items="${people}">
<table>
<tr class="trPersonClass">...</tr>
<tr>...</tr>
</table>
</c:forEach>
And I have a refresh button below. When the refresh button is clicked I want with ajax the people to rerender.
function refreshButtonClicked() {
$.ajax({
type: "GET",
url: "ajax/loadPeople.do"
}).done(function( msg ) {
//WHAT SHOULD I DO HERE???
}
});
So what I should do there? I have already defined how the people rendering should like with the c:forEach tag in my jsp. I don't want to repeat it again. I don't want to duplicate user interface code at both places - in the JQuery done callback and with JSP tags in my views. This is error prone in my opinion.
Please explain me kindly what I am missing here.
First of all, Spring MVC is very flexible. You can have backend handlers that return HTML generated by a view engine, you can have a handlers that returns JSON/XML/ProtocolBuffers/etc. and use client side rendering engines like Mustache etc. to display the page in the browser, or you can combine the two in the same application.
If you want to generate HTML on the server, Spring MVC allows you to use different template engines to do that. You can use JSP, Freemarker, Velocity etc. In order to do that, it uses a ViewResolver abstraction, and in your code you only have to deal with the ModelAndView API.
More details on ViewResolver can be found here: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html
Based on your question it sounds like you have a backend that use JSP to create the html server side. In order to update only the table and not reload the entire page when a user clicks a refresh button, you could for example have a handler that returns only the html table like so:
#RequestMapping("/table")
public ModelAndView renderTable() {
List<People> people = peopleService.findAllPeople();
return new ModelAndView("/people", "people", people);
}
I'm also assuming you have another handler that returns the main page where the table is embedded via ajax.
<body>
...
/* Content of div will be populated via ajax*/
<div id="myTableContainer" />
...
</body>
The javaScript for this would be something like:
$(function() {
var myTableContainer = $("#myTableContainer");
var renderTable = function(container) {
$.get("/table", function(data) {
container.empty().html(data);
}
};
/* This is called on document ready */
renderTable(myTableContainer);
/* Use the same renderTable function when the refresh button is clicked */
$("#refreshButton").click(function() {
renderTable(myTableContainer);
});
}
Basically, I see 2 options:
Always load the table using ajax, even on the first rendering (table creation code only in your javascript function)
Modify ajax/loadPeople.do to return an already rendered table instead of a Json list. You could then factor the people table rendering code in a JSP Tag file or use some templating library (tiles, etc.) to reuse that JSP fragment.

Categories