<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Undisciplined Bytes &#187; jQuery</title>
	<atom:link href="http://www.undisciplinedbytes.com/category/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.undisciplinedbytes.com</link>
	<description>Web Application Development Tips, Tricks and Techniques</description>
	<lastBuildDate>Tue, 31 Jan 2012 09:07:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaScript best practices II</title>
		<link>http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/</link>
		<comments>http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 10:35:08 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[browser]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=552</guid>
		<description><![CDATA[We’ve seen some basic recommendations we should all follow when writing  JavaScript. Now let’s go through some more:


Comment as much as needed, but no more: comment what you consider needed,  but don’t tell others your life story. Too many comments may make some other  developer get distracted from the actual code.
Javascript is [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve seen some basic recommendations we should all follow when writing  JavaScript. Now let’s go through some more:</p>
<p><span id="more-552"></span></p>
<ul>
<li>Comment as much as needed, but no more: comment what you consider needed,  but don’t tell others your life story. Too many comments may make some other  developer get distracted from the actual code.</li>
<li>Javascript is used to define the behaviour, not the look &amp; feel: even  though there’s the possibility to set the appearance of your application through  JavaScript, you should leave that for CSS. Always follow the “separation of  concerns” mantra. A change in the icons or the color of borders shouldn’t  require dealing with JavaScript code.</li>
<li>Modularize: keep your code modularized and specialized. Make sure to write  smaller, generic helper functions that fulfill one specific task, rather than  catch-all methods.</li>
<li>Allow for configuration and translation: everything that is likely to change  in your code should not be scattered throughout the code, for example, labels,  CSS classes and IDs. By putting these into a configuration object and making it  public, we make maintenance very easy and allow for customization.</li>
<li>Access the DOM as little as possible: accessing the DOM in browsers is an  expensive thing to do. The DOM is a very complex API and rendering in browsers  can take up a lot of time. To make sure that your code is fast and doesn’t slow  down the browser to a halt try to keep DOM access to a bare minimum.</li>
<li>Build on the shoulders of giants: JavaScript libraries are specifically  built to make browsers behave as you would expect by plugging browser holes.  Therefore, if you want to write code that works without keeping the maintenance  overhead of supporting current browsers and those to come, start with a good  library.</li>
<li>Development code is not live code: live code is done for machines,  development code is done for humans. Make your code as readable and  understandable as possible. Then, before deploying your web application,  collate, minify and optimize your code in a build process.</li>
</ul>
<p>If you follow all these recommendations, you can be sure you’ll have produced  a high quality code that will be easy to maintain.</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/' rel='bookmark' title='Permanent Link: JavaScript best practices I'>JavaScript best practices I</a></li>
<li><a href='http://www.undisciplinedbytes.com/2009/10/javascript-frameworks-overview/' rel='bookmark' title='Permanent Link: Javascript frameworks overview'>Javascript frameworks overview</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript I: the basics'>Object Oriented JavaScript I: the basics</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript best practices I</title>
		<link>http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/</link>
		<comments>http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 12:43:41 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[browser]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/</guid>
		<description><![CDATA[Now that we’ve seen the basic JavaScript concepts, we’ll go through some recommendations to make a good code. These are some practices that should be followed if you want to make a readable and maintainable code. It is based on my knowledge and experience of JavaScript over several years of practical experience:


Always use ‘var’: although [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we’ve seen the basic JavaScript concepts, we’ll go through some recommendations to make a good code. These are some practices that should be followed if you want to make a readable and maintainable code. It is based on my knowledge and experience of JavaScript over several years of practical experience:</p>
<p><span id="more-548"></span></p>
<ul>
<li>Always use ‘var’: although it is not compulsory, the use of the ‘var’ keyword is always recommended. By using it, your code will execute faster, and you will avoid some potential problems.</li>
<li>Feature-detect rather than browser-detect: before using any advanced feature that an older browser may not support, check to see if the function or property exists first, instead of writing code to detect browser versions.</li>
<li>Avoid ‘eval’: the eval() function in JavaScript allows a programmer to run arbitrary code at run-time, by interpreting a string as if it was code. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. “Eval is evil.&#8221; Don&#8217;t use it unless you are an experienced developer and know that your case is an exception.</li>
<li>Use unobstrusive JavaScript: now, this is an important one: HTML and JavaScript code should not be mixed together. You should always follow the “separation of concerns” mantra: HTML defines the structure and content of a web page, and JavaScript defines the behavior. Therefore, do not use inline event handlers. Attach your event-handling code by JavaScript. This way, you’ll improve readability and maintainability.</li>
<li>Avoid cluttering the global namespace: global variables and functions are rarely required. Using globals may cause naming conflicts between JavaScript source files and cause code to break. You should always use object oriented programming and write all your code in classes when writing JavaScript code.</li>
<li>Use JSON: when storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XML when possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is language-neutral.</li>
<li>Make you code understandable: choose easy to understand and short names for variables and functions. Think of your code as a story – a story that should be easy to read and understand, the names you choose shouldn’t make it more complicated.</li>
</ul>
<p>In my next post I’ll discuss some more recommendations. Stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/' rel='bookmark' title='Permanent Link: JavaScript best practices II'>JavaScript best practices II</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript III: some tips'>Object Oriented JavaScript III: some tips</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript I: the basics'>Object Oriented JavaScript I: the basics</a></li>
<li><a href='http://www.undisciplinedbytes.com/2009/10/javascript-frameworks-overview/' rel='bookmark' title='Permanent Link: Javascript frameworks overview'>Javascript frameworks overview</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript II: the pattern'>Object Oriented JavaScript II: the pattern</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HTML 5 C# Web Sockets server and ASP.NET client implementation</title>
		<link>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/</link>
		<comments>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 15:02:14 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=396</guid>
		<description><![CDATA[In the previous post we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.
I’ve developed a very basic Web [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a title="HTML 5 Web Sockets" href="http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/" target="_blank">previous post</a> we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.</p>
<p>I’ve developed a very basic Web Socket server implementation in C# just as a proof of concept. It handles the most basic operations you would expect from a server: start a new connection, disconnect, and send and receive data. Besides, I’ve developed the client part as well using regular ASP.NET. Actually it’s just plain HTML and JavaScript being served from an ASP.NET server – this example doesn’t use any fancy <em>runat=server </em>controls or anything of the like. The functionality is achieved with very simple and easy to understand JavaScript.</p>
<p><span id="more-396"></span></p>
<p>So what does this example do? It provides two projects: a Web Socket server and a Web Socket client. The server is a windows console application that once executed just sits there waiting for a connection request. When a client connects, the server sends its date and time to the client every 10 seconds. The client is a web page with some controls to connect/disconnect and to send data to the server, as well as a log window to see what’s going on. Take a look at the example at the bottom of the page.</p>
<p>Here’s a description of the public members of the Web Socket Server:</p>
<pre class="brush:c#">// Possible status of the server
enum ServerStatusLevel { Off, WaitingConnection, ConnectionEstablished };
// Constructor of the server with default values
WebSocketServer();
// Constructor of the server with the specified values
WebSocketServer (int serverPort, string serverLocation, string connectionOrigin);
// Close the server and release all resources
void Dispose();
// Start the server and make it listen for connection requests
void StartServer();
// Send data to the connected client
void Send (string message);
// Whether events should be logged or not
bool LogEvents;
// Origin of the connection
string ConnectionOrigin;
// Location of the server
string ServerLocation;
// Port of the server
int ServerPort;
// Current status of the server
ServerStatusLevel Status;
// Fired when data is received from the client
event DataReceivedEventHandler DataReceived;
// Fired when client is disconnected
event DisconnectedEventHandler Disconnected;
// Fired when a new connection is established
event NewConnectionEventHandler NewConnection;</pre>
<p>Note how I provide two constructors for the Web Socket Server class: one with default parameters (if you want to keep it as simple as possible), and another one to specify the values you want. Anyways, you can still change them after creating the new instance, as the properties are public. You can also specify whether you want the server to log out the events to the console with the <code>LogEvents</code> property.</p>
<p>In order to get the data being sent from the client, you must attach your own function to the <code>DataReceived</code> event, which will then receive the message as a parameter.</p>
<p>So here’s how you would use this Web Socket Server:</p>
<pre class="brush:c#">public void Test()
{
    WebSocketServer WSServer = new WebSocketServer();  // Default values
    WSServer.NewConnection += new NewConnectionEventHandler(WSServer_NewConnection);
    WSServer.Disconnected += new DisconnectedEventHandler(WSServer_Disconnected);
    WSServer.DataReceived += new DataReceivedEventHandler(WSServer_DataReceived);
    WSServer.StartServer();
}

void WSServer_DataReceived(string message, EventArgs e)
{
    Console.WriteLine("Data received from the client: " + message);
}

void WSServer_Disconnected(EventArgs e)
{
    Console.WriteLine("Server disconnected");
}

void WSServer_NewConnection(EventArgs e)
{
    Console.WriteLine("New connection established");
    WSServer.Send("Hello new client! I hope you enjoy your visit!");
}</pre>
<p>It’s a very simple Web Socket server, so it’s very easy to use. You shouldn’t have much problem understanding it.</p>
<p>Go ahead and download the Visual Studio solution and give it a try!</p>
<p><strong>UPDATE </strong><strong>(October 12th, 2010):</strong></p>
<p><strong>The Web Socket protocol is not closed yet, so it is being constantly updated. This means that previous Web Socket server implementations might stop working after an update has been made to the API. The original version of the code I released here complied with version 75 of the Web Socket draft. The current version is 76, so I updated my code and released a second project.</strong></p>
<p>No idea of what I&#8217;m talking about? I&#8217;ll make it easy for you&#8230; download the v76 implementation first, and if it doesn&#8217;t work then check out the v75 implementation. If you&#8217;re using one of the latest browsers, you should have no trouble.</p>
<p><del><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/06/WebSocketsTest.zip" target="_self">WebSocketsTest (draft 75).zip</a></del> (Older browsers)</p>
<p><a title="Web Sockets Test" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/10/WebSocketsTestdraft76.zip" target="_self"><strong>WebSocketsTest (draft 76).zip</strong></a><strong> (Latest browsers)</strong></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/' rel='bookmark' title='Permanent Link: HTML 5 Web Sockets'>HTML 5 Web Sockets</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>AJAX call using ASP.NET Web Services</title>
		<link>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/</link>
		<comments>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 20:17:10 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=382</guid>
		<description><![CDATA[We’ve already seen quite a few ways of performing AJAX calls: web pages, HTTP Handlers and Page Methods. Today we’ll see how to request data from the server using ASP.NET Web Services.
Web Services are a very general model for building applications, and can be implemented for any operation system that supports communication over the Internet. [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already seen <a href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/">quite a few ways of performing AJAX calls</a>: <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/">web pages</a>, <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/">HTTP Handlers</a> and <a href="http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/">Page Methods</a>. Today we’ll see how to request data from the server using ASP.NET Web Services.</p>
<p>Web Services are a very general model for building applications, and can be implemented for any operation system that supports communication over the Internet. A Web Service is some programmable application logic accessible via standard Web protocols. It is often referred to as <em>Web APIs </em>as well, since they are a set of methods that provide some functionality through remote method calls. It is a way of <strong>offering some of your functionality to all of the internet</strong>. But, of course, some kind of restrictions and security can be built into your web services, if that’s what you wish.</p>
<p><span id="more-382"></span></p>
<p>As it turns out, the previous article I posted showing how to use Page Methods was also a Web Service: Web Methods are the building blocks of Web Services (a Web Service has many different Web Methods). But it was a very small and simple implementation, intended to return simple data to a small script placed in that same web page. The example we’re going to see follows the same concept, but in a larger way. We’re going to see the basics of how to implement a full-blown Web Service that can be accessed from anywhere on the internet.</p>
<p>This is very handful if you want to develop a collection of methods to be called from anywhere in your application. Imagine you’d like to know in which moment the user logged in to the system: you could write this server method and then make it public as a web service. This way, you’ll have this server functionality available through an AJAX call from anywhere in the application.</p>
<p>Ok, enough theory, now let’s get our hands dirty. Get to the .aspx part of the web page in which you wish to implement your ajax call, and write the HTML code we’ve been using in all our examples:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>We need a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now, the Javascript code:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
    function ExecuteAJAXCall() {
        $.ajax({
            type: "POST",
            url: "AJAXCalls.asmx/GetServerTime",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data.d;
    };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. This time, this function has changed a bit from other examples. Web Services calls require more parameters to set the communication between client and server up. The content type must be declared as “application/json; charset=utf-8”. And, as with the <a href="http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/">previous Page Method example</a>, server procedures are called using the syntax <code>[page name] + “/” + [method name]</code>.</p>
<p>When the AJAX call returns, we have the usual function that takes care of painting the result on the screen. Note how we need to use the <code>d</code> property to access the data this time.</p>
<p>Now, we need to write the Web Service. The easiest way is to right-click on your project and add a new item from there. Select Web Service, and you’ll get a skeleton from which you can implement the functionality you wish in your web service. For our example, we’ll write this piece of code:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceAJAXCall
{
    /// &lt;summary&gt;
    /// Summary description for AJAXCalls
    /// &lt;/summary&gt;
    [WebService(Namespace = "http://www.undisciplinedbytes.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class AJAXCalls : System.Web.Services.WebService
    {

        [WebMethod] public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}</pre>
<p>As you can see, we’ve only written the code required to return the server date and time. If you compare this example to the previous one where I explained how to implement AJAX calls with page methods, you can see that this is essentially the same thing. It all comes down to using the <code>WebMethod</code> attribute from the <code>System.Web.Services library</code>. However, this example that we’re seeing today is more complete, as it is implemented using a full-blown web service. The objective of this article is not to fully explain ASP.NET Web Services (I’ll leave that to some other post I have in mind), but to explain the very basics to be able to implement and AJAX call using them, so I won’t bother about diving into the details. But keep in mind that <strong>Web Services are much more powerful than this</strong>, and that <a title="Web Services" href="http://en.wikipedia.org/wiki/Web_service" target="_blank">their intention aim much higher</a> than simple AJAX calls.</p>
<p>Here’s the Visual Studio project for you to play with:</p>
<p><a title="Web Service AJAX Call" href="http://en.wikipedia.org/wiki/Web_service" target="_blank">WebServiceAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET Page Method</title>
		<link>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/</link>
		<comments>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 19:26:09 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=367</guid>
		<description><![CDATA[We’ve already been through AJAX calls using simple web pages and HTTP Handlers. But there’s still more ways to request data from the server. Today we’ll take a look at how to do so using server methods.
ASP.NET allows you to define methods in the code-behind of an ASPX page. This is very helpful in situations [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already been through AJAX calls using simple web pages and HTTP Handlers. But there’s still more ways to request data from the server. Today we’ll take a look at how to do so using server methods.</p>
<p>ASP.NET allows you to define methods in the code-behind of an ASPX page. This is very helpful in situations where you want to expose some specific server side functionality such as data retrieval for a specific page. If you need to make the operation available to multiple different .aspx pages it’s a better idea to use a web service so your pages can share the functionality. We’ll see how to use web services in the next post.</p>
<p>Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carried around by an ASP.NET page.</p>
<p><span id="more-367"></span></p>
<p>Ok, so we’ll set up the HTML we need to run this test. We’ll use the same one we’ve been using in all our examples:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>As usual, we’ll draw a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now, the Javascript call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
    function ExecuteAJAXCall() {
        $.ajax({
            type: "POST",
            url: "default.aspx/GetServerTime",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data.d;
    };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. This time, this function has changed a bit from other examples. Page method AJAX calls require more parameters to set up the communication between client and server. We need to set the content type, and send the parameters to the method, even if it is a parameter-less method. Note how we’re calling the method by using the syntax <code>[page name] + “/” + [method name]</code>.</p>
<p>When the AJAX call returns, we have the usual function that takes care of painting the result on the screen. Note how we need to use the <code>d</code> property to access the data this time.</p>
<p>Now comes the interesting part. As we saw before, we’re programming a serverside method in the same web page to return the data from the server, so we don’t need any more web pages in our project. To implement this functionality, get to the codebehind part of the web page and write this code:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace PageMethodAJAXCall
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod] public static string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}</pre>
<p>The secret behind this magic is just the <code>System.Web.Services</code> library we’re importing. This library provides the <code>WebMethod</code> attribute, which can be used in <code>public static</code> methods to indicate they’re to be accessed by remote client calls. Whatever the function returns will be sent to the client. Note how this time we don’t need to serialize the data nor we need to deactivate the cache: everything is taken care of by the Web Services library. You just need to set the <code>WebMethod</code> attribute and return the data you want. Nothing more is required.</p>
<p>I would say this way of performing AJAX calls is the easiest of all. It requires almost no more concepts than what a developer will have from regular programming, and hides much of the complexity. However, it is not the standard way of communicating with the server for controls, plugins and widgets out there, so it is not always possible to use it. But if you’re developing your own web control from scratch or you can tweak the way some other web control requests data, you should consider using this technique. Remember: <strong>keep it simple!</strong></p>
<p>As usual, you can take the Visual Studio project from here and take a look at it:</p>
<p><a title="Page Method AJAX Call Project" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/04/PageMethodAJAXCall.zip" target="_self">PageMethodAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET HTTP Handler</title>
		<link>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/</link>
		<comments>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 14:56:19 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=357</guid>
		<description><![CDATA[We’ve already seen how to perform an AJAX call using just a simple ASP.NET web page. Now we’ll see how to do it with an HTTP handler instead of a web page.
But, what is an HTTP handler? Well, as its names suggests, it is an element that handles HTTP requests. Well, but that’s what an [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already seen <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/" target="_blank">how to perform an AJAX call using just a simple ASP.NET web page</a>. Now we’ll see how to do it with an HTTP handler instead of a web page.</p>
<p>But, what is an HTTP handler? Well, as its names suggests, it is an element that <em>handles </em>HTTP requests. Well, but that’s what an .aspx web page does, right? Sure, but in a lengthier, slower and resource-hungrier way. Regular web pages inherit from the <code>System.Web.UI.Page</code> class, which contains a lot of overhead and pre and post-processing in order to make it easier for the programmer to return HTML code to the client performing a request. In other words, the web page class has stuff to make it easier to develop a web page. It’s got some logic, doesn’t it?</p>
<p><span id="more-357"></span></p>
<p>But, what if we don’t want to return a web page? Then we’re just wasting resources in our server, since we’re not to going to use any of the facilities the web page class provides. If what we want to return is not an actual web page, then you should avoid using the <code>System.Web.UI.Page </code>class.</p>
<p>We’ll take a closer look at HTTP handlers in some other post I’m preparing, but for now you should know that they’re more adequate for processing AJAX requests.</p>
<p>This example is quite similar to the <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/" target="_blank">previous one</a>: the only difference is that the HTTP handler replaces the web page. Except for that, we’ll be doing the same call and using the same javascript code. However, just for clarity’s shake, I’ll be posting all the code involved here.</p>
<p>Ok, so now we’ll get our hands dirty and start doing some work! First, we’ll need some HTML code to draw a simple test page. Start a new Visual Studio Project and get to the newly created page. On the C# codebehind of the new page we won’t be changing anything. Leave everything by default. We’ll be doing our work in the .aspx part. This HTML code should be sufficient for our needs:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;jQuery AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>This is a very simple page. We’ll just have a heading, a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now we need some actual code to make the AJAX call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
   function ExecuteAJAXCall() {
         $.ajax({
             url: "AJAXRequest.ashx",
             dataType: 'json',
             success: Callback_AJAXCall
         });
   };

   function Callback_AJAXCall(data) {
         document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data;
   };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. We’re passing three parameters to the function: the URL of the element that will get called, they type of data we’re expecting back (JSON in this case) and the javascript function to execute once the data gets back to the client. The jQuery ajax function has <a href="http://api.jquery.com/jQuery.ajax/">many more parameters</a>, but we didn’t need them this time since the example is not very complicated.</p>
<p>The function called when the data is returned is very simple: its only purpose is to take the string returned from the server and write it in the container we previously created for this purpose. Note that the parameter it receives, data, is already a javascript object. The AJAX call returns a simple string from the server, but the jQuery function is smart enough to convert that string to a javascript object and pass it to the function we indicated.</p>
<p>Ok, now we’re getting to the interesting point. Now that we have the test page in place, let’s deal with the AJAX call server-side. The <code>AJAXRequest.ashx </code>HTTP handler is the link between the client web browser and the server. Here we’ll process everything we need and we’ll return a string to the client with the data requested.</p>
<p>So here’s how we program an HTTP handler:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    ///
    /// Processes AJAX requests
    ///
    public class AJAXRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            string CurrentDate = DateTime.Now.ToString();

            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            context.Response.Write(JSSerializer.Serialize(CurrentDate));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}</pre>
<p>To implement an HTTP handler you just need to implement the <code>System.Web.IHttpHandler</code> interface. You need to provide the desired behaviour to the <code>ProcessRequest</code> method and the  <code>IsReusable</code> property. The first method is the one which actually takes care of processing the HTTP requests and returning the data. The <code>IsReusable</code> property determines whether this instance of HTTP handler can be reused for fulfilling another request of the same type.</p>
<p>This implementation is very simple: it just takes the current date and time from the server, converts it to JSON format and returns it. Note the <code>System.Web.Script.Serialization</code> class we’re importing. This class takes care of converting the object we want to return to JSON format. Note the line in which we deactivate the cache as well. If you don’t do this, the AJAX call will always seem to return the same data, as the web browser will have kept a copy of it the first time it was executed. Most AJAX calls need the cache disabled in order to work properly.</p>
<p>You can download a copy of the Visual Studio project and do some tests to check how it works:</p>
<p><a title="jQuery AJAX HTTP Handler Call Visual Studio Project" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/03/jQueryAJAXHTTPHandlerCall.zip" target="_self">jQueryAJAXHTTPHandlerCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET web page</title>
		<link>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/</link>
		<comments>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 14:56:18 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=336</guid>
		<description><![CDATA[We already saw what an AJAX call is and the different types there are. Today we’re going to see how to perform an AJAX call using a regular web page at the server. The page will be the connection between the client’s web browser and the server. It will take care of performing the operations [...]]]></description>
			<content:encoded><![CDATA[<p>We already saw what an <a title="AJAX calls" href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/" target="_blank">AJAX call is and the different types there are</a>. Today we’re going to see how to perform an AJAX call using a regular web page at the server. The page will be the connection between the client’s web browser and the server. It will take care of performing the operations at the server (let it be some kind of processes or calculations, or just a regular database access).</p>
<p>I’ll be using <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a> in this example. <strong>jQuery is a superb </strong><a title="Javascript frameworks" href="http://www.undisciplinedbytes.com/2009/10/javascript-frameworks-overview/" target="_blank">Javascript framework</a>, and is the one I use the most. If you don’t know what it is yet, then the first thing you should do is getting acquainted with it. This JavaScript framework has <a title="jQuery functions to make an AJAX call" href="http://docs.jquery.com/Ajax" target="_blank">many convenient functions to make an AJAX</a> call. These functions hide much of the complexity of an AJAX call: you can forget about the <a title="XMLHttpRequest" href="http://en.wikipedia.org/wiki/XMLHttpRequest" target="_blank">XMLHttpRequest</a> object if you wish, and only worry about what to do with the data once you get it back from the server.</p>
<p><span id="more-336"></span></p>
<p>So, in order to perform an AJAX request, we’ll follow these steps:</p>
<ol>
<li>We’ll perform an AJAX call from the client, using Javascript. As I said before, we’ll be using jQuery. It makes the process much easier.</li>
<li>We’ll construct some way for the server to receive the request: in this example we’ll use a regular .aspx web page.</li>
<li>We’ll fetch the data to be returned to the client. This example is just a proof of concept, so we’ll leave this task to the reader. We’ll just return the server time.</li>
<li>We’ll convert that data into JSON notation.</li>
<li>Once the data gets back to the client, the jQuery library takes care of the conversion of the string received from the server to a Javascript object.</li>
<li>In this point we’ll have the data available to us. We’ll do something with it to show it on screen, for example.</li>
</ol>
<p>Ok, we already have the theory covered. Now, let’s get to work! Start a new Visual Studio project, and get to the newly created page. On the C# codebehind of the new page we won’t be changing anything. Leave everything by default. We’ll be doing our work in the .aspx part. First, we’ll need a little bit of HTML to draw our page:</p>
<pre class="brush:xml">&lt;body&gt;
   &lt;form id="form1" runat="server"&gt;
     &lt;h2&gt;jQuery AJAX call test page&lt;/h2&gt;
     &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
     &lt;br /&gt;&lt;br /&gt;
     &lt;div id="DataContainer" &gt;&lt;/div&gt;
   &lt;/form&gt;
&lt;/body&gt;</pre>
<p>This is a very simple page. We’ll just have a heading, a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server.</p>
<p>Now we need some actual code to make the AJAX call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;

    function ExecuteAJAXCall() {
        $.ajax({
            url: "AJAXCall.aspx",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data;
    };

&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. We’re passing three parameters to the function: the URL of the page that will get called, they type of data we’re expecting back (JSON in this case) and the javascript function to execute once the data gets back to the client. The jQuery ajax function has <a href="http://api.jquery.com/jQuery.ajax/" target="_blank">many more parameters</a>, but we didn’t need them this time since the example is not very complicated.</p>
<p>The function called when the data is returned is very simple: its only purpose is to take the string returned from the server and write it in the container we previously created for this purpose. Note that the parameter it receives, data, is already a javascript object. The AJAX call returned a simple string from the server, but the jQuery function is smart enough to convert that string to a javascript object and pass it to the function we indicated.</p>
<p>Ok, so now that we have the test page in place, let’s deal with the AJAX call server-side. The <code>AJAXCall.aspx </code>page is the link between the client web browser and the server. Here we’ll process everything we need and we’ll return a string to the client with the data requested.</p>
<p>Here is the C# codebehind from the <code>AJAXCall.aspx</code> page:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

namespace jQueryAJAXCall
{
    public partial class AJAXCall : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) // Returns the server current date and time
        {
            JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            string CurrentDate = DateTime.Now.ToString();
            Response.CacheControl = "no-cache";
            Response.Write(JSSerializer.Serialize(CurrentDate));
        }
    }
}</pre>
<p>Note the <code>System.Web.Script.Serialization</code> class we’re importing. This class takes care of converting the object we want to return to JSON format.</p>
<p>This page is very simple: it just takes the current date and time from the server, converts it to JSON format and returns it. Nothing more is needed. Simple enough, right? Be aware that this page must not return anything else than the JSON string: if you’re using Visual Studio be careful when creating this new webpage, as VS adds a bunch of HTML code by default in the .aspx page. Erase all HTML code, otherwise your javascript won’t be able to understand the data sent back.</p>
<p>Note the line in which we deactivate the cache. If you don’t do this, the AJAX call will always seem to return the same data, as the web browser will have kept a copy of it the first time it was executed. Most AJAX calls need the cache disabled in order to work properly.</p>
<p>So this is it! Nothing else is required. Donwload the Visual Studio project and play with it as much as you want:</p>
<p><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/02/jQueryAJAXCall.zip">jQueryAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Different ways to use AJAX in ASP.NET</title>
		<link>http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/</link>
		<comments>http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 14:53:34 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=314</guid>
		<description><![CDATA[Today’s web applications are unthinkable without AJAX techniques. These techniques provide an improved user experience, and tighten the gap between traditional desktop applications and web applications. This means that mastering AJAX technologies is a must for anyone who’s doing serious web application development. In this article I’ll explain the basics of AJAX, and I will [...]]]></description>
			<content:encoded><![CDATA[<p>Today’s web applications are unthinkable without <a title="AJAX" href="http://en.wikipedia.org/wiki/AJAX" target="_blank">AJAX</a> techniques. These techniques provide an improved user experience, and tighten the gap between traditional desktop applications and web applications. This means that mastering AJAX technologies is a must for anyone who’s doing serious web application development. In this article I’ll explain the basics of AJAX, and I will show how to program some AJAX calls using ASP.NET technology.</p>
<p><span id="more-314"></span></p>
<h4>First things first: the basics</h4>
<p><a href="http://en.wikipedia.org/wiki/AJAX" target="_blank">AJAX</a> is a set of web application development techniques used to create <a href="http://en.wikipedia.org/wiki/Rich_Internet_application" target="_blank">RIA</a> (<em>Rich Internet Applications</em>). These techniques are used in the web browser at the client’s computer, while an asynchronous communication with the web server is held in the background. Thus, it is possible to make changes in the pages without the need to reload them, increasing interactivity, speed and usability in these applications, compared to traditional click-and-wait web pages.</p>
<p>An AJAX call is nothing more than a request to the server for some data. It is the same thing as when you type in a web page address in your browser’s address box and hit Enter: your browser requests the server the HTML code representing that webpage. The only difference is that with an AJAX call, all this process takes place in the background, without the user’s knowledge. It is performed programmatically, using JavaScript.</p>
<p>AJAX stands for <strong><em>Asynchronous JavaScript and XML</em></strong>, which means that in its first conception XML was used to transmit data from the server to the client. But XML is not used much anymore, <a title="JSON" href="http://en.wikipedia.org/wiki/Json" target="_blank">JSON</a> is the preferred notation for this task. JSON is a lighter notation as it uses less characters, and follows the natural syntax of the JavaScript language. This means that, once you’ve received the data from the server in your JavaScript code, it is much simpler and faster to process it if it’s in JSON notation.</p>
<p>Let’s see a couple of examples to understand it better. This would be <strong>XML</strong>:</p>
<pre class="brush:xml">&lt;Person firstName="John" lastName="Smith"&gt;
    &lt;address&gt;
      &lt;streetAddress&gt;21 2nd Street&lt;/streetAddress&gt;
      &lt;city&gt;New York&lt;/city&gt;
      &lt;state&gt;NY&lt;/state&gt;
      &lt;postalCode&gt;10021&lt;/postalCode&gt;
    &lt;/address&gt;
    &lt;phoneNumber type="home"&gt;212 555-1234&lt;/phoneNumber&gt;
    &lt;phoneNumber type="fax"&gt;646 555-4567&lt;/phoneNumber&gt;
    &lt;newSubscription&gt;false&lt;/newSubscription&gt;
    &lt;companyName /&gt;
&lt;/Person&gt;</pre>
<p>And this would be the same data transmitted in <strong>JSON</strong> notation:</p>
<pre class="brush:javascript">{
       "firstName": "John",
       "lastName": "Smith",
       "address": {
           "streetAddress": "21 2nd Street",
           "city": "New York",
           "state": "NY",
           "postalCode": 10021
       },
       "phoneNumbers": [
           { "type": "home", "number": "212 555-1234" },
           { "type": "fax", "number": "646 555-4567" }
       ],
       "newSubscription": false,
       "companyName": null
}</pre>
<p>As you can see XML is lengthier to transmit. Besides, as it is not natural to JavaScript, the data must be interpreted and translated to a JavaScript object once it gets to the client, whereas JSON must not. Don’t worry though, you won’t have to deal with converting data to JSON and back, all this is done automatically.</p>
<h4>Different ways of requesting data from the web server</h4>
<p>There are several different techniques used to retrieve data from the server using ASP.NET technology. The most common ones are:</p>
<ul>
<li><strong>URL.</strong> This is the most used technique to provide data through AJAX. Most JavaScript plugins are designed to work this way, so it can be considered the most important technique as well. At the server, this type of request can be processed using two different approaches:
<ul>
<li>The request is processed as if it was a regular web page</li>
<li>The request is processed through an HTTP Handler</li>
</ul>
</li>
<li><strong>Page method.</strong> Server methods can be easily called just by using an attribute.</li>
<li><strong>Web service.</strong> Web services can be consumed from JavaScript, providing for an easy way to request data to the server.</li>
<li><strong>Web sockets.</strong> Not quite AJAX itself, web sockets are here to revolutionize the logic behind traditional client-server communication. Web sockets bring full-duplex and server-initiated communications, two techniques not possible in the web till now. They belong to the new HTML5 specification, and as such must be treated, meaning there’s not much support for it yet.</li>
</ul>
<p>We’ll be taking a look at each of these techniques. Stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>jqGrid multiselect: a little improvement</title>
		<link>http://www.undisciplinedbytes.com/2009/11/jqgrid-multiselect-a-little-improvement/</link>
		<comments>http://www.undisciplinedbytes.com/2009/11/jqgrid-multiselect-a-little-improvement/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 15:00:14 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=77</guid>
		<description><![CDATA[The jqGrid plugin is fantastic. It provides an improved user experience and makes your web application stand out from the rest. But sometimes the default behaviour it has is not what we like, and those are the times when we have to dive into the source code to tweak it. And today was one of those [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.trirand.com/blog/" target="_blank">jqGrid plugin</a> is fantastic. It provides an improved user experience and makes your web application stand out from the rest. But sometimes the default behaviour it has is not what we like, and those are the times when we have to dive into the source code to tweak it. And today was one of those times for me.</p>
<p>We&#8217;ve implemented the jqGrid plugin in a couple of pages in our project at work. We needed some multiselect in one of them. This option seems very easy to implement: just add a couple of options at creation time and you&#8217;re done&#8230; well, not quite. JqGrid&#8217;s multiselect default behaviour is not really the standard one. I mean, it is a multiselect, just not what the regular user might be used to.</p>
<p><span id="more-77"></span></p>
<p>What I was expecting from a multiselect behaviour is to behave just as normal as long as no special key is pressed. I mean, if you have a row selected and  click on another with no other key pressed, then it should select the new one and deselect the old row. Well, jqGrid&#8217;s standard options lets you choose between always regular behaviour, or always multiselect. You can&#8217;t have multiselect <strong>only </strong>when a special key is pressed.</p>
<p>I didn&#8217;t like it. So I changed it. So here I&#8217;m posting the code that needs to be changed in case somebody wants this behaviour too. I wrote some comments throughout the code to clarify what I&#8217;m doing a bit.</p>
<p>Please note that <strong>these changes are made to the 3.4.4 version of jqGrid</strong>. If you&#8217;re using some other version, consult first whether this behaviour is not already implemented&#8230; or even if these changes can be made at all.</p>
<p>File <code>grid.base.js</code>. Line 193 &#8211; function <code>setSelection</code>:</p>
<pre class="brush:javascript">	// We get a parameter telling us whether the special multiselect key has been pressed
	// This parameter might not always be passed
	$.fn.setSelection = function(selection,onsr,sd,multiselectKeyPressed) {
		return this.each(function(){
			var $t = this, stat,pt, ind;
			onsr = onsr === false ? false : true;
			if(selection===false) {pt = sd;}
			else { ind = $($t).getInd($t.rows,selection); pt=$($t.rows[ind]);}
			selection = $(pt).attr("id");
			if (!pt.html()) {return;}
			if($t.p.selrow &amp;&amp; $t.p.scrollrows===true) {
				var olr = $($t).getInd($t.rows,$t.p.selrow);
				var ner = $($t).getInd($t.rows,selection);
				if(ner &gt;=0 ){
					if(ner &gt; olr ) {
						scrGrid(ner,'d');
					} else {
						scrGrid(ner,'u');
					}
				}
			}
			// If multiselect is enabled but the key has not been pressed, it's as if multiselect was disabled
			if(!$t.p.multiselect || (multiselectKeyPressed != null &amp;&amp; !multiselectKeyPressed)) {
				if($(pt).attr("class") !== "subgrid") {
				if( $t.p.selrow ) {
					// This only deselects the last selected row. Only one row was supossed to be selected simultaneously
					// $("tr#"+$t.p.selrow.replace(".", "\\."),$t.grid.bDiv).removeClass("selected");
					// This way we consider there may be more than one selected row. Deselects all selected rows:
					$("#" + this.id + " tr.selected").removeClass("selected");
				}
				$t.p.selrow = selection;
				$(pt).addClass("selected");
				if ($t.p.multiselect) {
					$t.p.selarrrow = new Array();  // Empty the array containing selected rows
					$t.p.selarrrow.push($t.p.selrow);  // Insert the new selected row
				}
				if( $t.p.onSelectRow &amp;&amp; onsr) { $t.p.onSelectRow($t.p.selrow, true); }
				}
			} else {
				$t.p.selrow = selection;
				var ia = $.inArray($t.p.selrow,$t.p.selarrrow);
				if (!$(pt).hasClass("selected") &amp;&amp; ia != -1) ia = -1;  // Might report as not in the array
				if (  ia === -1 ){
					if($(pt).attr("class") !== "subgrid") { $(pt).addClass("selected");}
					stat = true;
					$("#jqg_"+$t.p.selrow.replace(".", "\\.") ,$t.rows).attr("checked",stat);
					$t.p.selarrrow.push($t.p.selrow);
					if( $t.p.onSelectRow &amp;&amp; onsr) { $t.p.onSelectRow($t.p.selrow, stat); }
				} else {
					if($(pt).attr("class") !== "subgrid") { $(pt).removeClass("selected");}
					stat = false;
					$("#jqg_"+$t.p.selrow.replace(".", "\\.") ,$t.rows).attr("checked",stat);
					$t.p.selarrrow.splice(ia,1);
					if( $t.p.onSelectRow &amp;&amp; onsr) { $t.p.onSelectRow($t.p.selrow, stat); }
					var tpsr = $t.p.selarrrow[0];
					$t.p.selrow = (tpsr==undefined) ? null : tpsr;
				}
			}
			function scrGrid(iR,tp){
				var ch = $($t.grid.bDiv)[0].clientHeight,
				st = $($t.grid.bDiv)[0].scrollTop,
				nROT = $t.rows[iR].offsetTop+$t.rows[iR].clientHeight,
				pROT = $t.rows[iR].offsetTop;
				if(tp == 'd') {
					if(nROT &gt;= ch) { $($t.grid.bDiv)[0].scrollTop = st + nROT-pROT; }
				}
				if(tp == 'u'){
					if (pROT &lt; st) { $($t.grid.bDiv)[0].scrollTop = st - nROT+pROT; }
				}
			}
		});
	};</pre>
<p>Line 1433: event handling:</p>
<pre class="brush:javascript">		$(ts).before(grid.hDiv).css("width", grid.width+"px").click(function(e) {
			evt = window.event || e;  // Get the event
			td = (e.target || e.srcElement);
			if (td.href) { return true; }
			var scb = $(td).hasClass("cbox");
			ptr = $(td,ts.rows).parents("tr.jqgrow");
			if($(ptr).length === 0 ) {return false;}
			var cSel = true;
			if(bSR) { cSel = bSR(ptr.attr("id"));}
			if(cSel === true) {
				if(ts.p.cellEdit === true) {
					if(ts.p.multiselect &amp;&amp; scb){
						$(ts).setSelection(false,true,ptr);
					} else {
						ri = ptr[0].rowIndex;
						ci = !$(td).is('td') ? $(td).parents("td:first")[0].cellIndex : td.cellIndex;
						try {$(ts).editCell(ri,ci,true,true);} catch (e) {}
					}
				} else if ( !ts.p.multikey || !e[ts.p.multikey] ) {  // Check if the special multiselect key was pressed
					if(ts.p.multiselect &amp;&amp; ts.p.multiboxonly) {
						// Pass whether the special multiselect key was pressed
						if(scb){$(ts).setSelection(false,true,ptr,e[ts.p.multikey]);}
					} else {
						// Pass whether the special multiselect key was pressed
						$(ts).setSelection(false,true,ptr,e[ts.p.multikey]);
					}
				} else {
					if(e[ts.p.multikey]) {
						$(ts).setSelection(false,true,ptr);
					} else if(ts.p.multiselect &amp;&amp; scb) {
						scb = $("[id^=jqg_]",ptr).attr("checked");
						$("[id^=jqg_]",ptr).attr("checked",!scb);
					}
				}
				if(onSC) {
					ri = ptr[0].id;
					ci = !$(td).is('td') ? $(td).parents("td:first")[0].cellIndex : td.cellIndex;
					onSC(ri,ci,$(td).html(),td);
				}
			}
			e.stopPropagation();
		})</pre>
<p>But there&#8217;s still more. One of the great features of jqGrid is <strong>subgrid</strong>. This feature allows having a nested grid inside a row. When enabling the subgrid option, you&#8217;ll get one checkbox column. But this column it&#8217;s not really necessary, you might opt for hiding it out. If you do so when you have multiselect enabled, then the subgrids will look weird&#8230; they will have moved to the right, leaving an ugly blank space to the left&#8230; what happened?</p>
<p>When having multiselect enabled, the subgrid assumes you&#8217;ll always display the checkbox column. That&#8217;s all. So we can go the subgrid code and tweak it to check if the checkbox column is hidden.</p>
<p>File <code>grid.subgrid.js</code>, line 20 &#8211; Click event handler:</p>
<pre class="brush:javascript">.click( function(e) {
	if($(this).hasClass("sgcollapsed")) {
		pID = $("table:first",ts.grid.bDiv).attr("id");
		res = $(this).parent();
		var atd= pos==1?'&lt; td&gt;&lt; /td&gt;':'';

		// Begin modification
		// To reach the grid we need $(this).parent().parent().parent()
		$($(this).parent().parent().parent()[0].p.colModel).each(function(i) {
			// If CB column exists and it's hidden, there's one cell less
			if (this.name == 'cb' &amp;&amp; this.hidden) atd= pos==1?'':'';
		});
		// End modification

		_id = $(res).attr("id");
		bfsc =true;
		if($.isFunction(ts.p.subGridBeforeExpand)) {
			bfsc = ts.p.subGridBeforeExpand(pID+"_"+_id,_id);
		}</pre>
<p>I posted the code here just to see what the changes are. If you&#8217;re going to be using this modification, probably it&#8217;s going to be easier if you just download the modified files and replace them with the ones you have: <a href="http://www.undisciplinedbytes.com/wp-content/uploads/2009/10/grid.base.js" target="_blank">grid.base.js</a> and <a href="http://www.undisciplinedbytes.com/wp-content/uploads/2009/10/grid.subgrid.js" target="_blank">grid.subgrid.js</a> . <strong>Remember this modification is ONLY for version 3.4.4 of jqGrid!</strong></p>
<p>Hope this helps! If you have any doubt, don&#8217;t hesitate to <a href="mailto:olivermezquita@undisciplinedbytes.com">drop me a line</a>!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2009/11/jquery-grid-plugin-jqgrid/' rel='bookmark' title='Permanent Link: jQuery Grid plugin: jqGrid'>jQuery Grid plugin: jqGrid</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2009/11/jqgrid-multiselect-a-little-improvement/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery Grid plugin: jqGrid</title>
		<link>http://www.undisciplinedbytes.com/2009/11/jquery-grid-plugin-jqgrid/</link>
		<comments>http://www.undisciplinedbytes.com/2009/11/jquery-grid-plugin-jqgrid/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 15:00:00 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=96</guid>
		<description><![CDATA[JqGrid is a jQuery plugin which provides impressive AJAX-enabled dynamic data tables.  And when I say impressive, I mean fantastic. Not only it&#8217;s packed full of features, but it&#8217;s got a very nice look and feel as well. It&#8217;s got nothing to envy from traditional desktop application grids. I would say it&#8217;s even better than [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.trirand.com/blog/" target="_blank">JqGrid</a> is a jQuery plugin which provides <strong>impressive</strong> AJAX-enabled dynamic data tables.  And when I say impressive, I mean fantastic. Not only it&#8217;s packed full of features, but it&#8217;s got a very nice look and feel as well. It&#8217;s got nothing to envy from traditional desktop application grids. I would say it&#8217;s even better than many of them.</p>
<div id="attachment_98" class="wp-caption aligncenter" style="width: 395px"><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2009/10/jqGrid.jpg"><img class="size-full wp-image-98 " title="jqGrid" src="http://www.undisciplinedbytes.com/wp-content/uploads/2009/10/jqGrid.jpg" alt="Themeable interface: you can set it up as you wish" width="385" height="149" /></a><p class="wp-caption-text">Themeable interface: you can set it up as you wish</p></div>
<p><span id="more-96"></span></p>
<p>The most important features jqGrid has are:</p>
<ul>
<li><strong>Paging. </strong>This feature enables the developer to display data page by page. Data will not be retrieved from the server until the end user comes to that page. Developers can control how many rows are displayed at a time.</li>
<li><strong>Resizable Columns. </strong>Column width can be changed by the end user.</li>
<li><strong>Sorting &amp; various data types.</strong> The end user can sort records by clicking on the header of a column. Developers can specify sorting for various types including string, number, boolean, link, select and percent.</li>
<li><strong>Event handlers &amp; user API.</strong> Event handlers and various methods give you more flexibility without coding too much.</li>
<li><strong>Auto loading data when scrolling.</strong> This feature allows you to load data without paging and using only the vertical scrollbar.</li>
<li><strong>Working with local data.</strong> jqGrid can work with local data defined as an array.</li>
<li><strong>Cross browser.</strong> Supports IE 6.0+, FireFox 2.0+, Safari 3.0+, Opera 9.2+ and Google Chrome.</li>
<li><strong>Multilanguage support (i18n).</strong> JqGrid currently supports more than 20 languages.</li>
<li><strong>Support for XML, JSON and arrays as data sources</strong>. Another great feature is the possibility to define your own custom data type.</li>
<li><strong>SubGrids.</strong> Using a SubGrid is the easiest method for displaying data from child records.</li>
<li><strong>Inline editing.</strong> Allows to update the cell content in a particular row in an in easy way.</li>
<li><strong>Searching and filtering. </strong>The columns in the grid can be used as the basis for a search form to appear above, below, or in place of the grid.</li>
<li><strong>Import / Export.</strong> JqGrid is able to import or export the entire grid configuration to another file format.</li>
<li><a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:features" target="_blank">And many more!</a></li>
</ul>
<p>This is a Javascript plugin running on the client which communicates with the server through AJAX. This means that you can use any technology you like on the server: ASP, PHP, JSP, etc.</p>
<p>In some other post I&#8217;ll explain how set it up and get it working in an ASP.NET project&#8230;</p>
<p>Links:</p>
<ul>
<li><a href="http://www.trirand.com/blog/" target="_blank">jqGrid official web page</a></li>
<li><a href="http://www.trirand.com/jqgrid/jqgrid.html" target="_blank">Some demos</a></li>
<li><a href="http://www.trirand.com/jqgridwiki/" target="_blank">Documentation</a></li>
</ul>
<p>This is the grid I&#8217;m using at work. Both myself and the end users are very happy with this plugin. Check it out and see for yourself what I&#8217;m talking about!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2009/11/jqgrid-multiselect-a-little-improvement/' rel='bookmark' title='Permanent Link: jqGrid multiselect: a little improvement'>jqGrid multiselect: a little improvement</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2009/11/jquery-grid-plugin-jqgrid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

