I have a code like this:
object1 = $.ajax({
..
..
});
In the event of error I want to be able to restart the ajax, for example, if the connection of the user drops I want to be able to call the same ajax again without having to make $.ajax(.....). Is it possible to do something like:
object1.restart();
?
put it in a function:
function callAjax() {
$.ajax({
..
..
});
Then its like callAjax() if theres an error..
That is easy, and jQuery allows you to do that inside an Ajax request. Have a look
$.ajax({
/* full ajax body */
url: 'page.html',
data: 'if-any',
success: function () {
/* show that ajax request has finished */
},
error: function () {
/* restart the ajax request, by re executing the function */
}
});
You can try this:
function ajax_request () {
$.ajax({
/* full ajax body */
url: 'page.html',
data: 'if-any',
success: function () {
/* show that ajax request has finished */
},
error: function () {
ajax_request(); // using this, you can re execute the function
}
});
}
$.when() is a potential candidate here,
for eg.
var object1 = $.ajax({
..
..
});
$.when(object1).fail(object1);
Related
I have a requirment where in AJAX call has to happen before document.ready and the response from the AJAX call will be used to update some HTML elements.
So I have something like below:
var ajaxget = $.ajax({
type: 'GET',
url:'/xxx/get',
success: function(resp) {
//logic
}
});
$(document).ready(function(){
$.when(ajaxget).done(function(resp) {
//do ur logic
$(documet).trigger("yyyy");
});
});
//the above part is common across pages and placed in the <head>
//below one goes into multiple places based on the pages
$(document).ready(function(){
$(document).on('yyyy', function() {
});
});
The issue is the trigger event "yyyy" doesn't get executed in IE and intermittently on other browsers as well. Please help!
Might be better to use then() instead of success to be sure that whatever happens in success is completed before the $.when.done
Note that success is not part of the promise chain
Try:
var ajaxget = $.ajax({
type: 'GET',
url: '/xxx/get'
}).then(function(resp) {
//logic
return resp;
});
$(document).ready(function() {
ajaxget.then(function(resp) {
//do ur logic
$(documet).trigger("yyyy");
});
});
But also note you are triggering the event before you register it also if the order shown in question is correct
This code works for me. Simply i defined "yyyy" event before triggering.
$(document).ready(function () {
$(document).on("yyyy", function () {
console.log('triggered');
});
$.ajax({
type:'GET',
url:'some.jsp',//your url
success:function(resp){
//logic
$(document).trigger("yyyy");
console.log(resp);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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'm writing a javascript function that should change the view of a postcard depending on which case is selected.
My problem is that the old values of the object "m_case" is getting used. If I press the button with class "case-btn" twice I get the right case selected in my postcard view. But I want it to be triggered when I press the button once.
I guess I have to do something like a callback function in the m_case.setCase() function call, but I can't get it working,
$('.case-btn').on('click', function() {
remove_active_state_from_cases();
m_case.setCase($(this).data('case'));
// Changes the view of the postcard
m_postcard.changeBackground(m_case.getPhoto());
m_postcard.changeMessage(m_case.getMessageText());
m_postcard.changeFullName(m_case.getFullName());
m_postcard.changeCountry(m_case.getCountry());
$(this).toggleClass('active');
});
The setCase() function
this.setCase = function(id) {
// Set ID
this.setID(id);
var that = this;
$.ajax({
url: 'get_case_by_id.php',
type: 'get',
dataType: 'json',
data: {id: that.getID() },
success: function(data) {
if(data.success) {
that.setFirstName(data.first_name);
that.setFullName(data.full_name);
that.setAdress(data.adress);
that.setCountry(data.country);
that.setStamp(data.stamp);
that.setPhoto(data.photo);
that.setSummary(data.summary);
that.setStory(data.story);
that.setMessageText(data.message_text);
that.setDefaultMessageText(data.default_message_text);
that.setMessageImg(data.message_img);
} else {
console.log('failure');
}
}
EDIT The problem might be in my AJAX call, I have to wait till the ajax have been called. but how do I continue the first flow when my Ajax is done and not before?
SOLUTION
I made it working by adding a callback parameter and calling that function in the ajaxs complete function.
$('.case-btn').on('click', function() {
remove_active_state_from_cases();
var that = this;
m_case.setCase($(this).data('case'), function() {
m_postcard.changeBackground(m_case.getPhoto());
m_postcard.changeMessage(m_case.getMessageText());
m_postcard.changeFullName(m_case.getFullName());
m_postcard.changeCountry(m_case.getCountry());
$(that).toggleClass('active');
});
});
// Sets the whole case from an id.
this.setCase = function(id, callback) {
// Set ID
this.setID(id);
var that = this;
$.ajax({
url: 'get_case_by_id.php',
type: 'get',
dataType: 'json',
data: {id: that.getID() },
success: function(data) {
if(data.success) {
that.setFirstName(data.first_name);
that.setFullName(data.full_name);
that.setAdress(data.adress);
that.setCountry(data.country);
that.setStamp(data.stamp);
that.setPhoto(data.photo);
that.setSummary(data.summary);
that.setStory(data.story);
that.setMessageText(data.message_text);
that.setDefaultMessageText(data.default_message_text);
that.setMessageImg(data.message_img);
} else {
console.log('fail big time');
}
},
complete: function() {
callback();
}
});
}
Your m_postcard.changeBackground and other calls should be in the success callback, or in another function that is called from the success callback, as those values aren't set till the async ajax call is done.
With the way your code is now the m_postcard.changeBackground and other calls are called immediately after your setCase function is done executing. This means your methods are executed before the data has arrived from the server
While the ajax is processing you probably should show a loading message on the screen to let the user know they have to wait till the processing is done. Show the message before calling the .ajax call and hide it in the success/error callbacks.
Any changes to the site content should be done from the success callback, ie changing active states, changing content, etc.
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'm trying to make some actions after an ajax call done with jquery.
I have seen that if i use a function like this:
function DownloadData() {
$.ajax({
url: "/api/AlbumsRest",
accepts: "application/json",
cache: false,
success: function () {
/*binding stuff*/
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error' + textStatus);
}
});
}
The ajax request it's done in async mode. I don't want to change it because i don't want to freeze the page. But i would like to make some actions (animations, effects etc) after this ajax is completed.
So, my question is, how can i to know if i'm at the end of this request without using the success event
If i call DownloadData function like this:
function DownloadNextData() {
DownloadData();
SlideOutAnimation();
SlideInAnimation();
}
I need to make slides after async request has been made.
Some idea ?
Using jQuery Deferred Objects you should return the result of $.ajax() from DownloadData
function DownloadData() {
return $.ajax({...});
}
and then you can register a function outside of your AJAX handler that'll only get called once the AJAX call has completed:
function DownloadNextData() {
DownloadData().done(function() {
SlideOutAnimation();
SlideInAnimation();
});
}
behold - your animation processing is completely decoupled from your AJAX function :)
To simplify things, .done can also actually take a list of function references:
function DownloadNextData() {
DownloadData().done(SlideOutAnimation, SlideInAnimation);
}
Note that in this case you can't supply your own function arguments - they'll actually get passed the contents of the AJAX data.
function DownloadData() {
return $.ajax({
url: "/api/AlbumsRest",
accepts: "application/json"
});
}
function DownloadNextData() {
SlideOutAnimation();
SlideInAnimation();
}
DownloadData().done(DownloadNextData);
Try $.ajaxcomplete. here is the documentation for it http://api.jquery.com/ajaxComplete/