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'
});
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 am trying to communicate with a server using JSONP call back.
Here is my code
$('.icwsDownloadRecording').click(function(){
var id = $(this).attr('data-recordingid');
$.ajax({
type: 'GET',
url: 'http://example.com/Default2.aspx',
data: {'ID': id},
dataType: 'jsonp',
cache: false,
timeout: 40000,
crossDomain:true,
jsonp: "MyCallbackFunction",
});
});
function MyCallbackFunction(data)
{
//process data further
console.log(data);
if(!data || data.url.length < 5){
return;
}
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload( data.url, {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
}
The issue here is that I keep getting this message in the console
ReferenceError: MyCallbackFunction is not defined
I do have this defined as you can see in my code above
The server respond looks like this
MyCallbackFunction("{'URL': 'http:\/\/example.com:8106\/ghjgj3835396265336634646562363030303122226D616C686179656B22535353557DBE0C305645E2DE110AA1D7F8792E96A3'}");
how can I correct this issue?
EDITED
This is my code after Quentin Answer , this is my new code
$(function(){
$('.icwsDownloadRecording').click(function(){
var id = $(this).attr('data-recordingid');
$.ajax({
type: 'GET',
url: 'http://example.com/Default2.aspx',
data: {'ID': id},
dataType: 'jsonp',
timeout: 40000,
success: function(data){
//process data further
console.log(data);
if(!data || data.url.length < 5){
return;
}
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload( data.url, {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
}
});
});
});
Unless you have all of that code wrapped in another function, that should work.
Using a hardcoded function name is bad practise though.
Update:
$(function(){
You do have all that code wrapped in another function.
Remove this:
jsonp: "MyCallbackFunction",
Replace it with:
success: MyCallbackFunction
Or you could put an anonymous function expression there instead (as you have done in your edit)
Let jQuery generate a unique function name (which protects you from race conditions) and allow the server to use the callback query string argument to determine what function name to use.
MyCallbackFunction is in the same scope as the ajax call, so it will be available to the function (which can copy it to a suitably named global).
After you fix that, you have an additional problem:
MyCallbackFunction("{'URL':
Your response is JSON encoded in a JavaScript string, but you are trying to treat it as a JavaScript object.
Either:
Fix the server so it doesn't stringify the JSON or
Run the first argument through JSON.parse
crossDomain:true,
Remove that. It doesn't do anything here. (All it does is, when using XHR (which you aren't using) to the same origin (which you aren't targeting), suppress the custom headers that aren't typically allowed on a cross-origin request so that you can perform an HTTP redirect to a different origin).
cache: false,
That's the default for JSONP requests. Including it is pointless.
return false; //this is critical to stop the click event which will trigger a normal file download!
If you want to stop the click event, then you need to return false from the click event handler function (not the Ajax success handler).
You can't wait until the Ajax function has run and got a response before doing that. Ajax is asynchronous.
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 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
});
});
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