jQuery Plugin – Fun with Query String Object
I have been working on an internal application which uses ajax and modal popups so that the user/manager/administrator doesn’t need to navigate to different pages to do different actions. While this looked the part and done everything it said on the tin I ran into a problem. When a user acknowledged an event that needs authorisation a email is sent to the appropriate manager asking for action. This email needed to contain a link that when the manager clicked it, the appropriate section was shown.
No point in re-inventing the wheel and writing individual pages so I had an idea about using querystrings to show the appropriate modal popup. I found a nice little jQuery plugin called query object. As you can see from the documentation it’s very easy to use.
If the link in the email is showing the manager a listing of say New Contacts added
http://app/view/manager/?showModal=LoadNewContacts
Within the document ready we could do the following:
1: $(document).ready(function() {
2: var section = $.query.get('showModal');
3: var allowedFunctionsArray = ['LoadNewContacts()', 'AlertMe()'];
4: if ($.inArray(section, allowedFunctionsArray) != -1) {
5: eval(section);
6: }
7: });
8:
9: function AlertMe() {
10: alert('this is an alert');
11: }
12: function LoadNewContacts() {
13: $('#Contacts').toggle();
14: }
Line 2 assigns the local variable section with the value of the querystring “showModal”. Notice live 5 with the eval(section).
“The eval() function evaluates a string and executes it as if it was script code.” – w3 Schools
The querystring value is the name of the function we want to call and the eval function makes this possible. However, using the eval() function can lead to cross site scripting(XSS). I have added a check to only allow what I want to run, in this case only the following two functions can be called “LoadNewContacts” and “AlertMe”. What you’re not seeing is the fact that the files that have these functions are served via a secure http handler based on windows authentication and that checks are in place to make sure managers can only see/action what they’re meant to. Is simple and effective.
View demo of running different functions via querystring
If you would like to see more posts in relation to jQuery please use the following link: View jQuery post listing