How to disappear message in 4 to 6 seconds using jquery - javascript

I can display the message using javascript/jquery and i have ajax request but that message is not disappearing after some seconds and i want to disappear it.
My Code
$('#password_change_form').submit(function(e) {
e.preventDefault();
var saveThis = $(this);
$.ajax({
type: "POST",
url: "/changepassword",
data: $(saveThis).serialize(),
success: function(data) {
$(".success-messages").text("Heslo bylo úspešne zmeneno").fadeIn();
setTimeOut(function(){
$(".success-messages").fadeOut('slow');
},2000);
$('#password_change_form').trigger("reset");
},
error: function (data) {
$(".error-messages").text("Zadali jste špatné heslo").fadeIn();
setTimeOut(function(){
$(".error-messages").fadeOut('slow');
},2000);
$('#password_change_form').trigger("reset");
}
});
}),
I have setup a setTimeOut function but its not working i dont kno where is the issue:
Your help needs here!

Aside from the already pointed out simple typo, jQuery has its own delay() function, simply use: $(".success-messages").delay(2000).fadeOut('slow')

You may not need the setTimeout since jquery provides fadeOut which have a signature like this
$(selector).fadeOut(speed,easing,callback)
In the speed you can either provide time in millisecond or slow or fast
$(".success-messages").fadeOut(2000);

setTimeOut should be setTimeout. Thats All.

Could also use:
$(document).ready(function(){
$(".foo_msg").fadeTo(2000, 500).slideUp(500, function(){
$(".foo_msg").slideUp(600);
});
})
mess around with the values to get desired time
also include "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" in your script tag

There's a typo in your code:
setTimeOut(function(){
$(".success-messages").fadeOut('slow');
},2000);
It should be:
setTimeout(function() {
$(".success-messages").fadeOut('slow');
}, 2000);
you can always make use of the Mozilla Developer Network (MDN) JS-reference for looking up details about syntax:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

You can use JQuery delay() and i will do something like this in your case:
$('#password_change_form').submit(function(e)
{
e.preventDefault();
var saveThis = $(this);
$.ajax({
type: "POST",
url: "/changepassword",
data: $(saveThis).serialize(),
success: function(data)
{
var msg = "Heslo bylo úspešne zmeneno";
$(".success-messages").text(msg).fadeIn().delay(2000).fadeOut("slow");
$('#password_change_form').trigger("reset");
},
error: function (data)
{
var msg = "Zadali jste špatné heslo";
$(".error-messages").text(msg).fadeIn().delay(2000).fadeOut("slow");
$('#password_change_form').trigger("reset");
}
});
});

Related

What is the proper way of doing long polling using jQuery and AJAX

I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}

Continue after ajax complete without using the callback

Trying to postpone further processing of script until ajax call is complete without using the callback. Trying something like this, but it locks. How do I do this without locking?
var loaded=false;
$.get(url,function(d){loaded=true;});
while(!loaded) //<--locks here
setTimeout(void(0),100);
//continue script after ajax call is complete
Have you tried with promises?
var jqxhr = $.get( url, function() {
alert( "success" );
})
.done(function() {
void(0);
})
.fail(function() {
void(0);
})
.always(function() {
alert( "finished" );
});
Try this
var loaded=false;
$.ajax({
url : 'your url',
type : 'GET',
async : false, // You need this
complete: function(data) {
loaded=true;
},
});
while(!loaded) //<--locks here
setTimeout(void(0),100);
If you work with jQuery, deferred objects are the way to go. They implement a robust and easy methodology.
However, if you want your script to work, try this:
var loaded = false;
function myfunc() {
if (loaded) {
clearInterval(timeout);
doSomethingAfter();
}
}
var timeout = setInterval(myfunc, 100);
$.get(url,function(d){loaded=true;});

Ajax recursive function work strange

Hello guys here's my code:
var ajax={
chiamata:function(target,url,opzioni){
if (!tools.array_key_exists('caricamento',opzioni)){
opzioni['caricamento']=1;
}
var dati=url.split('?');
$.ajax({
type: opzioni['type'],
url: url,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data: dati[1],
dataType: "html",
success: function(msg){
if (opzioni['caricamento']!=0){
ajax.printLoading();
}
$(target).html(msg);
},
error: function(){
alert("Chiamata fallita!");
}
})
},
printLoading:function(){
var body="#colonnaDX";
$(body).ajaxStart(function(){
$(body).append('<div id="loading"><img src="graphic/IMAGE/spinner.gif"/>Loading...</div>');
})
.ajaxStop(function(){
$('#loading').remove();
});
}
},
//Recursive function
var object={
checkAzione:function(target,url,opzioni,interval){
if (!interval)
interval=60000;
ajax.chiamata(target,url,opzioni);
setTimeout(function() {
this.checkAzione(target,url,opzioni,interval);
}, interval);
}
}
$(document).ready(function(){
object.checkAzione(
'#colonnaDX',
'someactions.php',{
'caricamento':0
},
10000
);
})
I'll try to explain the problem as better as i can, When the document is ready, the function "checkAzione" starts and it makes some stuff like DB calls etc, this kinds of ajax calls don't need any visual loading like spinner etc so in the array "opzioni" i set a flag 'caricamento':0 (same of 'loading':0) just check my ajax object to see what i mean, it works until i make some ajax calls that using 'caricamento':1, from that moment every ajax calls in my recursive function makes the "printLoading"... Any tips????
ajaxStart and ajaxStop are global, you add them to the body. You probably shouldn't use ajaxStart/Stop in this case, just add the functionality to your ajax listeners (success and error).

jQuery AJAX triggering too quickly

I have a relatively simple jQuery AJAX call wrapped in a function and I am testing my error functionality. The problem I am facing is the AJAX call happens too quickly! It is causing my 'H6' and '.loading' elements to start repeating. The behaviour I require is to remove the elements, then call the ajax.
function getAvailability(form) {
var str = $(form).serialize(),
warning = $('#content h6');
if ( warning.length > 0 ) {
$(warning).remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
}
else
{
$('<div class="loading">Loading…</div>').insertAfter(form);
}
$.ajax({
type: "POST",
url: "someFile",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$('<h6>Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
});
}
});
return false;
}
I would love to sequence it like so -> Remove 'warning' from page, add .loading. Then trigger AJAX. Then fade out .loading, add & fade in warning/calendar dependent on success.
I have amended my original code, and I have got the function to behave as expected, primarily because I have disabled the submit button during the ajax process.
function getAvailability(form) {
var str = $(form).serialize(),
btn = $('#property_availability');
// Disable submit btn, remove original 'warning', add loading spinner
btn.attr("disabled", "true");
$('.warning').remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
$.ajax({
type: "POST",
url: "public/ajax/returnAvailability1.php",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$(this).remove();
$('<h6 class="warning">Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
btn.removeAttr("disabled");
});
}
});
return false;
}
I believe that the original sequence was not working as expected due to the time delay created by the fadeOut() functions.
Instead of adding and removing warning, why not just show/hide leveraging ajaxStart and ajaxStop?
warning.ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).fadeOut();
});
If you need to sequence your events, then you should try using the deferred and promise methods that are a part of the jQuery.ajax API. This article does a good job of introducing them: http://www.bitstorm.org/weblog/2012-1/Deferred_and_promise_in_jQuery.html

Execute Javascript after ajax response has been rendered

I want to execute a piece of javascript after the ajax response has been rendered. The javascript function is being generated dynamically during the ajax request, and is in the ajax response. 'complete' and 'success' events to not do the job. I inspected the ajax request in Firebug console and response hasn't been rendered when the complete callback executes.
Does not work:
function reloadForm() {
jQuery.ajax({
url: "<generate_form_url>",
type: "GET",
complete: custom_function_with_js_in_response()
});
};
ajaxComplete does the job, but it executes for all the ajax calls on the page. I want to avoid that. Is there a possible solution?
$('#link_form').ajaxComplete(function() {
custom_function_with_js_in_response();
});
you can also use $.ajax(..).done( do_things_here() );
$(document).ready(function() {
$('#obj').click(function() {
$.ajax({
url: "<url>"
}).done(function() {
do_something_here();
});
});
});
or is there another way
$(document).ready(function() {
$('#obj').click(function() {
$.ajax({
url: "<url>",
success: function(data){
do_something_with(data);
}
})
});
});
Please, utilize this engine for share your problem and try solutions. Its very efficient.
http://jsfiddle.net/qTDAv/7/ (PS: this contains a sample to try)
Hope to help
Checking (and deferring call if needed) and executing the existence of the callback function might work:
// undefine the function before the AJAX call
// replace myFunc with the name of the function to be executed on complete()
myFunc = null;
$.ajax({
...
complete: function() {
runCompleteCallback(myFunc);
},
...
});
function runCompleteCallback(_func) {
if(typeof _func == 'function') {
return _func();
}
setTimeout(function() {
runCompleteCallback(_func);
}, 100);
}
Can't help a lot without code. As an general example from JQuery ajax complete page
$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxComplete handler. The result is ' +
xhr.responseHTML);
}
});
In ajaxComplete, you can put decisions to filter the URL for which you want to write code.
Try to specify function name without () in ajax options:
function reloadForm() {
jQuery.ajax({
url: "<generate_form_url>",
type: "GET",
complete: custom_function_with_js_in_response
});
};

Categories