After a successful ajax call I m showing an element telling the success status. I need to show it temporarily and hide it after say 10 seconds.
I have a paragraph element with the class set to hide on load <p class="response hide" >Successfully Updated!</p>
The code below does not seem to work as the element does not hide after its shown by adding the 'show' class
function UpdateChangeRequest() {
$.ajax({
url: '/Request/UpdateRequest',
cache: false,
data: $('form[id="RequestForm"]').serialize(),
type: 'POST',
success: function (data) {
$('.divPartial').html(data);
$('.response').addClass('show').removeClass('hide');
setTimeout(function () {
$('.response').fadeOut('fast');
}, 1000);
}
});
}
Any ideas? thanks
You should try to make something like the below in your success callback:
$(function(){
$('.response').hide();
$('#fake').click(function(){
$('.response').show();
setTimeout(function () { $('.response').fadeOut('fast'); }, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="response" >Successfully Updated!</p>
<input type="button" value="click" id="fake"/>
Update
Since you updated you post, I could be more specific:
function UpdateChangeRequest() {
$.ajax({
url: '/Request/UpdateRequest',
cache: false,
data: $('form[id="RequestForm"]').serialize(),
type: 'POST',
success: function (data) {
$('.divPartial').html(data);
// Show the success message
$('.response').show();
// Define a timeout after which fade out the success message.
setTimeout(function () { $('.response').fadeOut('fast'); }, 1000);
}
});
}
what about simple:
$(obj).show().delay(10000).hide();
You may use callbacks.
$(".response").fadeIn("slow","swing", function()
{
(".response").delay(10000).fadeOut("slow");
});
http://www.w3schools.com/jquery/jquery_callback.asp
You code should be working like i mentioned in the comments. I have put them in codepen with minimum changes
html:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<p class="response hide" >Successfully Updated!</p>
<!--- response msg is hidden by default --->
css:
.hide{
display: none;
}
js:
var millisecondsToWait = 1000;
$(document).ready(function(){
//$('.response').addClass('show').removeClass('hide');
$('.response').show();
setTimeout(function () {
$('.response').fadeOut('fast');
}, millisecondsToWait);
});
codepen example: http://codepen.io/anon/pen/bNrGwW
Find your element, show it, add a delay of 10 seconds, and finally hide it. You can chain all these effects/events like that:
$('.response').show().delay(10000).hide();
Try this :-
$('.response').show().delay(10000).fadeOut('slow');
Related
below is my script in that, particular div should be refresh every three seconds. how to add the time interval in my code using jquery and ajax?
<script>
$(document).ready(function () {
$('#data_form').on('submit', function (e) {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success: function (data)
{
scrollDown();
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="row msg_container base_receive"><div class="col-md-12 col-xs-12"><div class="messages msg_receive"><p><a>' + message + '</a></p></div></div></div></div>');
$('#messagee').val('');
},
error: function ()
{
alert('failed');
}
});
e.preventDefault();
});
scrollDown();
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 200);
}
});
</script>
To refresh the div every 3Sec.
You can use "setInterval" function.
And to stop this interval you can use "clearInterval" function.
The simple code is as follows:
var refreshIntervalId = setInterval(function(){
// alert("Hello");
//Your Div's ID
}, 3000);
/* later */
clearInterval(refreshIntervalId);
This code simply calls the alert every 3seconds,so modify the above code and put the div's id to be refreshed.
You can use setInterval javascript function for that. check the code snippet below
setInterval(scrollDown, 3000);
I hope this will help you. Please check below code.
function animatedText() {
$('.text').animate({ opacity: 1 }, 200, function() {
$('.text').animate({ opacity: 0 }, 200);
});
setTimeout(function() {
animatedText();
},3000);
}
animatedText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Animated Text</div>
Use
setInterval(function(){
getMessage();
}, 3000);
setIterval lets you to repeat a function or a code block every n seconds.
I think you should add your ajax call into a function.
function getMessage () {
//Your ajax call here
}
This way the code could be reused more times without repeating it.
Im trying to show a loading div while waiting for an ajax call to complete. I have tried a couple of methods but cant seem to get anything to work consistently.
with my current code it works if i have a break point on the function that shows the div once the ajax is complete.
Fiddle
var https = 'https://www.googleapis.com/calendar/v3/calendars/';
function HideCheckShowLoading(checkId) {
$("#check_" + checkId).hide('slow', function() {
$("#loading_" + checkId).show('slow');
});
};
function HideLoadingShowCheck(checkId) {
$("#loading_" + checkId).finish().hide('slow', function() {
$("#check_" + checkId).finish().show('slow');
});
};
$(document).ready(function() {
$('#get').click(function() {
HideCheckShowLoading(1);
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function(response) {
//do something
},
error: function() {
//do something else
}
}).done(function() {
HideLoadingShowCheck(1)
});
});
$('#get2').click(function() {
HideLoadingShowCheck(1);
});
});
#check_1
{
background-color:red;
}
#loading_1
{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="check_1">Check</div>
<div hidden id="loading_1">LOADING</div>
<button id="get">Get</button>
<button id="get2">Get2</button>
What i would like to happen is,
on the click of a button we hide the check div
we show the loading div
make the ajax call
if successful do something(Reload the contents of the check div)
hide the loading div
show the check div
As said I have tried a few methods that i have found but i repeatedly get stuck with just the loading div shown
Thanks
I believe you may be slightly over-complicating things here. Something simple like this would suffice:
$('#get').click(function() {
HideCheckShowLoading();
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function (response) {
//do something
},
error: function() {
//do something else
},
complete: HideLoadingShowCheck
});
});
If you don't want the HideLoadingShowCheck routine to happen after success or error (standard behavior of complete), you can just move a function call HideLoadingShowCheck(); into your success and error blocks instead of using complete.
When you add () to a function name, it calls it immediately and returns the result. What you want to do is pass the function itself, not the result of the function - and you do that without the ().
There's no need for the $.when (assuming HideCheckShowLoading() doesn't make an ajax call, the jquery animations work differently), and $.ajax returns the promise itself, so you can update your code to:
$(document).ready(function() {
$('#get').click(function() {
HideCheckShowLoading();
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function (response) {
//do something
},
error: function() {
//do something else
}
})
//.done(HideLoadingShowCheck);
.done(function() { HideLoadingShowCheck(otherparams); })
});
});
I would change the showcheck function to add .finish() incase it's still animating from the showhide:
function HideLoadingShowCheck() {
$("#loading").finish().hide('slow',function () {
$("#check").finish().show('slow');
});
};
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.
I have a problem with an animation (fadeIn). It doesn't work after ajax. There is just NO ANIMATION but the content appears.
My code is like:
function ajax(varia) {
return $.ajax({
dataType: "html",
async: false,
type: 'POST',
url: 'index.php?fn=' + varia,
data: { token: "mytoken" }
});
}
Function with ajax works fine...
ajax("login").done(function (data) {
$("body").prepend(data);
}).done(function () {
// The #login have atribute style="display: none;"
$("#login").fadeIn(500);
});
This problem can be resolved with using delay before the fade, but i think it should be fine without this. Why it's not?
Thats probably because JavaScript is an asynchroneus language. What you are experiening is a synchronization issue:
Your ajax is done, you are firing DOM manipulation (prepend()), and imidiately after you fire it you do the fadeIn() but the fadeIn is complete before your data is prepended, so probably you'are calling fadeIn() on an element that doesn't exist yet.
Try this:
ajax("login").done(function (data) {
$("body").prepend(data);
setTimeout(function(){
$("#login").fadeIn(500);
},0);
});
And read this to understand why using timeout 0 is sometimes helpful: Why is setTimeout(fn, 0) sometimes useful?
By wrapping your action with setTimeout function you are basically telling: "wait until everything is done before doing this".
Here's the fiddle: jsFiddle
Did you try to put both calls into the same .done()-Block?
I think this should work:
ajax("login", "html").done(function (data) {
$("body").prepend(data);
// The #login have atribute style="display: none;"
$("#login").fadeIn(500);
});
In this case it should be guaranteed that the two lines of code are executed
successively.
I've made an live example here: http://jsfiddle.net/xLo93d29/
For me it works.
You should use "success" instead of "done":
function ajax(varia) {
$.ajax({
dataType: "html",
async: false,
type: 'POST',
url: 'index.php?fn=' + varia,
data: { token: "mytoken" },
success: function(data) {
$("body").prepend(data);
// The #login have atribute style="display: none;"
$("#login").fadeIn(500);
}
});
}
ajax("login", "html");
May be you can do like this
.done(function (data) {
var $data = $(data).hide();
$data.prependTo($("body"));
$data.fadeIn(500);
});
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/