jquery show/hide doesn't wait for completion - javascript

I am trying to periodically:
Fetch data from an ajax call
compare the data to the content of a div
if data != content of the div: hide the div, change data, show the div
Here is my code:
...
<div id="myDiv">old data</div>
</body>
<script type="text/javascript">
$(document).ready( function() {
updates();
done();
});
function done() {
setTimeout( function() {
updates();
done();
}, 5000);
}
function replace(div, content){
$(div).html(content)
}
function updates() {
$.ajaxSetup({ cache: false });
$.getJSON("mywebsite/get_data", function(data) {
if ( $("#myDiv").html() !== data ){
$("#myDiv").hide(400, replace("#myDiv", data));
$("#myDiv").show(400);
}
});
}
</script>
...
The problem is that div content is replaced by the new data before the div is completely hidden, even if the callback function replace() is supplied to the hide() function.
How can make the hide() function to wait for its completion (400 ms in this example) before calling the replace() function?
I also tried with delay() and setTimeout() but it does the same thing.
Thanks

I don't think you need that replace function. Anyway this should work:
function updates() {
$.ajaxSetup({ cache: false });
$.getJSON("mywebsite/get_data", function(data) {
if ( $("#myDiv").html() !== data ) {
$("#myDiv").hide(400, function() {
$("#myDiv").html(data);
$("#myDiv").show(400);
})
}
});
}
SEE JSFIDDLE (without ajax call)

Related

How to call a function in javascript?

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

jQuery hide and show from do not work

I have the following in a event:
function onclickEvent () {
$.ajax({
url: "somePage.html",
beforeSend: function( xhr ) {
$('#Element1').hide("slow",function() {
$('#Loading').show("slow");
});
}
}).done(function( data ) {
$('#Loading').hide("slow",function() {
$('#Element1').show("slow");
});
});
}
First time works well but the second time (second click) in "Done" ajax the loading does not hide, always is visible.
What am I doing wrong?
You hid Element1 first, so you need to show it first on success/done. show() paired with hide() and vice versa seem to base the toggling on precedence. It seems to be the behavior. You may want to further read the documentation of these functions.
<script src="jquery.min.js"></script>
<script>
function onclickEvent () {
$.ajax({
url: "somePage.html",
beforeSend: function( xhr ) {
$('#Element1').hide("slow",function() {
$('#Loading').show("slow");
});
}
}).done(function( data ) {
$('#Element1').show("slow", function() {
$('#Loading').hide("slow");
});
});
};
</script>
<div id="Element1" style="display:block;">
Element 1
</div>
<div id="Loading" style="display:none;">
Loading
</div>
<button onclick="onclickEvent();">Click Me</button>
Using success
function onclickEvent () {
$.ajax({
url: "somePage.html",
beforeSend: function( xhr ) {
$('#Element1').hide("slow",function() {
$('#Loading').show("slow");
});
},
success: function( data ) {
$('#Element1').show("slow", function() {
$('#Loading').hide("slow");
});
}
});
};
It looks like there are couple of things that need to be modified to get this to work the way I think you want it to work.
The beforeSend setting in the $.ajax() function is intended to give you a place to modify the request before you send it. This probably isn't the best place to call the first animation functions.
The animation callbacks and ajax callbacks seem to be causing a race condition -- it looks like it's possible for the ajax request to return while the initial animations are still running, which means that the #Loading element is shown when it should be hidden.
This example assumes that the #Loading element should be hidden by default when the page loads and that the elements should revert to their initial state even when the ajax request fails (always instead of done).
$(function() {
$('#button').on('click', function() {
$('#Element1').hide('slow', function() {
$('#Loading').show('slow', function() {
$.ajax({
url: 'somePage.html'
})
.always(function(data) {
$('#Loading').hide('slow', function() {
$('#Element1').show('slow');
});
});
});
});
})
})
#Loading {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="Element1">
Element1
</div>
<div id="Loading">
Loading
</div>
<button id="button">
Button
</button>
What's happening here is that when the button is clicked, the toggling animations (hide() and show()) are run, then the ajax request is sent as a callback from the show() animation so that the request doesn't go out until the #Loading element is visible.

$.when().then() not working with nested ajax calls

I have been trying to scroll the page to a dynamic div that is created by the an ajax call.
When #divnotifications div clicked (below), I make the first ajax call that adds the Post details, then within this ajax call, another ajax call is made to add the related comments to the div.
The part explained so far works great. Then, I use $.when().then() to scroll to a div item created based on the ajax calls. However, the page does not scroll to the element that was created by LoadCommentsForPost ajax call.
Did I get the logic of $.when().then() wrong?
$(document).on('click', '#divnotifications div', function (event) {
event.preventDefault();
$.ajax({
//other details
success: function (postid) {
$.when(DisplayPostWithFullDetails(postid)).then(function () {
//scroll to the content created by
//LoadCommentsForPost function nested
//inside DisplayPostWithFullDetails
});
}
});
});
function DisplayPostWithFullDetails(postId) {
$.ajax({
//other details
success: function (post) {
//The code to build the div to display the post -- working fine
LoadCommentsForPost(post.PostId);
}
});
}
function LoadCommentsForPost(postid) {
$.ajax({
//other details
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//builds the div to display the comments - working fine
}
});
}
UPDATED CODE
After receiving some feedback, I ended up with the following code. However, it is still not working. It works only if I add some delay to make sure the div is loaded:
$(document).on('click', '#divnotifications div', function (event) {
event.preventDefault();
$.ajax({
//other ajax stuff
success: function (postid) {
DisplayPostWithFullDetails(postid).done(function () {
setTimeout(function () {
var scrollto = $("div[data-" + type.toLowerCase() + "displayform='" + relateditem + "']").offset().top;
$("html, body").animate({ scrollTop: scrollto }, 600);
}, 500);
});
}
});
});
function DisplayPostWithFullDetails(postId) {
jQuery.support.cors = true;
return $.ajax({
//other ajax stuff
success: function (post) {
post = JSON.parse(post);
//display the post details
LoadCommentsForPost(post.PostId);
}
});
}
function LoadCommentsForPost(postid) {
var promise = new $.Deferred();
jQuery.support.cors = true;
$.ajax({
//other ajax stuff
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//this is not ajax
promise.resolve('loadedcomments');
}
});
return promise;
}
Did I get the logic of $.when().then() wrong?
Yes, you need to return a promise from the functions if you want to use the function with $.when:
function DisplayPostWithFullDetails(postId) {
return $.ajax({...
// ^^^^^^
That said, wrapping a single promise in $.when is useless.
$.when(DisplayPostWithFullDetails(postid)).then(function () {
should just be:
DisplayPostWithFullDetail(postid).then(function () {
Did I get the logic of $.when().then() wrong?
No, but you are NOT returning the promise so you can't use the promise functions like .then().
UPDATE:
I use $.when().then() to scroll to a div item created based on the ajax calls. However, the page does not scroll to the element that was created by LoadCommentsForPost ajax call.
For me this means that you need to wait that both ajax calls are resolved.
This fiddle show how it should work emulating the ajax call using setTimeout Fiddle.
Your code may look similar to:
function DisplayPostWithFullDetails(postId) {
var promise = new $.Deferred();
$.ajax({
//other details
success: function (post) {
//The code to build the div to display the post -- working fine
LoadCommentsForPost(post.PostId).then(function() {
promise.resolve();
});
}
});
return promise;
}
function LoadCommentsForPost(postid) {
return $.ajax({
//other details
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//builds the div to display the comments - working fine
}
});
}
Now when you execute the function DisplayPostWithFullDetails it return a promise.
So you can use .then() method;
DisplayPostWithFullDetails(postid)).then(function () {});
or...
var promise = DisplayPostWithFullDetails(postid);
promise.then(function(data){});
Also the major advantage of use $.when() is that you can execute the .then() method when all the promises that you pass to it are resolved.
There are not need to use it when you are waiting for a single promise.

Reload function after Ajax call

I have a plugin raty (http://wbotelhos.com/raty) that is loaded to document.ready, the page content changes at the click of a button reloading a part of the DOM, and the document is not ready "recalculated" and I will not reload all javascript (there are other similar behavior) I tried this solution but without success
function star(){
alert("star");
...code plugin...
}
$(document).ready(function() {
star();
});
$.ajax({
..code..
done: function(creaStella) {
alert("D");
star();
},
complete:function(){
alert("C");
star();
},
});
After call ajax i have alert("star") but i haven't my div populated
Incorrect usage of $.ajax
$.ajax({
..code..
success: function(creaStella) {
//code to populate div goes here
alert("complete");
star();
}
}).done(function(){
//or here
alert("complete2");
});
use success/done as show (or both).
I resolve in this Way..(promise().done)
also form with jquery validate plugin before dosen't works
function star(){
//plugin star
}
$(document).ready(function() {
formJqueryValidate1();
formJqueryValidate2();
star();
});
function formJqueryValidate1() {
//my check
function formJqueryValidate2() {
//my check
}
$.ajax({
success: function(msg) {
$('#myid').html(msg.template).promise().done(function(){
formJqueryValidate1();
formJqueryValidate2();
star();
});
}
}
});

Javascript - Load content, callback and loading

Here is my 'getContent' functions which takes a URL:
function getContent(url, callback) {
var request = new Sys.Net.WebRequest();
request.set_url(url);
request.set_httpVerb("GET");
var del = Function.createCallback(getContentResults, callback);
request.add_completed(del);
request.invoke();
}
What I'd like to do is display a loading image when this is called and then hide it when the callback is complete?
Can any suggest antying?
You can use the jQuery .load() function to load your HTML, then use the .ajaxStart() and .ajaxStop() event handlers to show and hide the loading animation.
Here is an example:
$(document).ready(function() {
$("#loadlink").click( function() {
$("#container").load( "load.htm" );
});
$("#loadlink").ajaxStart( function() {
console.log("start");
});
$("#loadlink").ajaxStop( function() {
console.log("stop");
});
});
$('#selector').html('<img src="loading.gif" />').ajax({
URL: 'myurl',
type: 'GET',
dataType:'html',
success:function (data){
console.log('This has changed');
// data is your html returned/response
},
error: function (){
//this handles errors such as 404,500, etc...
}
});
Whats happening?
$('#selector')//is where the result would be shown this instance <div id="selector">
.html('<img src="loading.gif" />')// adds an image to <div id="selector"><img src="loading" /></div>
.ajax();//well its the ajax call to get the page data
for more information
http://api.jquery.com/jQuery.ajax/

Categories

Resources