My scripts are working perfectly fine. However, the content does not refresh itself to get new data. Why is it so?
function updateMsg() {
$.ajax({
url: "/recent/notifications/",
cache: false,
success: function(html){
$("#profile_notifarea_msgbox").html(html);
}
});
setTimeout('updateMsg()', 4000);
}
updateMsg();
Your setTimeout can reference updateMsg directly instead of using a string:
var timeout;
function updateMsg() {
$.ajax({
url: "/recent/notifications/",
cache: false,
success: function(html){
$("#profile_notifarea_msgbox").html(html);
timeout = setTimeout(updateMsg, 4000);
}
});
}
updateMsg();
function stopUpdate() {
clearTimeout(timeout);
}
To stop the continuous update you save a reference to the setTimeout in a variable and then call clearTimeout and pass in that variable. In this example, you would just call the function stopUpdate() to cancel the updates.
when you use ajax with jQuery try to always put an error function, in this way you can identify if something is wrong with the request
Related
I am trying to get the response time of an ajax request and use it in a setTimeout() function, this function displays a loader that is suppose to keep loading until we get the response.
Here's my function :
$("#recalculer").click(function(){
ajax_call();
setTimeout(function()
{
$("#divgris").fadeTo(0,1);
$("#loadingdiv2").hide();
}, 5000);
});
And here's my ajax request :
function ajax_call()
{
var resultat;
var duree_souhaitee= $("#duree").val();
var apport_personnel= $("#apport").val().replace(/\s+/g, '');
var prix_achat_bien=$("#prix").val().replace(/\s+/g, '');
$.ajax({
type: "POST",
url: "/iframe/rest-assurance",
data : {
"duree_souhaitee" : duree_souhaitee,
"apport_personnel" : apport_personnel,
"prix_achat_bien" : prix_achat_bien
},
dataType: 'json',
xhrFields: {
withCredentials: true
},
async: true,
beforeSend: function(){
$("#actualiserAssurance").hide();
},
success: callback_assurance
});
}
For now i set a time of 5000 but i need to replace it with the ajax response time, how can I achieve that ?
I use always:
$("#loadingdiv2").show();
$.ajax(
...
).always(function(){ $("#loadingdiv2").hide(); });
If you want to separate it from the Ajax call I would use a custom event.
$("#recalculer").click(function(){
ajax_call();
});
$("body").bind('custom.ajaxStart', function(){ $("#loadingdiv2").show(); });
$("body").bind('custom.ajaxStop', function(){ $("#loadingdiv2").hide(); });
function ajax_call(){
$('body').trigger('custom.ajaxStart');
$.ajax(..).always(function(){ $('body').trigger('custom.ajaxStop'); });
}
The always callback is triggered even on a 404, relying on timing never works well for me.
Using an event gives you the flexibility of calling the loading deal, from anywhere.
Meaby the you can use:
console.time(label);
and
console.timeEnd(label);
more info can be found here.
Goodluck!
use
var afterfnc = ()=>{
$("#divgris").fadeTo(0,1);
$("#loadingdiv2").hide();
}
and then set
callback_assurance = afterfnc
in ajax call
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);
});
I am having some trouble with the timing of javascript events. The problem I am having is that one part of the code seems to be executing before another part of the code completes. I need to ensure that the first code finishes before the latter code begins. Here is the initial code:
function(){
myLoop(); //this needs to complete before the call to myMethod below
$.ajax({
url: sURL + "myController/myMethod",
success: function() {
$.msg("My Success Message",{live:10000});
error: function(){
$.msg("My Error Message",{live:10000});
});
}
And here is the code that loops and inserts records into a db:
function myLoop(){
$('input[name=c_maybe].c_box').each(function(){
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
success: function(data) {
//not sure what to do on success.
}
});
}
});
}
The problem that seems to be happening is that the call to myController\myMethod is happening before myLoop completes inserting all the records into the database.
Can someone suggest a way for me to redesign this code so that I can ensure that myController\myMethod is not called until myLoop has completely finished?
Thanks.
function myLoop() {
var jqxhrs = [];
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
jqxhrs.push($.ajax({...
}
return jqxhrs;
}
function () {
$.when.apply(undefined, myLoop()).done(function () {
$.ajax({
url: sURL + "myController/myMethod",
...
});
}
$.when.apply is used to call $.when on the array of ajax requests, so .done is not called until they are all complete.
You can use the $.when function that has been added to jQuery.
It goes something like this:
$.when(ajaxFunction1(), ajaxFunction1()).done(function(response1, response2){
// when the function calls are done this code here will be executed -> the response will be passed as parameters corresponding to the functions -> response1, response2
});
Or you can try to use "beforeSend" within the ajax function:
$.ajax({
beforeSend: function(){
alert("doing stuff before the ajax call ...");
},
success: function(){
alert("Whoa!");
}
});
You can make the ajax call synchronous. That way, the execution will be blocked till ajax call returns:
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
async: false,
success: function(data) {
//not sure what to do on success.
}
});
I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page.
So jQuery ajax() function have an timeout variable. But i want to use getJSON function. And i think that i can use ajaxStart() and ajaxStop() functions. But how?
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
setTimeout("throw '';",15000) //i used this but didn't work
setTimeout("return;",15000) //i used this but didn't work
setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events)
})
.ajaxStop(function() {
$(this).fadeOut();
});
getJSON() returns a promise on which you can call the abort function :
var p = $.getJSON(..., function(){ alert('success');});
setTimeout(function(){ p.abort(); }, 2000);
EDIT : but if your goal is just to abort if it takes too much time, then lethal-guitar's answer is better.
getJSON() is just a shorthand for the following:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So you could use $.ajax() and specify the timeout option as desired. See also: http://api.jquery.com/jQuery.getJSON/
As lethal-guitar mentioned getJSON() function is just an shorthand for $.ajax(). If you want to detect if a timeout has occurred rather than an actual error use the code below.
var request = $.ajax({
dataType: "json",
url: url,
data: data,
success: function( ) { },
timeout: 2000
}).fail( function( xhr, status ) {
if( status == "timeout" ) {
// do stuff in case of timeout
}
});
There's always the nuclear route as well:
//Set AJAX timeout to 10 seconds
$.ajaxSetup({
timeout: 10*1000
});
This will set all the AJAX requests your program makes (even via $.getJSON) to have a time out of 10 seconds (or what have you).
the setTimeout function executes a set of code after a specified number of milisecons in the global scope.
The getJSON function (per the jQuery documentation here http://api.jquery.com/jQuery.getJSON/) is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so you would want to make your call like so:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success,
timeout: 15000
});
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
})
.ajaxStop(function() {
$(this).fadeOut();
});
I don't think any of these answers are ideal. I know this is years late, but what you want to do is use the success/error callback options of the .ajax(); method when receiving a JSONP response.
Example of how I would structure this:
// Call
$.ajax({
// URL you want to get
url: 'http://example.com/json?callback=?',
// Set a realistic time in milliseconds
timeout: 3000,
// Put in success callback function here, this example
// shows you the data you got back from the call
success: function(data) {
console.log(data);
},
// Put in an error handling function, just an alert in this case
error: function(badData) {
alert('The call was unsuccessful');
},
type: 'POST'
});
I am trying to access variable 'dimensions' in my ajax response but not able to get it. I dont want to make this variable global. Following is my code
$(document).ready(function(){
$('#submittext').click(function(){
var dimensions;
$.ajax({
type: "GET",
url: "bin/getcontentsize.php",
data: findContentsize,
success: function(response){
//want to access dimensions here to assign response and some calculation(but not able to access it)
}
});
//so i can use here
});
});
In this case you can access the dimensions variable from both the ajax call back and the code immediately after starting the ajax request. The variable is accessible in both of these contexts.
What is most likely causing the problem though is the timing. The success method will run asynchronously after the ajax request is completed. It's best to view this as executing later. However the code immediately after the $.ajax call will execute immediately. Hence you won't see any effects from the success handler on the dimensions variable when it runs.
If there is code you want to run with the value of dimensions as calculated by the success method you need to call that code from the success callback. For example
$('#submittext').click(function(){
var handleNewDimensions = function (dimensions) {
// Code that used to be after the $.ajax line
}
$.ajax({
type: "GET",
url: "bin/getcontentsize.php",
data: findContentsize,
success: function(response){
var dimensions = doTheCalculation(...);
// Call the code which needs to deal with the new dimensions
handleNewDimensions(dimensions);
}
});
Problem when you run it.
$(document).ready(function(){
$('#submittext').click(function(){
var dimensions="1";
$.ajax({
type: "GET",
url: "bin/getcontentsize.php",
data: findContentsize,
success: function(response){
dimensions = "2";
}
});
//!!!!Attention
alert(dimensions); // result is "1", not "2"
});
});
First, your code already ran. After that, your $.ajax starts to run.
Assign the dimensions variable the value, and test it again:
var dimensions="sample";
This should work:
$(document).ready(function(){
$('#submittext').click(function(){
var dimensions = 1;
$.ajax({
type: "GET",
url: "bin/getcontentsize.php",
data: findContentsize,
success: function(response){
alert(dimensions);
}
});
//so i can use here
});
});