Loading screen while Servlet loads - javascript

I have this JSP where I select certain parameters and hit "submit" button, after clicking "submit" I am calling a JavaScript function as below
<body>
<input type=button class="button" id = "submit" value="Evaluate"
onclick="JavaScript:return evaluateFunction()">
</body>
and in the evaluateFunction() I am collecting all the parameters and call a new Servlet in new popup window as below:
<script>
function evaluateFunction(){
var win = window.open('ConfirmEvaluate?parameters,'mywindow','width=600,height=500,titlebar=no')
}
</script>
Now the issue is ConfirmEvaluate servlet takes some time to get the data from database(around 15-20 secs based on size of input) and displays the data in the forwarded JSP(say userdata.jsp)
Now I want to display a loading gif or screen in that 15-20 seconds while the Servlet loads the data from database.
How can I proceed, any help would be appreciated.
I have already gone through some similar questions in SO but none of them is having a specific answer.

You have to use AJAX. Servlet requests like the one in your example are synchronous. Which means it will wait until the processing finishes then do the next activity.
With an AJAX request you can send the request and then do something else without having to wait for it to finish processing, because it is asynchronous.
The way i would approach this is in the following way:
You get the user details in ConfirmEvaluate, and redirect the user to userdata, then once the user is on the page do the AJAX request to fetch the information that takes a long time to process. When the request is made you can show a loading icon but when you get a response from the AJAX request, you can hide this loading icon. Check out this brilliant post on how to make AJAX requests with servlets
I had to implement something like this recently, here is some example code:
<script>
//when page loads, the ajax request starts
$(document).ready(function() {
$(this).scrollTop(0);
getposts(username);
});
//ajax request that will show and hide the loader depending on response
var getposts = function (username) {
var params = {
user: username
};
$.get("../GetUserFeed",$.param(params),function(responseXml) {
$("#user-feed").append($(responseXml).find("feed").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
$('#logo-loader').hide();
if(isBlank(responseXml)){
$('#logo-loader-completed').show();
$('#logo-loader-image').hide();
}
});
};
</script>

Related

update ajax on browsers back & refresh button is press

Its my first web application building with jsp , jstl using ajax as to make music player play throughout the site. i have many ajax req in single page . when i click on that its works all fine but when ever i refresh it takes me to blank content page in this code "Djpage.jsp" with out any content as requested in ajax i know as for url it will show but i researched a lot and tried but its not working and when i click button it does not respond only url is changed .
Need help and explanation how do i achieve this -
Show ajax data whenever refresh button is trigger.
Forward and backward button should work and show the ajax content.
Hope you get My problem
Below is on of my ajax req code -
$('li.box').on('click', function(){
$(this).children("form").submit();
var form = $(this).children("form");
var url = 'Djpage.jsp';
var Djname = $(form).children('input[type=hidden][name=inputName]').val();
$.get(url,{inputName:Djname},function(data){
$("#cssSlider").hide();
$("#tabscontainer").hide();
$("#dj_loard").html(data);
$("#dj_loard").show();
var newTitle = $(data).filter('title').text();
document.title = newTitle;
window.history.replaceState({html:"Profilepage.jsp"},null, url);
});
});
You can call functions (to make ajax request) on page load in order to fetch corresponding data of each section.
For e.g.,
$(function(){
// functions to be triggered on page load
abc();
xyz()
});

How can I interrup slow ajax request, running in background

The situation:
User visit some fast loading page, that makes an AJAX async request to some slow PHP script, that loads, for example, for 30 seconds
After 3 seconds user clicks some link to go to another fast loading page, but browser waits 27 seconds to finish AJAX request to slow script, and only after that starts to load next page
How can you solve this problem? How to tell web server to interrupt processing the request, started with defined AJAX call?
PS. abort() is not the solution
PPS. The code example: my page includes filter of shop products, that loads longer that other page components. After first load filter is cached - next times it loads fast. So when page loads, I don't show filter, but add a JS, that calls current page again using AJAX, adding some parameter (SHOW_FILTER). If page receive this parameter - it shows filter...
<div id="catalog_filter_container">
<?if($_REQUEST['SHOW_FILTER'] == "Y"):?>
... filter code here ...
<?endif;?>
</div>
<?if($_REQUEST['SHOW_FILTER'] != "Y"):?>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "<?=$APPLICATION->GetCurPageParam("SHOW_FILTER=Y", array("SHOW_FILTER")); // get cur URL with adding param SHOW_FILTER=Y ?>"
})
.done(function(html) {
$("#catalog_filter_container").append($(html).find('#catalog_filter_container'));
});
});
</script>
<?endif;?>
If I understand you correctly it is not neccessary to have an ajax-call because the page is reloaded anyway. This seems like something you can do server-side only (with sessions).
Something like this: (If the thing you want to achieve is store a value to filter when filter not set and display the value from filter when it is set)
<?php
session_start();
?>
<div id="catalog_filter_container">
<?if($_REQUEST['SHOW_FILTER'] == "Y") {
$_SESSION['filter_content'] = 'bla bla bla';
}
else {
echo $_SESSION['filter_content'];
}
?>
</div>
Try using a cron job to run the queries separate from page loads and cache the results on the server. Then have your AJAX request return the cached content.

Sending dynamic POST data with Javascript

So basically, I'm trying to send some data to a remote PHP page, via POST, with 4 static parameters and one random parameter, a number.
So far what I have done is created an HTML page with a form with 4 hidden fields and 1 empty field, in which a random number is inserted as the value via Javascript (using Math.random). Now whenever I submit this form, it takes me to the remote PHP page, and so I have to click back again (in the browser) and then submit.
So, I decided to load this form in an iFrame in another HTML Page, so after clicking submit, I can just hit refresh, and then submit again.
I want to know, is there a way I can use Javascript in the parent HTML to automatically submit the form in the iFrame, then create a new random value and submit it again?
Here is my code so far
a.html
<html>
<body>
<form method="post" action="http://awebsite.com/remotefile.php">
*some hidden fields with the static values*
<input type="text" id="mytext" name="mobile_no">
<input type="submit">
</form>
<script>//don't remember the exact code, use javascript to generate a random number which is put in the value for mytext via getElementById</script>
</body>
</html>
now this was the form which was to manually send data to the server
this is to load an iframe:
b.html
<html>
<body>
<iframe src="a.html">
</body>
</html>
Can I use javascript in b.html to resend the form multiple times, but with the value of mobile_no different each time?
Or can I simply send POST data with the parameters to the server via simple Javascript (or PHP)
You question isn't 100% clear, but it sounds like you want to asynchronously post form data. You could easily do this with a JavaScript library like jQuery without the need for an iframe. First you should add an ID attribute to your form to make it easier to reference in your jQuery code. Then you can attach an event listener to the form's submit event where you can customize the form before submission and handle the response
$('#myForm').submit(function(e) {
// prevent default form submit action from occuring
e.preventDefault();
// load values need to make AJAX request
var method = $(this).attr('method');
var action = $(this).attr('action');
// Process Ajax request
$.ajax({
type: method,
url: action,
dataType: 'html',
data: $(this).serialize(),
beforeSend: function() {
// generate and assign per form submit random number
// show loading gif
},
success: function(response) {
// AJAX POST success, insert the HTML response into the DOM
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log any errors for debugging here
},
complete: function() {
// Post completion tasks, such as hide loading gif
}
});
});

Is it possible to get php echo/response to Ajax without posting through Ajax?

Ajax parsing, wondering if it is possible if i post a form with text and images through an html form. And just getting the response back through Ajax?
Steps
1.) Form is in html and submit button in html
2.) Form submitted to php, and it runs through verifying/Uploading text and images.
3.) Any echos from the php is received through AJAX.
I am not sure if its possible to do so. Thanks for your time.
Javascript
$("button#submitbutton").click(function () {
$.ajax({
url: ("submitlisting.php"),
type: 'GET',
dataType: "text",
success: function (data) {
console.log(data); // e == result from the ajax call.
$("p#result").html(data);
}
});
});
use a hidden iframe as target for the form
<form target="form_result"><!-- input elements --> </form>
<iframe name="form_result" style="display:none;"></iframe>
Then after form is submitted, check the content of the iframe to read the response.
No. Not in the way you're thinking. The server responds to a request and the cycle ends there. If you submit a form, that is one request, and the client cannot listen to arbitrary requests sent by the server. To obtain the functionality that you are thinking of (seeing some sort of progress as the user is uploading a file, for example), you would need to do everything by AJAX.
A simplistic way is to use some sort of AJAX file uploader (blueimp comes to mind: https://github.com/blueimp/jQuery-File-Upload), and then poll the server for progress updates using AJAX.

Greasemonkey doesn't execute again after form prints result

I'm using greasemonkey to manipulate a form on an existing web page. (autofill)
The action attribute of the form is itself, once submitted it prints a success message above the submit button.
What I'm trying to do is, once the form is submitted - I want to redirect the browser to another page. But this doesnt work with greasemonkey. Nothing happens.
I wrote a code to detect when the page is submitted, but doesnt work after the form is submitted.
getData("goingback"); //pulls the goingback data from database using ajax
if (goingback == "yes") {
window.location = "index.php";
} else {
//business as usual
// manipulate the form and get it ready for submission
sendPost("goback","yes"); // this function sends data to a php to be handled via ajax
//ajax stores the data in database
//the form is submitted using a timer and .click();
var submission = Math.floor(Math.random() * 10000) + 5000;
setTimeout(function() {
$('button[value="submit"]:first').click();
}, submission);
}
How can I achieve this?
Thanks in advance
The question is not clear; we might need to see the actual page itself. But, it sounds like the page is submitting the form via AJAX, and not a full post.
In that case, your script won't refire. Instead, monitor the page for the success message. Here's one way:
Suppose the success message is like this:
<div id="post_status">
<h2>Some one set us up the (data) bomb!</h2>
</div>
where the <h2> is added after the form posts.
Then this code will redirect after the post happens:
var postChkTimer = setInterval (checkForPostDoneNode, 200);
function checkForPostDoneNode () {
var postDoneNode = $("#post_status h2");
if (postDoneNode.length) {
window.location.assign ("index.php");
}
}
There is no need for that getData("goingback") or
sendPost("goback","yes"). Also that looks like it's setting goback but checking goingback -- which could be a problem. Although it is not the problem causing the behavior as described in the question.

Categories