i have pagination links echoed with a for loop like this '<< < > >>".
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>< </a>"
somewhere within my codes i set the $currentpage using GET request:
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])){
$currentpage = (int)$_GET['currentpage'];
}else{
$currentpage = 1;
}
//the offset of the list , based on current page
$offset = ($currentpage-1) * $rowsperpage;
and i have a session variable to hold search criteria selected by the user while he navigates the page links. The logical error i get is when user clicks any of the pagination link, the session variable wipes out and table displays without the search criteria.
After intensive research i figured out i can use ajax but am confused on how to arrive my goals. THis is what i tried doing. please some help will do.
$('#pglink).click(function(e,$prevpage){//***i need to pass the current page parameter for clicked link
e.preventDefault();
var pgNo = $prevpage;
$.ajax({
url:"file.php",
type: "get",
data:{
currentpage: pgNo }
});
});
Related
I am working on a platform, with comments, messages etc...
Surprisingly, I can't find the answer anywhere!
I'm trying to keep the same position of the page after a post method, and when I return a jsp from the controller.
The problem is, whenever I send a message for an example, or post a comment, the page returns, but returns in the top position which is annoying and ineffective.
How can I keep the page and scroll at the same position after returning or redirecting from the controller?
I'll post some example code:
#RequestMapping(value = "/{recipient}", method = RequestMethod.POST)
public String chatPost(#PathVariable("recipient") String recipient, #ModelAttribute("message") Message message, Model model, Principal principal) {
Date date = new Date();
message.setCreationDate(date);
Profile recipientObj = profileService.getProfileByUsername(recipient);
messageService.sendMessageTo(message, recipientObj);
return "redirect:/message/" + recipient;
}
I am assuming that the button click is doing an HTTP post to the server. In order to avoid the full page load, you will need to use Javascript on the web page so that the communication to the server is done asynchronously. Based on the response from the server, your javascript code will need to update the page appropriately. This should not affect the positioning of the web page as technically you never left the page.
Before you send the request, save the current scroll position in session storage using js. Then, when the view reloads, use js to retrieve the value from session storage and assign it to the scrollTop property of the document or body/div element.
Note that if you load this js code when the whole document is ready you'll probably see the initial state (scrollTop = 0) before the retrieved value is setted. So, this block of js code must be executed as soon as the element to be scrolled exists.
I cobbled together a js script that maintains page position and does so per page. I jus take the full location href, strip out colons and slashes for good measure, then use that as part of the key in session storage.
<script>
$(window).scroll(function () {
let pageName = location.href.replaceAll('/','').replaceAll(':','');
// console.log('scrolled ' + pageName);
sessionStorage[pageName + '_scrollTop'] = $(this).scrollTop();
});
$(document).ready(function () {
let pageName = location.href.replaceAll('/','').replaceAll(':','');
if (sessionStorage[pageName + '_scrollTop'] != "undefined") {
// console.log('restored ' + pageName);
$(window).scrollTop(sessionStorage[pageName + '_scrollTop']);
}
});
</script>
Use anchor links and redirect the post back to "mypage.jsp#myAnchor"
<a name="myAnchor">Important Section</a>
<section class="important">Javscript is cool!</section>
I want to pass into a java bean a value from listbox prior to submit--in that, user selects a new listbox value and a table with dynamically update based on the value selected--in that, the value is used by a bean function that creates a new List based on the value and is what is used to populate the table.
It is a little table displayed to the right of the form items and is meant to be informational only.
It is jsp page and I do have a bean with the listbox set/get functions.
I am confused by ajax examples as they seem to require a url. Can I put url to the same page? It also seems to require the url to point at a page or xml file. I just want the listbox value in the form from the present page.
I am not using php by the way (there are a lot of examples of php use out there).
I am not using jquery.
I am using jstl/el.
I do understand jstl/el and bean stuff is server side and javascript is client side.
I am willing to adapt my page to accommodate a working idea.
Cheers,
David
Example:
I was asked for some code, so here is my feeble attempt. Imagine a function in a jsp called stuff.jsp. It has in its function a where it grabs the listbox value and puts it in a variable called project_acronym. It then tries to pass it with ajax as a parameter. I then in the createTable function try to grab it into a java bean value called acronym and for this test case I simply try to show its value with an alert.
This does not work. All I seem to play with with responseText and responseXML, which are just returning the web page source code of stuff.jsp. I want the parameter I am passing, not the source code.
function init() {
document.add_user_roles.acronym.value = project_acronym;
alert("project acro at client is: " + project_acronym);
// alert happily shows the value.
var url = "http://myserver.com/apps/myappstuff/stuff.jsp";
var params = "acronym=" + project_acronym;
var xmlhttp = false;
try {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
//Create a asynchronous GET request
xmlhttp.open("GET", url + "?" + params, true);
//When readyState is 4 then get the server output
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
//document.add_user_roles.getElementById("DOMTarget2").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
// yuck, this shows the stuff.jsp source code
}
else {
alert('Something is wrong !!');
}
}
};
xmlhttp.send(null);
} catch(e) {
alert(e);
}
tableCreate();
function tableCreate() {
<% String acronym = request.getParameter("acronym"); %>
alert("acronym: " + "<%=acronym%>");
... code to make table here
It is not what I wanted to do, but I made another page called rolestable.jsp that has the function to create the table and has access to the same bean as the first jsp page, but set to session="page". I then have the first jsp page call a function when the listbox change event occurs that calls the new jsp page with one parameter (i.e., acronym=theselectedvalue). The first page displays the table in an iframe. I then put a meta refresh in the second page so that it updates every 15 seconds to show any changes that might occur to it. I hate this because the meta refresh of course makes the page disappear and reappear in a very notable fashion.
Can ajax fit in this scenario with minimal adjustment?
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);
}
I want to pass a javascript variable to my servlet, where I need to use it.
In javascript, the variable count returns the rows of my table and I can show count in the jsp, using $('#counter').html(count); , but I cannot pass count's value to my servlet. I tried document.getElementById("hiddenField").value=count; but it doesn't work.
Javascript
<script>
var count = 3;
$(function() {
$('#counter').html(count);
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
});
document.getElementById("hiddenField").value=count; // ???
</script>
JSP
Count: <span id="counter"></span> <%-- it works --%>
<form method="post" action="newteamsubmit">
...
<input type="hidden" id="hiddenField" name ="countRows" />
<input type="submit" name ="button1" value=" Submit " />
<input type="submit" name = "button1" value=" Cancel " />
</form>
Servlet
String cr = request.getParameter("countRows"); //I' ve tried also to convert it
// to int, but that's not my problem, since I cannot pass the value as a start
I've spent many hours, trying to figure out how I can access a javascript variable in jsp, but I haven't found any solution.
Thanks in advance.
The count is computed each time the add button or the delete button are clicked. But you only set the hidden field value once, when the page is loaded (and its value is thus hard-coded to 3).
You must set it, as you're doing for the #counter element, in your click handlers:
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
Also note that you're repeating exactly the same code in two click handlers here. You should do that only once, for the two buttons:
$('#addButton, #deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
or even, since you're using jQuery:
$('#addButton, #deleteButton').bind('click', function() {
count = $("#dataTable tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
document.getElementById('hiddenField').value is not set because it is outside your document.ready. Put it inside your click handler.
Make sure of 2 things -
There is only one element with id "hiddenField" on your page.
Make sure that the following code
document.getElementById("hiddenField").value=count;
is after in the page.
Just make sure that js sets the hiddenField after the element has been loaded.
3. check for any JS errors using Javascript console.
Rest it looks good
The main issue here is that you are trying to access from the server, a variable that only exists at the client. To access that variable you have to send it from the client to the server using AJAX to trigger some form of API in the backend. REST, SOAP or XML-RPC are common technologies used for this sort of thing. The server side code is used for generating the UI and providing it with data from a database or such. Commonly the UI is generated only once, and then the client calls the server asking for more data in response to user actions, like clicking a button.
Imagine a table filled with information about books: title, author, publish date etc. This table can get quite large, and traditionally this table will be split up over several pages and possibly a dynamic filter. To save bandwidth and increase the user experience by not loading the entire page from scratch you can use AJAX to ask the server for just the relevant data. Doing so the page updates dynamically and smoothly for the user.
In your case, you can use this technique to update the server every time the user clicks the button.
If however you are really just looking to update a hidden field in a form with a value as the user performs actions, and the server wont do anything with it except show it you can just use javascript.
Remember also that the request variable contains the data you post to the server when you submit the form. The servlet will get the data after the client has posted it, which is after the JSP has generated the page. The sequence of the code execution is JSP -> Javascript -> Servlet.
Hope this helps!
You can use this way:
document.forms[0].countRows.value = counter
Hope this will help you
I'm trying to make a sleek login function here =)
I want the "login experience" to be smooth and seamless, so I don't want the user to "feel" like he/she is being "redirected" and taken back to the same page again.
So the process goes:
User X visits page A
X is not logged in
X presses on Login btn (that lives in a in a div together with the form)
Login fields and buttons fade away
X is logged in and still on page A (without noticing a "redirection")
Thank you for all your answers!
You can use jQuery.load to re-request the same page (which should load the correct content since the session was created). It has support for loading part of the requested document.
Example:
function onSuccessfulLogin() {
$("#content").load(window.location.href + " #content");
}
EDIT: Oops, sorry, I think I misunderstood. I thought page A had content only visible to authenticated users, and you were showing a login form and wanted the correct content to show up once they authenticated.
If you just want the async. login, you can add a submit handler to the login form that submits the form to some sort of login handler script that returns whether their login attempt was successful.
$("#loginform").bind("submit", function () {
$.ajax({
url: "login.php",
method: "post",
cache: false,
dataType: "json", // for example
data: $(this).serialize(),
success: function (data) { // data is the JS object based on the JSON returned
if (data.success) {
$(this).fadeOut();
} else {
alert("bad login: "+data.error);
}
}
});
return false;
});
I solved this using an Ajax login system that reloaded the page after a succesful login. If you don't want to reload the current page, you will need a JavaScript based system to show and hide a logged in state. (although I think that might complicate any further development)
One way that you could accomplish this, would be to use some AJAX and a modal dialog containing the required login fields and the submit button. You can do a slick implementation using a Dojo dialog dijit.