Posts Tagged ‘JQuery’

JQuery AJAX Timeout Issue

Posted: February 2, 2013 in JQuery
Tags: , , ,

jQuery ajax default timeout is unlimited (=0).

Set/Detect Timeout on JQuery AJAX – http://stackoverflow.com/questions/5225597/set-timeout-for-ajax-jquery

http://stackoverflow.com/questions/4148830/anyone-know-the-jquery-default-timeout-value

Browser will have default timeout which controls the request/ response. For IE Refer – http://support.microsoft.com/kb/181050

Online editor to try html/script/css – http://jsfiddle.net/tSW7M/

<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js&#8221; language=”javascript”></script>
<script language=”javascript”>
$(document).ready(function() {
window.setTimeout(function() {$(‘#box’).removeClass(“box1”).addClass(“boxCls”);}, 5000);

});

</script>
<style type=”text/css”>
.boxCls {
position: absolute;
width: 200px;
height: 200px;
top: 0;
left: 200px;
background-color: white;
border: 10px solid black;
}

.box1 {
position: absolute;
width: 50px;
height: 50px;
top: 0;
left: 0;
background-color: yellow;
border: 2px solid red;
float:left;
}
</style>
</head>
<body>
<div id=”box” class=”box1″>Box</div>
</body>
</html>

JSON to C# object to JSON

Posted: September 8, 2011 in C#, Javascript, JQuery, JSON
Tags: , , ,

[DataContract]
public class SearchFilter
{
[DataMember]
public string SearchCol { get; set; }
[DataMember]
public string SearchOp { get; set; }
[DataMember]
public string SearchText { get; set; }
[DataMember]
public int PageNo { get; set; }
}
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}

public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
Usage –

SearchFilter lSearchFilter = JSONHelper.Deserialise<SearchFilter>(“{‘SearchCol’:’Col1′,’SearchOp’:’contains’,’SearchText’:’hi’}”);
lSearchFilter.SearchCol
lSearchFilter.SearchOp

Refer following links in your web pages to get latest version of JQuery files from CDN …

http://code.jquery.com/jquery-latest.js
http://code.jquery.com/jquery-latest.min.js

http://encosia.com/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/

Do you know how to use Firebug’s console effectively?

Execute jQuery/javascript statement at the console, with your page loaded in the browser, and you will instantly see the array of matching elements that are returned. If that result set isn’t correct, press the up-arrow key to retrieve the last command entered, refine the statement, and test it again

It works in conjunction with Firebug’s debugger. When execution is paused, switching to the console tab allows you to interrogate and manipulate the state of the DOM as it was at the time execution was halted. As you step through JavaScript code in the debugger, the execution context of the console remains in sync with the debugger’s.

http://msdn.microsoft.com/en-US/scriptjunkie/hh273390.aspx

1. Centralized event handling

This will be used in cases where we have a number of similar elements or structures on a page that share similar behaviour when a user-action is performed against them.

In JavaScript, there’s a known bubbling effect in the language so that if an element such as a link or button is clicked, that event is bubbled up to the parent, informing them that something lower down the tree has been clicked. We can use this effect to our advantage.

Ex: In following example we can bind click event to ul and can handle every li click separately with out binding different functions directly to each li. This will also improve performance by minimizing the DOM access for binding/unbinding and by avoiding the event handling for each element separately.

<ul>
 <li class=’one’>One</li>
 <li class=’two’>two</li>
 <li class=’three’>three</li>
 <li class=’four’>four</li>
 <li class=’five’>five</li>
</ul>

stateManager = {
    fly: function () {
        var self = this;
        $(‘ul’).unbind().bind(“click”, function (e) {
            var target = $(e.originalTarget || e.srcElement);
            if (target.is(“li.one”)) {
                self.handleLIOne(target[0]);
            }
            else if (target.is(“li.two”)) {
                self.handleLITwo(target[0]);
            }
        });
    },
    handleLIOne: function (elem) {
        //Do your own implementation for first li element click
        alert(elem.innerHTML);
    },
    handleLITwo: function (elem) {
        //Do your own implementation for second li element click
        alert(elem.innerHTML);
    }
}
stateManager.fly();

1. Using bind, trigger functions we can implement simple Publish/Subscribe pattern in JQuery
2. Below example shows how to create Subscribers (generally the script on page sections or modules) by subscribing to a common custom event called buttonClick through JQuery bind method and it also shows how to publish the custom event on some action (manual or automatic – here on click of button which is manual action) which intern fires all subscriber’s Action methods through JQuery trigger method.
3. There is already a plug-in available in JQuery site for achieving this by simply calling $.subscribe, $.publish and with few other functions. Refer http://www.dotnetoutsource.com/Download/jQuery/Publish-subscribe.aspx for sample. Our custom functions can be extended on top of native JQuery code using Plug-ins to access them directly on $ operator, like $.subscirbe.

<input type=”button” value=”Click Button & Publish Button Click Event” id=”myfield2″/>
<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.js“></script>
<script language=”javascript”>
    // Publisher script can be at page level. Actual publish action will be invoked through either user actions or through callback functions in case of ajax calls
    var Publisher = {
        Publish: function (eventName, args) {
            $(document).trigger(eventName, args);
        }
    };

    // Subscriber1/Subscriber2 can be part of page sections i.e. user controls (in case of asp.net page)
    var Subscriber1 = {
        subscribe: function () {          
            $(document).bind(‘buttonClick’, Subscriber1.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber1 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber1.subscribe();

    var Subscriber2 = {
        subscribe: function () {           
            $(document).bind(‘buttonClick’, Subscriber2.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber2 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber2.subscribe();

    $(document).ready(function () {
        // Binding publish method for button click event
        $(‘#myfield2’).unbind(‘click’).bind(‘click’, function () { Publisher.Publish(‘buttonClick’, [‘1’, ‘2’, ‘3’]); });       
    });
</script>

JQuery – Samples

Posted: November 22, 2010 in JQuery
Tags:

1. Check class exist or not – if($(“#id”).hasClass(“narroww”))
2. Change element width/height (one or more “,” separated targets) – $(“#id1 .clsname, #id2 .clsname”).width(10px).height(10px);
3. Set css – $(“#id”).css(‘visibility’, ‘hidden’);
4. The difference between .css(‘height’) and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element’s height needs to be used in a mathematical calculation.
5. Show/Hide elements based on class/id/tag –
 $(“#id”).show(); $(“#id”).hide();
 $(“a”).show(); $(“a”).hide();
 $(“.myclass”).show(); $(“.myclass”).hide();

Events –

If you are using JQuery 1.4+ then always use unbind before calling bind, otherwise events will fire more than once due to binding the same event multiple times. Performance will be bad in case if you have too many links on page and you are attaching events to them through JQuery bind method.

1. $(this).unbind(‘hover’); does not work. So use either $(this).unbind(‘mouseenter’).unbind(‘mouseleave’); or $(this).unbind(‘mouseenter mouseleave’);
2. To unbind all events use $(this).unbind(); unbind() doesn’t work with hardcoded inline events Ex: <div id=”some_div” onmouseover=”do_something();”>

AJAX Sample

Posted: November 22, 2010 in Uncategorized
Tags: , , , ,
1. JQuery – AJAX
 
jQuery.ajaxSetup( options ) – A set of key/value pairs that configure the default Ajax request. All options are optional.

Ex:
$.ajaxSetup({
url: “/xmlhttp/”,
global: false,
type: “POST”,
data: myData
});

Sets the defaults for Ajax requests to the url “/xmlhttp/”, disables global handlers and uses POST instead of GET. The above Ajax request then sends some data without having to set anything else.

Note: Global callback functions should be set with their respective global Ajax event handler methods-.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()-rather than within the settings object for $.ajaxSetup().

Show a loading message before AJAX request starts

Ex:
$(“#loading”).ajaxStart(function(){
$(this).text(‘Triggered ajaxStart handler.’);
//$(this).show();
});

2. Microsoft AJAX Toolkit Sample
 
<div id=”OverlayContent”>
Content will be shown here!
</div>

<div class=”data”>
<div class=”bums clearfix”>
<div class=”bum”>
<a href=”#” class=”bumoverlay” data-bumid=”556119″>
<img src=”default_large.jpg”/>
</a>
</div>
<div class=”bum”>
<a href=”#” class=”bumoverlay” data-bumid=”556119″>
<img src=”default_large.jpg”/>
</a>
</div>
</div>
<div class=”lists clearfix”>
<div class=”list”>
<a href=”#” class=”listoverlay” data-listid=”2″ data-uid=”10″>
<img src=”med_9745314cb3f92d6460abfdb895c865d0.jpg”/>
</a>
</div>
<div class=”list”>
<a href=”#” class=”listoverlay” data-listid=”3″ data-uid=”10″>
<img src=”med_9745314cb3f92d6460abfdb895c865d0.jpg”/>
</a>
</div>
</div>
</div>

<script>
var OverlayControl = function() { }

OverlayControl.prototype = {
Key : ‘MediaContent’,
ShowbumOverlay : function(e, element) {
var aid = element.getAttributeNode(‘data-bumid’).value;
var r = new Sys.Net.WebRequest();
r.set_url(‘/Modules/abc.asmx/GetData?’);
r.set_body(String.format(‘contentkey={0}&queryparams={1}’, e.Key, ‘bum;’ + aid));
r.set_httpVerb(‘POST’);
r.set_userContext(this);
r.add_completed(e.ResponseHandler);
r.invoke();
},
ShowlistOverlay : function(e, element) {
//alert(this.childNodes[0].getAttributeNode(‘data-uid’).value);
var listid = element.getAttributeNode(‘data-listid’).value;
var uid = element.getAttributeNode(‘data-uid’).value;
var r = new Sys.Net.WebRequest();
r.set_url(‘/Modules/abc.asmx/GetData?’);
r.set_body(String.format(‘contentkey={0}&queryparams={1}’, e.Key, ‘list;’ + listid + “;” + uid));
r.set_httpVerb(‘POST’);
r.set_userContext(this);
r.add_completed(e.ResponseHandler);
r.invoke();
},
HideOverlay : function(e, element) {
var target = $(‘#OverlayContent’);
target[0].innerHTML = “Content will be shown here!”;
},
ResponseHandler: function(executer, args) {
var ele = executer.get_webRequest().get_userContext();
//try
//{
if (executer.get_responseAvailable())
{
var result = executer.get_xml();
var target = $(‘#OverlayContent’);
if (document.all)
target[0].innerHTML = result.documentElement.firstChild.text;
else // Firefox  
target[0].innerHTML = result.documentElement.firstChild.textContent;
}
//}
//finally {
// userContext._requestingData = false;
//}
}
};

var overlayCtrl = new OverlayControl();

// Attach event (mouseover, mouseout) & event handler to every bum <a> tag
var bums = $(‘.bumoverlay’);
for(i=0;i <>
var currentbum = bums[i];
$addHandler(currentbum , “mouseover”,
// javascript closures implementation in for-loops – http://www.mennovanslooten.nl/blog/post/62
function(overlayCtrl, currentbum ) {
return function() {
overlayCtrl.ShowbumOverlay.apply(currentbum , [overlayCtrl, currentbum ]);
}
}(overlayCtrl, currentbum )
);
$addHandler(currentbum , “mouseout”,
function(overlayCtrl, currentbum ) {
return function() {
overlayCtrl.HideOverlay.apply(currentbum , [overlayCtrl, currentbum ]);
}
}(overlayCtrl, currentbum )
);
}

// Attach event (mouseover, mouseout) & event handler to every list <a> tag
var lists = $(‘.listoverlay’);
for(i=0;i <>
var currentlist = lists[i];
$addHandler(currentlist, “mouseover”,
function(overlayCtrl, currentlist) {
return function() {
overlayCtrl.ShowlistOverlay.apply(currentlist, [overlayCtrl, currentlist]);
}
}(overlayCtrl, currentlist)
);
$addHandler(currentlist, “mouseout”,
function(overlayCtrl, currentlist) {
return function() {
overlayCtrl.HideOverlay.apply(currentlist, [overlayCtrl, currentlist]);
}
}(overlayCtrl, currentlist)
);
}
</script>