jquery hide a div thats loaded by jquery - javascript

I'm creating a website and use jquery to post a form.
When I press the submit button a jquery function posts the form to a php file.
The php file creates a result error or success. The result is echoed by the php file
and jquery file outputs the echo using the .html() method.
I call the html output #result.
So my question is how do I hide the #result using jquery. This has to happen after 5 seconds.
This works fine when #result is loaded with the page. But not when #result is loaded like is said above.
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);

I think the easiest way would be to always have the empty result div in your html and just keep it hidden. This way whenever you get a result from the AJAX you can just change the html, show it, then slide it up again.
$("#result").html(AJAX RESULT);
$("#result").show();
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
This will change the html of the div then show it. Then hide it after 5 seconds.

You can use $.ajax with the success callback option or use .done() method. Example:
$.ajax({
url:"http://someurl/",
success: function(data){ $('#result').html('success').show(); },
error: function(data){ $('#result').html('error').show(); }
}).done(function(){
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
})

Thing is #result is sometimes dynamically added to DOM, and jQuery functions are usually loaded when document is ready, to solve this issue you must listen to DOM changes. If for some reason you're not using AJAX or need another approach, you could try this:
function hideMsg(){
// Hide dynamically added div
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
}
// Listen DOM changes
$('.document').bind("DOMSubtreeModified", hideMsg);
In order for this to work, you must change .document by your document wrapper (where your message will be displayed).
jsFiddle example: http://jsfiddle.net/laelitenetwork/GUxgX/
Cheers.

Related

JavaScript - Wait until DOM modification within AJAX callback has been completed

So, I have the following code:
$(document).ready(function(){
//Retrieve menu html
$.get('/modules/menu.php', function(data) {
//Load menu html
$('main#main').prepend(data);
});
//Initialize Menu
menuInit();
$('#menuToggle').click(function() {
$('#main_menu').fadeToggle();
});
});
menuInit() successfully modifies DOM elements when included in the html directly instead of using $.get(),so the intialization has no issues, however, when using ajax, the intialization of the menu starts before the DOM elements are fully loaded.
I've made a little research and .prepend() does not support callbacks, so not an option.
Surrounding menuInit() with a setTimeOut() with 100 ms works, but it will most certainly fail with slow connections, I need something more dynamic.
Just put the rest of the code inside the callback so it executes after the data has been added to the page:
$(document).ready(function(){
//Retrieve menu html
$.get('/modules/menu.php', function(data) {
//Load menu html
$('main#main').prepend(data);
//Initialize Menu
menuInit();
$('#menuToggle').click(function() {
$('#main_menu').fadeToggle();
});
});
});

Javascript: change CSS element if jquery GET failed

I have a Javascript in my header that calls an external server to retrieve some information, like this:
$.getJSON("https://domain.tld/json/", function (something) {
var results = //stuff that formats the result, not relevant here;
window.$info = results;
}).fail(function(){
// here's where I need the code to make the warning appear
});
Then in the body I have a warning that should pop up in case the GET request failed:
<div id="warning">Warning text</div>
Problem: the javascript is in the header and I can't change the "warning" div because it has not been created yet.
If I use document.getElementById("warning").style.display='block'; I get an error message saying it is null.
So how do I use the .fail() part of the jquery GET function to make the warning div appear (that is created later) in case the GET function has failed? Or is that not possible? And some 'solution' I tried (don't remember what exactly) even delayed the loading of the whole page. I'd like to avoid that as well.
Thank you for helping me out.
You should hide your html element initialy
<div id="warning" style="display:none;">Warning text</div>
And you can call show() method to display hidden element when get request failed
$("#warning").show();
Your javascript is trying to execute and look for things before the DOM has loaded. You can solve this problem by making sure your javascript only fires when the DOM is ready. In jQuery you do that like this:
$(document).ready(function(){
//your code here
});
The native javascript version of this is much more complicated so I won't post that here. However you could also wait for the entire page to load before executing the code like so:
window.onload = function(){
//your code here
}

extend jquery load() function to show spinner inside div

is there a way to alter .load behavior so that it load a spiner inside any div that is loading data ?
example
<div class='content lside'></div>
<script>
$(document).ajaxStart(function() {
$('body').append('<div class="notice" style="position:fixed;top:40%;left:30%;z-index:99999;"id="loadingspin">loading</div>'); });
$(document).ajaxStop(function() {
$('#loadingspin').fadeOut().remove();
});
$('.content').load("<?=base_url();?>booking/<?=$day?>");
</script>
i use above script.
but what i actually want is that when ever ajaxstart the content of $('.content') is replaced with spinner until it finish loading the new content.
so is there a way i can extend .load to do that by it self and replace the ajaxstart,
so where ever $(div).load() is called a $(div).html('spiner'); is fired.
if not, is there a way .ajaxstart can reference the div that the content will be loaded into ?
please note: im currently using .ajaxstart and .ajaxstop in my header script in all my webpage to handle showing the spinners in general, but i want to replace it/extend it with div specific solution that would still work on any page without further editing into each and every ajax request.
thanks
probably something like this should do the trick. Override jQuery's prototype and save the old function.
(function(){
var oldLoad = jQuery.fn.load;
jQuery.fn.load = function( url, data, complete ){
/*
* do your stuff
*/
oldLoad.call( jQuery, url, data, complete );
}
})();
That changes the globally available jQuery.load() method for the whole page so »your stuff« should be executed even if other scripts call that method, a least after your re-definition of that function is parsed.

Execute $(document).ready() after $.load(), is that possible or is there an Alternative

I have page with a form and a table (to show results of the saved data using the form).
The form uses ajax to submit the data, data saved and the table should be reloaded afterwards.
The problem is that the table (which is loaded using AJAX($.load)) is loaded after the execution of $(document).ready(). which implies that the table does not have the required functionality.
Is there any approach where i can postpone the execution of $(document).ready() until the AJAX finish its loading, or shall i use a complete different approach like using iframe?
below is an example of my problem:
$(document).ready(function(){
//some code here that needed for the html in table.html e.g. datepicker, chosen, jqueryui, etc
});
<form>
//Inputs with a button to submit using ajax, where the result is displayed using table.php
</form>
<div id="tableOfContent"></div>
<script>
$('#tableOfContent').load("table.php");
</script>
You can do
$('#tableOfContent').load("table.php",function(){
//completed load actions here
});
But you should note that if you load images, they will not be loaded yet. If that is the case, you can make the contents of table.php initially hidden and do the same again inside for $('#tableOfContent img').load(). This would work for 1 image; multiple images is a bit more complicated, but feel free to ask if that is what you are looking for :)
You can delay the ready event using jQuery.holdReady():
$.holdReady(true);
// Do your custom stuff... the document may already be loaded.
$.holdReady(false); // Now the ready event will fire as soon as the DOM is loaded.
See http://api.jquery.com/jQuery.holdReady/
document.ready is called when the HTML of the page has finished loading, there's no two ways about it.
What you can do, however, is use live binding, which will attach handlers to elements that are not yet on the page.
Example:
$(".datepicker").live("click", function() {
$(this).datepicker();
})
Updated for jQuery >1.7 (this is also faster)
$("#tableOfContent").on("click", ".datepicker", function() {
$(this).datepicker();
})
Load the table data from within the ready function and use the complete event of the load() function to call the remainder
$(document).ready(function() {
// click bindings etc ..
$('#tableOfContent').load("table.php",function() {
// things to do once the table is loaded
});
});
load() documentation
$(document).ready() should be used for scripts that should execute, well, when document is ready.
If you need to execute something after an ajax call, you may write everything within a function and call it with the ajax callback.
function what_i_need() {
// bla bla
}
<script>
$('#tableOfContent').load("table.php", {}, what_i_need);//code had syntax error; '{)'
</script>
I'm not sure. Plus, you can call the function when document is ready too.
$(document).ready(function(){
what_i_need();
});

jQuery Ajax Loader

Greetings,
I would like to know what should I do to make appear a ajax loader...
actually I am calling a function in ajax... everything is going well
here is how it's being done
$('#txtEmail').blur(function()
{
$.post("ajaxAvailability.aspx",{ email:$(this).val() } ,function(data)
{
if(data=='false')
...
Now I would like to have a loader so I done it like this:
$('#loader').ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
This should be working? what is happening is that I am getting an exception inside the jquery.js....
-thanks in advance
I usually do this in my code:
$('#txtEmail').blur(function(){
var value = $(this).val();
//display loader image
$("#indicator").html("<img src='PATH/loading.gif' alt='' /> Sending...").show();
$.post(URL,
{ email:value },
function(data) {
$("#indicator").empty().hide();
//...
});
)};
In above code, the animated image will appear inside DOM element with id="indicator". After AJAX request completed, I emptied the container, then hide it. Adjust this according to your page element.
My another code use jQuery blockUI, usually when submitting form, to prevent double submit. Check the web for the usage example.
Greetings, for everyone
The solution for this issue is correct the jquery-1.3.2-vsdoc2.js file
on the ajax function there are f parameter, this should be replaced into callback

Categories