Javascript

Angular re-route to login page on user session expiration when user redirects to another route

Goal: Whenever the user redirects to another route via the Angular route provider, check the server if the user is still logged in by creating an MVC controller/action to verify the user session. If the user's session has expired, redirect the user to the login page. Environment: - .Net MVC Core 1.0 - Angular SPA Solution: Create an MVC controller (HomeController) to verify if the user's session has expired. In this scenario, we decided to check the .Net authentication cookie we create as part of ......

Angular - redirect to login after user session expires (including ajax/background processes)

Environment: .Net MVC with Angular v 1Issue: When the user redirects in Angular app or performs any kind of ajax request (searching inside a search box, clicking any button, etc. any event that triggers an Angular $http request to the backend), the user is not aware that they have been logged off from the server. They may redirect to another Angular "page" and search for info and get "weird" server errors.Goal: Provide the user an alert and redirect to the login page. Note, this also needs to support ......

Creating classes in JavaScript

Goal:Creating class instances in JavaScript is not available since you define "classes" in js with object literals. In order to create classical classes like you would in c#, ruby, java, etc, with inheritance and instances.Rather than typical class definitions using object literals, js has a constructor function and the NEW operator that will allow you to new-up a class and optionally provide initial properties to initialize the new object with.The new operator changes the function's context and ......

Intercept a form submit with jQuery and prevent or allow submission

Goal: Intercept a form submit, find out what submit button was clicked/invoked and decide to prevent the submission or continue to submit. Solution: $(document).ready(function() { $("form").submit(function(e) { if (e.originalEvent.explicitOr... == "myButton") { if (some status is true continue to submit the form) return true; //If the status above is false continue to prompt the user if they want to submit or not var ok = confirm('Do you really want to save your data?'); if (ok) { return ......

Why CoffeeScript is tough to maintain

I recently started trying out CoffeeScript only to find out that it caused more headaches. The abstraction level of jQuery was perfect, it did not dictate to coders how to design their code, it just works. However, I recently posted a request to the CoffeeScript team to consider introducing curly braces to help with more complex code to control the flow of logic. For example a if-then-else with many nested levels can be near impossible to debug without tracing through it when using CoffeeScript. ......

jQuery - upgrade from version 1.6.x to 1.7

Goal: Issues to consider when upgrading from jQuery version 1.6 to 1.7. This is a short list and may help identify the real issues you need to concern yourself with in stead of reading through all the release notesSummary of issues encountered during upgrade:As you prepare for upgrade to jQuery 1.7 from 1.6.x, this is a quick glimpse of all the issues that are relevant, not sure if it covers all but may be all you need to worry about.Use this method only for checking checkboxes and radio buttons:$("input:checked")h... ......

Knockoutjs - stringify to handling observables and custom events

Goal: Once you viewmodel has been built and populated with data, at some point it goal of it all is to persist the data to the database (or some other media). Regardless of where you want to save it, your client-side viewmodel needs to be converted to a JSON string and sent back to the server. Environment considerations: jQuery 1.4.3+ Knockoutjs version 1.1.2 How to: So let’s set the stage, you are using Knockoutjs and you have a viewmodel with some Knockout dependencies. You want to make sure it ......

jQuery Templates, Data Link

I am sure you must have read Scott Guthrie’s blog post about jQuery support and officially supporting jQuery's templating, data linking and globalization, if not here it is: jQuery Templating Since we are an open source shop and use jQuery and jQuery plugins extensively to say the least, decided to look into the templating a bit and see what data linking is all about. For those not familiar with those terms here is the summary, plenty of material out there on what it is, but here is what i

jqGrid - customizing the multi-select option (restrict single selection and adding custom events)

Goal: Using the jgGrid to enable a selection of a checkbox for row selection - which is easy to set in the jqGrid - but also only allowing a single row to be selectable at a time while adding events based on whether the row was selected or de-selected. Environment: jQuery 1.4.4 jqGrid 3.4.4a Issue: The jqGrid does not support the option to restrict the multi-select to only allow for a single selection. You may ask, why bother with the multi-select checkbox function if you only want to allow for the ......

jqGrid - dynamically load different drop down values for different rows depending on another column value

Goal: As we all know the jqGrid examples in the demo and the Wiki always refer to static values for drop down boxes. This of course is a personal preference but in dynamic design these values should be populated from the database/xml file, etc, ideally JSON formatted. Can you do this in jqGrid, yes, but with some custom coding which we will briefly show below (refer to some of my other blog entries for a more detailed discussion on this topic). What you CANNOT do in jqGrid, referring here up and ......

jQuery 1.4.4 - issue with attr('selected', null)

Issue: The code below worked before under version jQuery 1.4.2 but when I upgraded to version 1.4.4 it no longer worked as expected - it did not unselect the list box item, only setting "selectd" worked: _handleClick: function(elem) { var self = this; var initElem = this.element; var checked = $(elem).attr('checked'); var myId = elem.attr('id').replace(ini... + '_chk_', ''); initElem.children('option[v... + myId + ']').attr('selected', function() { if (checked) { return 'selected'; ......

Combine and compress javascript and css files in ASP.Net MVC

Goal: When loading js or css files, combine all the js files into one and all css files into one file respectively when rendering to improve on performance. Also compress if need be on the fly. In this example we use many css files and even more js files to organize the ASP.Net Mvc web app into manageable pieces. The reason for the separation is mainly because it gives the team the ability to work on different part of the web app by working on the affected css or js files. It also helps to decide ......

How to store arbitrary data in the DOM using jQuery

Goal: Storing arbitrary data inside the DOM Issue: Storing data : $('selector').attr('alt', 'my data'); Retrieving data: $('selector').attr('alt'); The ALT attribute is designed to be an alternative text description. For images the ALT text displays before the image is loaded. ALT is a required element for images and can only be used for image tags because its specific purpose is to describe images.So therefore, "alt" is an HTML attribute meant to give the tag meaning and not to store data. Also ......

How to dynamically add Edit button to grid for editing row using the jqGrid formedit

Goal: Dynamically add an Edit button to an empty column that will NOT trigger an inline edit but rather a jqGrid formedit for the selected row using the modal dialog option. Problem: All examples in the Demo version include editing inline and adding buttons to a column that only does an inline edit and the Demo version's getRowdata does not perform as expected. I tried it an could not get it working and the getRowData did not work as specified. Solution: gridComplete: function() { var rows = $(item).jqGrid('getRowData'); ......

JSCompress fails to compress my js file - why?

Issue: You use the online compression utility jscompress.com to compress your js file but it fails with an error. Why this may be happening and how to fix it. Possible causes: Apparently not using open and closing curly brackets in an IF statement would cause this. Well turns out this is not the case. Look at the following example and see if you can figure out what the issue is :-) function SetupDeliveredVPRecontactNo... id) { var theData; $.ajax({ data: { deliveredVPId: id }, url: $('#ajaxGetDeliveredVPRecon... ......

How to stop and prompt user when closing browser

Scenario: For some reason you want to stop the user from closing the browser window or from redirecting away from the current page, based on some condition. The solution: window.onbeforeunload = function(event) { return true; } This will prompt you for input (like the JavaScript confirm pop-up menu). There is no way to override the text though. Some concerns: This works great but it may not be what you want all the time, as no matter if you click a hyperlink, hit submit, etc will prompt the user, ......

Prevent repeated clicks on submit button

Scenario: The user wants to save something and hits the Save button (type=submit). The event performs an Ajax call to send the request to the server. The user, being unaware or not sure if their request is being processed or if they clicked the Save button properly, click it again, and again, causing several Ajax requests, which could be a real problem, if the update is to, for example, transfer funds to your ex-girlfriend's account The solution: Prevent the user from being able to click the Save ......

jQuery SELECT does not show selected option

Scenario: You have a drop down box or list box in your jQuery jqGrid plugin and you edit the row via the form edit modal dialog but the form fails to show your selected option(s) in the drop down or list box. The reason: The jqGrid SELECT element binds the selected option(s) innerHTML (not the value) with the name value in the colModel. Example: In the JavaScript file I have a function that I call to setup the grid: function jqGridAccountContact(item, listURL, editURL, $rows, hideGrid) { //get all ......

jQuery AutoComplete in ASP.NET MVC Framework

Goal: jQuery AutoComplete in ASP.NET MVC Framework with callback to customize result Platform/Environment: Asp.Net Mvc version 1 jQuery 1.3.2 Autocomplete - jQuery plugin 1.0.2 Quick Solution: Here I am simply returning a list of account names: $('#Name').autocomplete( $('#ajaxListMatchingAccount... { delay: 10, minChars: 3, matchSubset: 1, matchContains: 1, cacheLength: 10, autoFill: true, mustMatch: false, selectFirst: true, max: 15 } ); ajaxListMatchingAccountName... - this is a ......

Browser engine performance related to JavaScript

Normal 0 false false false MicrosoftInternetExplorer4 st1\:*{behavior:url(#ieooui) } /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.000... mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} ......

jqGrid hide columns but show when editing/adding

Issue: I have a grid which I have what I can only describe as containing “Core” data and “Minor” data. What I'd like to be able to do is to show the Core data in the main grid view but to allow the user to add/edit/view the Core and Minor data when they open the relevant dialog. In essence this would be like having hidden columns that were viewable/editable when the dialogs were opened with form editing/viewing. The Minor data is only of interest to some users, so I don't want to show it in the main ......

jQuery function to truncate long text

The scenario: You have some text that is too long in for example a textarea and want to be able to truncate it client-side and only display a maximum amount of characters. You also want to add the ability for the user to dynamically expand the text by clicking the "more..." link appended to the text. The concern: This is not Ajax enabled and the entire text is rendered to the client and the text extending beyond the maximum is hidden. If the text you want to hide is very large it may suffice the ......

ASP.NET MVC with jQuery Grid

Incorporating the jQuery Grid With ASP.NET MVC Scenario: You have an ASP.NET MVC application and don't want to custom build smart controls like the ASP.NET GridView, ListView, etc, that support sorting and paging, as well as filtering and searching for data, and all of this using Ajax. Solution: The jQuery Grid plug-in. What tools/plug-ins do I need? jQuery version 1.3 and up jqGrid version 3 and up (this post references version 3.4.4) A strong cup of coffee In the past you had to also add the jQuery ......

jQuery Selector efficiency/cost impact

Normal 0 false false false MicrosoftInternetExplorer4 st1\:*{behavior:url(#ieooui) } /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.000... mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} ......

Useful jQuery Plug-ins

Normal 0 false false false MicrosoftInternetExplorer4 st1\:*{behavior:url(#ieooui) } /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.000... mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} ......

jQuery in Action or Learning jQuery

Normal 0 false false false MicrosoftInternetExplorer4 st1\:*{behavior:url(#ieooui) } /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.000... mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} ......

Favorite Techical Books

A list of my favorite technical books that I found very useful over the years. Most of them are related to CSS, jQuery, DHTML, Ajax, and ASP.NET C#: <A HREF="http... _fcksavedurl=&q... ......

How to find out what is calling a Javascript function

Scenario: What is calling a Javascript function. You may have a situation where a function in your code (or anyone else's for that matter) that is loaded into a web page is being called many times, and although in the Firebug profiler you may see the function being called 1000 times, you want to know who is responsible for calling it. The problem: You may use the console.log in Firebug to do this, or even break in the function and step out of it to see who is calling it, but this may be difficult ......

How to set Firebug profiling programmatically

Scenario: You are using the profiler tab in Firebug that profiles everything, in stead you would rather profile one specific function. The solution: You can do this programmatically inside your function: function MyFunction() { console.profile('somename'); ... console.profileEnd('somenam... } Firebug is a free Firefox extension. Ready to install ......

Dynamically setting jqGrid search

You are using the jqGrid search option but in one instance you want to enable the search but on another you want to disable the search for the same grid. The problem: This cannot be done, in short, by setting the properties dynamically, like so: gridComplete: function() { setGridParam({ gridModel: true, gridNames: false, gridToolbar: true, autosearch: false, enableClear: true, enableSearch: true, toolbar: [true, "top"] }); } Setting the search option dynamically during a loadComplete, or gridComplete, ......

jQuery Grid Plugin

Building web-apps using the new MVC-framework for ASP.NET can be challenging if you need to build the boiler-plate code for the SMART controls that come standard with ASP.NET, like the GridView, ListView, etc. However, jQuery's (see jQuery in Action for an excellent resource) plug-in, jqGrid, makes this easy. Although it can be time-consuming to setup the template that specifies the requirements for the grid, it is easy to duplicate once you have it set up. So basically you specify the columns you ......

Firebug Console Quick Reference Guide

Firebug adds a global variable named "console" to all web pages loaded in Firefox. This object contains many methods that allow you to write to the Firebug console to expose information that is flowing through your scripts. console.log(object[, object, ...]) Writes a message to the console. You may pass as many arguments as you'd like, and they will be joined together in a space-delimited line. The first argument to log may be a string containing printf-like string substitution patterns. For example: ......

Firebug Network Monitoring Quick Reference Guide

Network Monitoring Your web app on the server has plenty of tools and ways to measure performance, as well as tools like SQL-Server Profiler for SQL databases. But how do you trace, track and debug client-side code interactively? The use of alerts has been useful but does not support an interactive way for you to interact with the web-page on the fly. To make matters worse, even if you place some traces into your js code to help find the slow functions, etc, network latency may be another cause of ......

jqGrid Dynamically loading select options

Scenario: You are using the jqGrid to edit rows that contain fields that are of HTML tag type "SELECT". Problem: You do not want to hard code the values of the select tag like in the jqGrid samples. For example: editoption: { value: "FE:FedEx; IN:InTime; TN:TNT" } Solution: For example to load a list of countries dynamically, define the variable before the definition of the jqGrid: //get all countries var countries = $.ajax({url: $('#ajaxAllCountriesUrl').v... async: false, success: function(data, ......