Loading finishing before everything has loaded from multiple functions - javascript

I'm sure this is going to be something really simple, but I am having a problem when calling a function which needs to do various different function calls via ajax to a .net code behind and I want to show a loader over the page until everything has finished, but its not happening.
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
checkSession();
expand2(ID, user);
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
Which calls
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
});
}
and
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
});
}
But the loading overlays are disappearing before it is finishing doing what its doing? I've seen something about using $.when for my calls but I'm not sure how to get this working properly?
Any advice would be great. Thanks

Try to hide loading in expand2 or checkSession function on finish request. Like this
... .done(function () {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
});
So loader will be hidden after everything will have finished.
To be sure that everything is over, you can set "flag". For example check = 2. And do
check--; check||$('.loadingBlackSml, .loadingSml').fadeOut(1000);
edited 10.04.17
Example with flag (check) for requests
var check = 0; // count pending requests
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
count = 2;
checkSession();
expand2(ID, user);
}
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
count--;
if (count === 0) { // check. are all requests finished
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
Of course, you can move
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
to separate function

Related

Jquery ajax request increases exponentially on each request

I use Jquery-ajax calls to get information from a api and store it. The problem I encounter is the following:
When first call is made call everything seems normal. When the call is made 2nd time (after 1 min )again one only call takes place but with 3rd call 2 times sendData function is getting called ,4th time 4 times sendData function is called.
Please tell me where i am going wrong.Thanks in advance.
$(document).ready(function() {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
async: false,
success: function(resp) {
if (resp != null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
setInterval(ajaxCall, 1000 * 60);
} else {
alert("something went wrong");
}
}
});
});
I would suggest you to move calling method to Ajax's complete method:
$(document).ready(function () {
$(function ajaxCall() {
$.ajax({
url: "https://blockchain.info/ticker",
method: "GET",
dataType: "json",
crossDomain: true,
processData: true,
success: function (resp) {
if (resp !== null) {
alert(resp);
var myJSON = JSON.stringify(resp);
alert(myJSON);
sendData(myJSON);
} else {
alert("something went wrong");
}
},
complete: function () {
setInterval(ajaxCall, 1000 * 60);
}
});
})
});

jQuery Raty set score inside click event

I'm trying to use this rating plugin but I was unable to set the new score on click.
I'm making an ajax request on click event and get new calculated score. I wanted to set the new score inside the click event. What is the right way to do it?
<div class="rating" data-id="some-int" data-score="0.5"></div>
Javascript:
$(".rating").raty({
score: function () { return $(this).attr("data-score"); },
click: function (score, evt) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "./ajax.asmx/RateImage",
data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
dataType: "json",
async: false,
success: function (result) { actionResult = result.d; }
});
if (actionResult.Success) {
console.log("Score: " + actionResult.Message);
score = actionResult.Message;
} else { // cancel rating
alert(actionResult.Message);
return false;
}
}
});
There is a built in method to set new score, so just use:
$('.rating').each(function(i) {
var thisRating = $(this);
thisRating.raty({
score: function () {
return $(this).data('score');
},
click: function (score, evt) {
$.ajax({
type: 'post',
contentType: 'application/json; charset=utf-8',
url: './ajax.asmx/RateImage',
data: {
ImgId: thisRating.data('id'),
Score: score
},
dataType: "json",
success: function (result) {
thisRating.raty('score', result.d.Message);
}
});
return false;
}
});
});
Under docs - Functions you will find:
$('#star').raty('score');
Get the current score. If there is no score then undefined will be
returned.
$('#star').raty('score', number);
Set a score.
You can do
$(".rating").raty('setScore', score);
See it working
http://codepen.io/anon/pen/qdVQyO
According to the documentation, you can simply do $('#selector').raty({score: 3}) to set the score. So in the callback, you can call $(".rating").raty({score: actionResult.Message}) like so:
$(".rating").raty({
score: function () { return $(this).attr("data-score"); },
click: function (score, evt) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "./ajax.asmx/RateImage",
data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
dataType: "json",
async: false,
success: function (result) { actionResult = result.d; }
});
if (actionResult.Success) {
console.log("Score: " + actionResult.Message);
$(".rating").raty({score: actionResult.Message});
} else { // cancel rating
alert(actionResult.Message);
return false;
}
}
});

Cannot invoke ashx inside the function

I am having jquery code to invoke ashx file. Its perfectly working while page load. When i call the function from another function means not working.I have place the two codes here.
Please check and help me.
<script type="text/javascript">
$(document).ready(function () {
try {
$("#submit").click(function () {
var user = $("#login").val();
var pass = $("#password").val();
CallLoginHandler(user, pass);
}
}catch(ex){
}
</script>
<script type="text/javascript">
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
alert(response[0]["FLD_ID"]);
//successCallback(response);
} else {
alert(response[0]["FLD_ID"]);
}
}
});
}
</script>
I think you are missing the proper jquery syntax . Try the following modified code :-
<script type="text/javascript">
$(document).ready(function () {
try {
$("#submit").click(function () {
var user = $("#login").val();
var pass = $("#password").val();
CallLoginHandler(user, pass);
});
} catch (ex) {
}
});
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
alert(response[0]["FLD_ID"]);
//successCallback(response);
} else {
alert(response[0]["FLD_ID"]);
}
}
});
}
</script>

Ajax doesn't execute success function

My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});

Load up javascript files after ajax call

Hi how do i go about loading up my javascript files after an ajax call has been made, reason being it seems once i click submit, some javascript functions do not end up working. I tried using "$getscript" however it was a bit buggy especially in google chrome? This is what my call looks like;
function InsertStatus() {
var fStatus1 = document.getElementById('<%=txtStatus.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebServices/UserList.asmx/InsertUserStatus",
data: "{ 'fStatus': '" + fStatus1 + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == "Successful") {
$("#col-3").load(location.href + " #col-3>*", "");
$.getScript('scripts/script.js', function () {
});
}
else {
alert("its false");
$.getScript('scripts/script.js', function () {
});
}
}
});
};
Replace $.getScript('scripts/script.js', function () {});
With:
$.ajax({
dataType: 'script',
url: 'scripts/script.js',
crossDomain:true,
success: function(response)
{
//Whatever
}
});

Categories