I am returning data from a php file using ajax. But it would look good if a loading display came up, like an animated gif or something. I have had a go using text but noting shows up. Is there a better way of doing it than I have.
function small_loader(t){
if(t === 'show'){
$('#sub_menu').html('Loading');
}else{
$('#sub_menu').html('');
}
}
function loadtools(t){
var tools = 'tools/'+t+'.php';
$.ajax({
url:tools,
type:'POST',
beforeSend: function(){
small_loader('show');
},
success: function(e){
$('#sub_menu').html(e);
},
complete:function(){
small_loader('hide');
}
});
}
At the moment the php file just has a for loop on it echoing out numbers with kine breaks for testing purposes. This does work if I take the small_loader function off. Why is this?
You set #sub_menu to 'Loading...' then put the AJAX stuff there, then at the end overwrite it with '' when you disable the loader, overwriting the ajax response.
Try using a different div for the loader, and maybe hide the #sub_menu and display it when it's finished.
You should add your loader in your HTML (at the right place, say beside the button launching the ajax request), hide it in css (display:none), show it before sending your request and hide it when response comes back :
function loadtools(t){
var tools = 'tools/'+t+'.php';
$.ajax({
url:tools,
type:'POST',
beforeSend: function(){
$("#your_loader_wrapper_id").show();
},
success : ...,
error : ...,
complete: function(e){
$("#your_loader_wrapper_id").hide();
$('#sub_menu').html(e);
}
});
}
Related
I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page.
$.ajax({
type: 'GET',
url: '/index.php/content/generate_search',
data: {
search: input.val()
},
beforeSend: function() {
window.location.href = '/index.php/content/search';
},
success: function() {
$('.hero h1').text(input.val());
}
});
To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. (I cannot find the implementation in the jQuery source, but I will come back with a link).
The easiest and probably best way of doing it, since you're already using jQuery is by:
$( function() {
// your code here
} );
which is a shorthand for
$( document ).ready( function() {
// your code here
} );
EDIT
Ok, so as I promised, I came back with the implementation of document.ready. You can find it here, on GitHub. Here is a permanent link to the current version of the file.
Try this:
$(document).ready(function(){
//Your code
});
onload is used for executing code on pageload
window.onload = function() {
// your code
};
This code:
beforeSend: function() {
window.location.href = "/index.php/content/search";
},
… is causing the browser to leave the page and load a new one before it sends the Ajax request.
Consequently, the Ajax request gets cancelled. If it didn't, then there would be no JavaScript waiting to receive the response.
If you want to visit /index.php/content/search and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search. A page you've just left can't run JavaScript on the next page.
using ASP .Net MVC 4.0 , vs10 , MSSQL 2008
I have a stored procedure, which is executed in one of my page. it generally takes 30 to 50 second to execute. I want to show a alert dialogue where an gif image will be loaded during this process time. I am executing stored procedure with sqlcommand. The process started on clicking Process button. after finishing the process, the page returns another view.
I have poor knowledge of javascript, so please show me a simple way.
EDIT:
Is it possible to show an image on buttonclick an do other codebehind process?
Like:
<script type="text/javascript">
function showImage() {
document.getElementById('Processing').style.visibility = visible;
}
</script>
<div id="progessbar">
<img alt="Processing" src="../../Images/Processing2.gif" id="Processing" style="visibility:hidden"/>
</div>
It will be difficult to accomplish what you're trying to do in a traditional MVC fashion since the request takes a long time. This is better accomplished using AJAX which processes your request asynchronously. I recommend also using jQueryUI dialog or any modal to show a progress indicator, or even any custom JS.
I like jQuery BlockUI personally to create the modal for me but that's just a preference.
/** Using a wrapper to show/hide the progress indicator.
Swap the blockUI with any library or custom JavaScript for displaying the progress indicator.
*/
var showProgress = function() {
$.blockUI({ message: '<img src="progressImage.gif" />' });
};
var hideProgress = function() {
$.unblockUI();
;}
/** Trigger to submit the form */
$('#submit').click(function() {
/** Show an indicator before making an AJAX request*/
showProgress();
$.ajax({
url: '/someEndpoint',
data: $.toJSON({/* some JSON param */}),
type: 'POST',
dataType: 'json',
timeout: 50000 /** Override timeout in ms accordingly */
}).done(function(data){
/** Remove the indicator once the request has succeeded and process returned data if any. */
hideProgress();
});
return false;
});
Use ajax for your process. It ll make the parallel processing for "showing gif" and completing your desired code.
You can use JQuery-AJAX with page methods this way: [1]: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
or you can try simply this
var actionURL = "(Your disired action e.g /index.jsp)"
$.ajax({
cache:false,
url: actionURL,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
$("#progessbar").show();
//Here you can write any code to execute before the action like gif loading etc
},
success: function( data ) {
alert("Success Conditions");
//"data" is what u gets from your target. You can see by alert(data); here
//Here you can write any code which you want to execute on finding the required action successfully
},
complete: function(){
alert("Complete Conditions");
$("#progessbar").hide();
//Here you can write any code which you want to execute on completion of the required action you given in actionURL
},
error: function(){
alert("Error Conditions");
}
});
NOTE: alerts are just for explanation, you can write your own code also
For this code you have to include jquery plugins. which can be downloaded from their official site [l]: http://jquery.com/
I am not trying to ask for free ride, but I don't seem to know how to do this at all.
My recent posts are about running jobs in the background, but I have no luck in doing that.
So...
User clicks run inside a form and it fires a job.
It takes about 30 seconds to complete the job, returns, and tells Django view function to return HttpResponseRedirect(....).
So while the page is being redirect (it takes 30 seconds to signal "GO AHEAD").... I want to show user like an Ajax loading gif picture.
I don't have Ajax implemented and the system is way too complicated to hack on.
Can we actually do this with javascript? The problem is that it hasn't load any page yet because it needs heavy_work to finish.
result = heavy_work(....)
.... more code ....
return HttpResponseRedirect(go to this page...)
Thanks!
Why don't you use a regular ajax call?
javascript
function do_heavy_lifting(argument) {
$.ajax({
type: 'GET',
data: { argument: argument }, // if necesarry
url: '/heavy_lifting_django_view_url/',
beforeSend: function() {
$('#loading').show();
},
success: function(data) {
...redirect...
},
cache: false
});
}
html
<div id="loading" style="display:none">
<button onclick="do_heavy_lifting('argument');">
Using AJAX is simple: just show a 'loader' animated gif before the actual ajax call, and in 'on_success' response callback to hide the loader gif.
Bu without AJAX - the only solution so far is using iterators - look at this: How to stream an HttpResponse with Django
I am using ajax to allow the user to filter content that appears in a target div (var target).
While the content loads, I show a div containing a loader image ('#loader').
However, when the ajax call is done, IE doesn't re-hide the loader as other browsers do.
It also indentifies the the setTimeout() call (in the ajax callback) as an 'invalid argument'.
If I didn't find this so baffling I wouldn't ask here. Thanks!
CODE:
function run_ajax() {
$.ajax({
url: 'artworks_ajax',
beforeSend: function(){
target.empty();
$('#loader').fadeIn();
},
complete: function() {
$('#loader').fadeOut('fast')
},
data: {
'select' : 'artworks',
'artwork-filter': JSON.stringify(filter)
},
success: function(data) {
target.hide();
target.html(data);
fireMasonry();
reloadMasonry(); // masonry needs reminding how big its div is
setTimeout(
fadeUp()
, 1000); // pause necessary to give masonry time to fix itself in place
}
});
}
There is a semicolon missing at the end here:
$('#loader').fadeOut('fast')
Also, the first argument to setTimeout should be a function, while here you are calling the function and using its return value. Assuming that fadeUp is a free function, it should be like this:
setTimeout(fadeUp, 1000);
If for whatever reason there is still an issue, you can move complete to be after the ajax call like so: $.ajax({ajax_stuff_goes_here}).complete(function() {$('#loader').fadeOut('fast');});
I have a jquery ajax request in my website page, and every page i need to post this request to server to get the status. But it have a issue: after i open the page in browser, before this request return the data, my page all link can't works, they can't click.But it render normal. so anybody have a solution for that? such as: make the page load this script after page loaded or other.
$(function(){
var login_status;
$.ajax({
async:false,
url:<%= url(:login_status_header_session, :from => from_uri).to_json %>,
dataType:"html",
success:function(data, textStatus){
login_status = data;
}
});
if(login_status) {
$(".loginDetails p .login_status").html(login_status);
} else {
$(".loginWrapper").remove();
}
});
this is the login_status_header actin:
self.headers["Cache-Control"] = "no-cache, must-revalidate"
self.headers["Expires"] = "0" partial "session_header",
:format => "html"
First, remove the async:false, line. This way the interface will keep responding while the AJAX request is being processed. Second, move your checking of the result into the success function - otherwise it runs before the request finishes, and so login_status hasn't been set yet (and thus defaults to null, which is treated as false).
$(function(){
var login_status;
$.ajax({
url:<%= url(:login_status_header_session, :from => from_uri).to_json %>,
dataType:"html",
success:function(data, textStatus){
login_status = data;
if(login_status) {
$(".loginDetails p .login_status").html(login_status);
} else {
$(".loginWrapper").remove();
}
}
});
});
Without more information I can only guess, and my guess is that since you're using async: false, the interface is not responding. Is there a reason for doing the request synchronously? If not try removing async:false and see if that works.
Uhm... without examining your code in too much detail, if this is supposed to occur at soon as the page is loaded, why not just put it on the server side, and generate the proper HTML in the first place? i.e. do it with PHP or whatever you're using and forget the AJAX?