Disable page behind on processing using Javascript in MVC4 - javascript

I am using MVC4 in my project. On click of a button on a page, I need to show a dialog and then on confirmation, I need to do an event processing.
$('#btn1).click(function (e) {
e.preventDefault();
var meetingvar = new Array();
var cells = $(this).closest('td').siblings('td');
meetingvar = $(cells[2]).text().split(",");
var params = {};
params.meetingdate = meetingvar[0];
params.meetingstate = meetingvar[1];
params.meetingvenue = meetingvar[2];
$.ajax(
{
type: 'GET',
url: '/[Controler]/[action1],
data: { MeetingDate: params.meetingdate, MeetingState: params.meetingstate, MeetingVenue: params.meetingvenue },
beforeSend: function (jqXHR, settings) {
setLoaderLabel('Please wait...');
showLoader();
}
}).done(function (data, textStatus, jqXHR) //success callback
{
if ($.trim(data) == 1) {
var dialog = $('<p>Confirmation Required. Do you want to overwite ?</p>').dialog({
buttons: {
"Yes": function () { //alert('you chose yes');
window.location.href = '/[Controller]/[Action2]?MeetingDate=' + meetingvar[0] + '&MeetingState=' + meetingvar[1] + '&MeetingVenue=' + meetingvar[2] + '&toGen=1';
},
"No": function () { //alert('you chose no');
window.location.href = '/[controller]/[action2]?MeetingDate=' + meetingvar[0] + '&MeetingState=' + meetingvar[1] + '&MeetingVenue=' + meetingvar[2] + '&toGen=0';
},
"Cancel": function () {
dialog.dialog('close');
}
}
});
}
if ($.trim(data) == 0) {
showLoader();
window.location.href = '/[controller]/[action1]?MeetingDate=' + meetingvar[0] + '&MeetingState=' + meetingvar[1] + '&MeetingVenue=' + meetingvar[2] + '&toGen=1';
}
if ($.trim(data) == 2) {
ShowErrorMessage('<p>NOT DEFINED</p>');
}
}).fail(function (jqXHR, textStatus, errorThrown) //error callback
{
var errorMsg = GetAjaxResponseTitle(jqXHR.responseText);
ShowErrorMessage('<p>' + errorThrown + '</p>' + errorMsg);
hideLoader();
}).always(function () //complete callback
{
hideLoader();
});
});
Here , on success, from first action1 is it going to success, with the Loader(basically disabling the main page). But I need the same Loader functionality on Click of Yes or No, because, before redirecting there is an event which takes some time. At this stage, shouldn't allow user to click on any other button on the base page. Don't know how to achieve this. Please appreciate any help.
Thanks In advance

Related

Getting resolved data undefined in jquery

I am trying to call synchronous call for getting data count using ajax call.
Here is my Jquery Code:
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return count;
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
var count = tilesCount("");
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
Output:
Call 1: 1
Call 2: undefined
Synchronous call working perfectly, but I am getting data as undefined
Since ajax is asynchronous return count; will be empty
var count = tilesCount("");
So the best solution is to just passed a callback function inside your method which can be call whenever your ajax is completed
function tilesCount(tilename, count, callback)
Wrap this inside your callback function
function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
}
so your $(document).ready will be like this and just add parameter count inside the callback
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});
your javascript code would be like this now
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count, callback)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return callback(count);
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});

abort long polling ajax request and restart request with new parameter

how do I cancel an ajax request, then call it again with new parameter? with my code, the previous ajax requests still hang around.
var stats_url = '/stats';
var live_stats_ajax_object = $.ajax();
$(".check-round").on("click", function(){
live_stats_ajax_object.abort();
round = $(this).attr('class').split(' ')[0];
get_live_stats(round);
});
var get_live_stats = function(round) {
live_stats_ajax_object = $.ajax({
url: stats_url,
type: "GET",
data: 'live_stats=true' + "&event_id=" + $( "#event-list option:selected" ).val()
+ "&fight_id=" + $( 'input[name=fightlist]:checked' ).val()
+ "&round=" + round,
dataType: "json",
timeout: 3500,
complete: function(xhr, textStatus) {
console.log("polling again stats for " + round);
if (textStatus != "abort") {
setTimeout( function() { get_live_stats(round); }, 10000 );
}
},
success: function(data) {
console.log("polling and got live stats for " + round);
console.log(data);
}
})
.fail(function() {
console.log("polling failed and couldn't get live stats for " + round);
})
};
I have been on this for hours. Thanks
Edit, Updated
Try
// create empty object
var live_stats_ajax_object = {}
// reference for `setTimeout` within `get_live_stats`
, id = null
, stats_url = "/stats"
, get_live_stats = function (round) {
var eventlist = $( "#event-list option:selected" ).val()
, fightlist = $( 'input[name=fightlist]:checked' ).val();
live_stats_ajax_object = $.ajax({
type: "GET",
url: stats_url,
data: "live_stats=true&event_id="
+ eventlist
+ "&fight_id="
+ fightlist
+ "&round="
+ round,
timeout: 3500
});
// return `live_stats_ajax_object`
return live_stats_ajax_object
.done(function (data, textStatus, jqxhr) {
console.log("polling and got live stats for " + round + "\n"
, data);
})
.fail(function (jqxhr, textStatus, errorThrown) {
console.log("polling failed and couldn't get live stats for "
+ round);
})
.always(function (jqxhr, textStatus) {
if (textStatus !== "abort") {
// set `id` to `setTimeout`'s `numerical ID`
// call `get_live_stats()` within `setTimeout`
id = setTimeout(function () {
get_live_stats(round);
}, 10000);
}
});
};
$(".check-round").on("click", function () {
var round = $(this).attr('class').split(" ")[0];
// at initial click `live_stats_ajax_object` is empty object ,
// not having `jqxhr` `promise` property ;
// call `get_live_stats()` , which sets `live_stats_ajax_object`
// to `$.ajax()` , having `state` property at returned `jqxhr` object
if (!live_stats_ajax_object.hasOwnProperty("state")) {
get_live_stats(round);
} else {
// if `id` was set during initial call to `get_live_stats()`
if (id) {
// `.abort()` previous `live_stats_ajax_object` request ,
// `clearTimeout()` of `id` , set `id` to `null`
// call `get_live_stats()` with current `round` argument
live_stats_ajax_object.abort();
clearTimeout(id);
id = null;
get_live_stats(round);
}
}
});
jsfiddle http://jsfiddle.net/guest271314/7wrdo5wr/

jQuery add/removeClass & AJAX not working

I'm using Isotope with AJAX to pull in some posts in WordPress, pretty much everything is there, except for the default Isotope animation runs when I AJAX in content, which looks a bit weird. I still wanted it to animate when filtered though.
So I thought I could just use add/removeClass within my AJAX function to turn it off/on when needed, but if I do the animation never runs.
Any ideas where I'm going wrong here?
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
if( $('body').hasClass('home') ) {
var loopHandler = '/inc/loop-handler.php';
} else {
var loopHandler = '/inc/loop-handler-archive.php';
}
var load_posts = function(){
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page},
dataType : "html",
url : templateDir+loopHandler,
beforeSend : function(){
if(page != 1){
$('.loader').append('<div id="temp_load" style="text-align:center; z-index:9999;">\
<img src="'+templateDir+'/img/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
var itemHeight = $('.item').height();
var height = $content.height()+itemHeight*2;
$content.append($data);
$content.css('min-height', height);
$data.hide();
// should stop the animation
$('.isotope').addClass('no-transition');
$content.isotope('destroy');
$content.imagesLoaded( function(){
$content.isotope({
// options
layoutMode: 'fitRows',
itemSelector : '.item'
});
});
$data.fadeIn(700, function(){
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// should start up the animation again
$('.isotope').removeClass('no-transition');
$content.css('min-height', '0');
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() +
$content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
If you need any of the HTML/PHP I'm happy to post it up. Also, here's the dev site if you want to check it out.
I don't know Isotope and I have not tested if it works. But I have refactor your code with annotations to help you better understand the problem.
I think it comes from how you call removeClass and addClass successively, the two instantly cancel.
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
var loopHandler = '/inc/loop-handler.php';
var isotopeController = {
append: function($data) {
// Add AJAX data
var itemHeight = $('.item').height();
var height = $content.height() + itemHeight * 2;
$content.append($data);
$content.css('min-height', height);
// Stop
isotopeController.stop($data);
// Restart
$content.imagesLoaded(function() {
// When images loaded !
isotopeController.start($data);
});
},
start: function($data) {
// Start isotope
$content.isotope({
layoutMode: 'fitRows',
itemSelector: '.item'
});
// Show data
$data.fadeIn(700, function() {
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// Start the animation
$content.removeClass('no-transition');
$content.css('min-height', '0');
},
stop: function($data) {
// Hide data
$data.hide();
// Stop the animation
$content.addClass('no-transition');
// Stop isotope
$content.isotope('destroy');
},
loadPosts: function() {
$.ajax({
type: "GET",
data: {
numPosts: 1,
pageNumber: page
},
dataType: "html",
url: templateDir + loopHandler,
beforeSend: function() {
if (page != 1) {
$('.loader').append('' +
'<div id="temp_load" style="text-align:center; z-index:9999;">' +
'<img src="' + templateDir + '/img/ajax-loader.gif" />' +
'</div>'
);
}
},
success: function(data) {
var $data = $(data);
if ($data.length) {
isotopeController.append($data);
} else {
$("#temp_load").remove();
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
};
$window.scroll(function() {
var content_offset = $content.offset();
if (!loading && ($window.scrollTop() + $window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
isotopeController.loadPosts();
}
});
// On load
$(function() {
if (!$('body').hasClass('home')) {
loopHandler = '/inc/loop-handler-archive.php';
}
isotopeController.loadPosts();
});

javascript formatting

I have a piece of code that seems to have a problem. I've tried JSLint and other tools to see where I might have a missing delimiter. Eclipse doesn't show me anything either. In Firebug, the complete block of code shows as disabled line numbers like comment lines do. Anyone know of a good tool? I used ctrl+K to indent the code I pasted below.
$(document).ready(function() {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if (ReInitAnswer){
return true;
}
ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({ type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown){
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function(i){
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter){
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger ('click');
});
$(".alphabet").hover(function () {
var _$this = $(this);
var usercount = 0;
$.ajax({ type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res){
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount +")</span>"));
},
error: function (xhr, textStatus, errorThrown){
console.log('errorThrown');
}
});
},
function () {
$(this).find("span:last").remove();
}
);
});
It's really difficult to tell what you're asking, but if you mean it's formatted wrong, try http://jsbeautifier.org/ for better formatting. Here's that code cleaned up (including the incorrect casing of else):
$(document).ready(function () {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if(ReInitAnswer) {
return true;
} else {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if(CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
$(".alphabet").hover(function() {
var _$this = $(this);
var usercount = 0;
$.ajax({
type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res) {
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount + ")</span>"));
},
error: function(xhr, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}, function() {
$(this).find("span:last").remove();
});
});
Javascript is case sensitive.
ELSE must be lowercase.
ELSE must be lowercase
ELSE { // <-- this is bad
alert('canceled');
return false;
}

What makes the entire script block disabled?

When I check this code in Firebug, the entire block is disabled.
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
</script>
You have to replace all uppercase ELSE with else (JavaScript is case-sensitive).
Add the closing brace and parenthesis at the end of the code, to finish the $(document).ready(function(){ block.
Working code:
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} else { // <------------------------------------ ELSE > else
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else { // <------------------------------------ ELSE > else
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
}); // <---------------------------------------------------- Added });
</script>

Categories