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
}
});
Related
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>
I am creating a page dynamically which contains a list of hostel's in a particular area, I want tom implement a sidebar filter like that in Flipkart or amazon to refine my search result. How can this be done in java, can someone point me in the right direction.
My thoughts on this are : make a list of checkboxes with different categories and when a particular checkbox is selected, make a ajax call to the servlet which should fire a query with the desired results and display the result back on the page.
Considering you are not interested in using lots of frameworks that do this for you (JSF + Richfaces or Primefaces etc, Spring MVC, Struts 2)
A possible-ugly solution would be:
Your Ajax calls your Servlet and all your work is done there (query etc)
You creates a html-list of components in your servlet (using a custom HtmlUtils to help you create tags and fill with data)
You send back to Ajax using below code
(response is HttpServletResponse) from your doPost/doGet
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
You get this data in Ajax like below and fills a Div content with your filtered result (It uses jquery so you need import jquery javascript)
$.ajax({
type: "GET",
url: servlet-url,
success: function(data){
$("#"+divid).html(data);
},
error: function(req, status, error){
//handle error here
}
});
Is there a way to send ajax requests in a Java program? I was thinking that there might be a jquery library somewhere, but I don't even know if jquery would be something that I should use. I'm trying to get the data from a certain request from a website as shown in this function:
function searchFraze(fraze, page) {
page = typeof page !== 'undefined' ? page : 1;
$.ajax({
url: 'ajax/tradeCsRight.php',
type: 'POST',
data: "search=1&type=10&fraze="+fraze+"&page="+page,
success: function(data) {
$("#itemlist").html(data);
}
});
}
Basically, I want to POST custom data in the data field above to the website (http://csgolounge.com/). Honestly, I don't even know if I should be doing what I'm doing this way, or if I should use some other method.
Also, in FireBug, I can see the contents of the tradeCsRight.php file as seen here (which is my goal, to see the html content of this): http://i.imgur.com/8ACnGbp.png
If I open the actual file in chrome, however, the page and html is blank (http://i.imgur.com/LHtKyUb.png). Can someone tell me why this is?
Let's say there is a JSP which has been rendered to the client. On this Jsp, I created a link, I want this link to make a request to the server and server sends a spring from with command object in it and this spring form gets rendered on the already loaded page on client. I mean I do not want whole page to be loaded. Let's take a scenario like there is link 'update contact details' on my page. Clicking on this link makes an ajax request to the server and spring form is sent from the server such that form is populated with the contact details of the user who clicked the link of 'update contact details'. Basically I want stuff like header and footer not to be loaded unnecessarily every time.
Thanks in advance.
IF you have a link as,
<a id="screenId" href="#">
then add <div id="container"></div> somewhere you want your page, also a js function as,
$('#screenId').click(function() {
$.ajax({
type: "GET",
cache: false,
url: "yourControllerURL",
data: "",
success: function(response){
$('#container').html(response);
}
});
});
with the above ajax call, inside your controller, return your jsp with the command object. The controller code may look something like this.
#RequestMapping(value="yourControllerURL")
public String includeAnotherJSP(ModelMap model) {
model.addAttribute("commandObjectName", commandObject);
return "yourJSPMapping/jspName";
}
After your controller will send the response, you will get the required JSP inside the response and you can then load that into your <div id="container"> using above js code.
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