Dialog popup and spinner not behaving correctly - javascript

I want to popup/display a dialog. It has two tabs and in each of these tabs there is a table (lets say table1 and table2).
Both of these tables contain data those are populated by a rest/ajax service (lets say service1 and service2).
When each of these rest services completes, the table component is populated with the data.
On top of this, the dialog has a spinner widget activated when the dialog first pops up.
The spinner widget is deactivated when BOTH of the rest services have completed.
For table1 I have code that looks a bit like this :
this.updateTable1 = function (dialog)
{
dialog.setSpinner(true)
var call = {}
call.url = 'service1';
call.xmlHttpReq = $.ajax({
url: url,
dataType: 'json',
async: true,
type: 'GET'
}).always(
function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown)
{
dialog.table1.loadData(processedDataOrXHRWrapper);
dialog.setSpinner(false)
});
};
For table2 the code is pretty much the same.
Which means that it also has dialog.setLoading(false). This means that whichever process finishes first, the spinner is deactivated, which is incorrect behaviour.
Somehow the two ajax calls need to know about each other, but I don't like that idea :(. Should I have some kind of third object that stores state of which processes have finished?
I tried using ajax calls in sync mode, but that just blocks the display thread in the browser.

You can use Deferred promises to implement this.
var updateTable1 = function (dialog)
{
return $.ajax({
url: url,
dataType: 'json',
async: true,
type: 'GET'
}).always(
function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown)
{
dialog.table1.loadData(processedDataOrXHRWrapper);)
});
};
// and same for updateTable2
dialog.setSpinner(true);
$.when(updateTable1(dialog), updateTable2(dialog)).always(function() {
dialog.setSpinner(false);
});
Only issue with the above is that, if the ajax call in updateTable1 or updateTable2 fails, the always function is immediately called. If you don't want this - see the $.whenall function in the answer to this question:
jquery deferred - "always" called at the first reject

Related

Only IE 11 losing focus on ajax call sometimes ASP.NET MVC4

I am using a boostrap dialog box to pull in a list with a quantity. After I submit my form, and open the dialog box to check to see if the quantity has updated, it seems to be stale data. I have a call with ajax to the controller and then back to the database to pull in updated info. But when I set a breakpoint in the controller (on server side) it never hits. IT ONLY kicks out of the issue when I set a breakpoint to the function calling ajax within developer tools and debugger. I don't see any console errors either.
I don't have an issue with Firefox, just IE11.. here is the code:
<script type="text/javascript">
function LocationModal() {
$("#GetLocBtn").attr("disabled", "disabled");
var partNumber = $("#PartNum").val();
var Condition = 'Z';
var urlQry;
var receiveIsChecked = document.getElementById('Receive').checked;
var src = 'removed for security';
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { partNumber: partNumber, CCODE: Condition },
beforeSend: function () {
},
success: function (data) {
$("#LocationModalContainer").html(data.LocationModal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
};
The problem is indeed that IE caches the results of Ajax calls. You can prevent that behavior either by adding cache: false to every call, like you've discovered, or setting it globally via ajaxSetup before you make any calls.
$.ajaxSetup({
cache: false
});
The use of ajaxSetup is discouraged in the jQuery documentation, but might be a good solution for you if you don't use any plugins that might rely on the normal behavior and want to quickly make sure none of your own ajax calls is cached.
Personally, I have my doubts about how real the interference risk mentioned in the documentation is when it comes to the cache setting, since basically you just make IE behave like other browsers.

Knockout: Make the whole page wait for result of ajax call

Basically, I would like to call to geoip.com to get the information of the browser user and then use their location to render correctly. But the problem is that using knockout, the page get rendered without waiting for the result of ajax (Even all render code stay behind a success callback). How can I achieve the result?
Changing from ajax to synchronous also does not work.
I am using knockout to bind data to a custom handler in view
<div id="main_layout" class=layout data-bind="svg:handle">
....Other HTML....
Inside the svg.handle of its viewModel
ko.bindingHandlers.svg = {
init: function (element, valueAccessor) {
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// Do everything
}
}
// return viewModel for the HTML

How to tell when multiple functions have completed with jQuery deferred

I have 3 functions which handle data pulled in from AJAX, they update the page after the ajax function is called.
When the AJAX function is called I show a loader, I want to hide the loader after the AJAX has completed and the functions have completed.
How can I use deferred with when and then in jQuery to test once all 3 function are completed.
Here is my AJAX code, this hides the loader on AJAX success at the moment, ideally this would be after the 3 functions have been completed / were successful.
The 3 functions receive data to process and display on the page, they are not AJAX functions.
function setUpStocking() {
$.ajax({
url: url,
cache: false,
beforeSend: function(){
// Show loader
$('.loader').show();
},
success: function(data){
updateMyList(data.gifts);
updateRecievedGift(data.recieved);
updateGiftsOpenedToday(data.opened);
// Hide loader
$('.loader').hide();
}
});
}
The functions are outside the AJAX function:
function updateMyList(gifts) {
// Get data, process it and add it to page
}
function updateRecievedGift(recieved) {
// Get data, process it and add it to page
}
function updateGiftsOpenedToday(opened) {
// Get data, process it and add it to page
}
You need to first make each of these functions return the deferred object jQuery gives you when you make an AJAX request. Then you can put those in to an array, and apply that to $.when(). Something like this:
var deferreds = [];
$.ajax({
url: url,
cache: false,
beforeSend: function(){
// Show loader
$('.loader').show();
},
success: function(data){
deferreds.push(updateMyList(data.gifts));
deferreds.push(updateRecievedGift(data.recieved));
deferreds.push(updateGiftsOpenedToday(data.opened));
$.when.apply(deferreds).done(function() {
// Hide loader
$('.loader').hide();
});
}
});
There should be $, inside .apply to make above code work.
$.when.apply($, deferreds).done(function() {
// Hide loader$('.loader').hide();
});

AngularJS - ui-grid - Data display issue

I am implementing http://ui-grid.info/ in my application.
I am populating the grid with ajax call like this :-
$scope.getGrid = function () {
jq.ajax({
type: "POST",
url: "getData",
dataType: "html",
traditional: true,
data: { columnDb: $scope.columnDb },
success: function (data) {
var dataObj = jQuery.parseJSON(data);
......
$scope.gridOptions.data = $scope.myData;
});
}
There is a weird problem i am facing. on the above function call, i can see nothing in my HTML, But if i just mouse scroll on the Grid area the data gets displayed, even if i open Inspect Element in Chrome, the data gets displayed.
Any Idea How to solve this?
This code does not lead to an Angular digest when the ajax call returns, and hence you don't see anything change in your on screen 'view'. So you can either:
Use $http for your ajax call
Add a $scope.$apply() to the callback function.
I would suggest using 1

alert dialogue during a process with javascript

using ASP .Net MVC 4.0 , vs10 , MSSQL 2008
I have a stored procedure, which is executed in one of my page. it generally takes 30 to 50 second to execute. I want to show a alert dialogue where an gif image will be loaded during this process time. I am executing stored procedure with sqlcommand. The process started on clicking Process button. after finishing the process, the page returns another view.
I have poor knowledge of javascript, so please show me a simple way.
EDIT:
Is it possible to show an image on buttonclick an do other codebehind process?
Like:
<script type="text/javascript">
function showImage() {
document.getElementById('Processing').style.visibility = visible;
}
</script>
<div id="progessbar">
<img alt="Processing" src="../../Images/Processing2.gif" id="Processing" style="visibility:hidden"/>
</div>
It will be difficult to accomplish what you're trying to do in a traditional MVC fashion since the request takes a long time. This is better accomplished using AJAX which processes your request asynchronously. I recommend also using jQueryUI dialog or any modal to show a progress indicator, or even any custom JS.
I like jQuery BlockUI personally to create the modal for me but that's just a preference.
/** Using a wrapper to show/hide the progress indicator.
Swap the blockUI with any library or custom JavaScript for displaying the progress indicator.
*/
var showProgress = function() {
$.blockUI({ message: '<img src="progressImage.gif" />' });
};
var hideProgress = function() {
$.unblockUI();
;}
/** Trigger to submit the form */
$('#submit').click(function() {
/** Show an indicator before making an AJAX request*/
showProgress();
$.ajax({
url: '/someEndpoint',
data: $.toJSON({/* some JSON param */}),
type: 'POST',
dataType: 'json',
timeout: 50000 /** Override timeout in ms accordingly */
}).done(function(data){
/** Remove the indicator once the request has succeeded and process returned data if any. */
hideProgress();
});
return false;
});
Use ajax for your process. It ll make the parallel processing for "showing gif" and completing your desired code.
You can use JQuery-AJAX with page methods this way: [1]: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
or you can try simply this
var actionURL = "(Your disired action e.g /index.jsp)"
$.ajax({
cache:false,
url: actionURL,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
$("#progessbar").show();
//Here you can write any code to execute before the action like gif loading etc
},
success: function( data ) {
alert("Success Conditions");
//"data" is what u gets from your target. You can see by alert(data); here
//Here you can write any code which you want to execute on finding the required action successfully
},
complete: function(){
alert("Complete Conditions");
$("#progessbar").hide();
//Here you can write any code which you want to execute on completion of the required action you given in actionURL
},
error: function(){
alert("Error Conditions");
}
});
NOTE: alerts are just for explanation, you can write your own code also
For this code you have to include jquery plugins. which can be downloaded from their official site [l]: http://jquery.com/

Categories

Resources