Archive for the ‘AJAX’ Category

Getting POST values with an ASHX file

Today I had this scenario where I wanted to post items from multiple HTML input elements to a generic handler (.ashx) file without using the action attribute of the form. Specifying the action meant that that you are navigated away from the page where the action is happening, which means re-creating UI logic. How did I achieve this? By using an XMLHttpRequest and using a POST method. GET places everything inside a querystring, which is ok, but I just wondered what would happen if the content was too long for the querystring. I guess the same can be said for POST, but it just seems POST uses a different way to transfer the data. So lets say you had this JavaScript:

    getXMLHTTPPostObject: function(url, elementName, parameters) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", url, true);
        xmlhttp.send(parameters);
    }

I use this function to create an XMLHttpRequest object by passing it:

  • the URL for the AJAX call
  • an elementName to put the result of request in
  • A parameter list

I then have a function like this:

    addPost: function() {
        objXMLHTTP.getXMLHTTPPostObject("url to handler", "categoryTemp", "postTitle=" + document.getElementById("txtPostTitle").value + "&blogpost=" + document.getElementById("txtBlogPost").value);
    }

The function gets the values of two HTML input elements and passes it as parameters. The parameters are then used in the POST HTTPMethod. My next challenge was to get the data in the generic handler (.ashx) so that I can process it. I also wanted to return the data from the ASHX file to see that its processed successfully. So in my handler I created this code:

        context.Response.ContentType = "text/plain";
        System.IO.Stream body = context.Request.InputStream;
        System.Text.Encoding encoding = context.Request.ContentEncoding;
        System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
        //if (context.Request.ContentType != null)
        //{
        //    context.Response.Write("Client data content type " + context.Request.ContentType);
        //}
        string s = reader.ReadToEnd();
        string[] content = s.Split('&');
        for (int i = 0; i < content.Length; i++)
        {
            string[] fields = content[i].Split('=');
            context.Response.Write("
" + fields[0] + "
"); context.Response.Write("
" + fields[1] + "
"); } //context.Response.Write(s); body.Close(); reader.Close();

I first create a class of type Stream that is instantiated through the Response.InputStream property, after which I set the content encoding for the response object. I then create a StreamReader instance and call its ReadToEnd method. After this I do some string manipulation and return the text back to the XMLHttpRequest object, which then writes the content to an HTML Element.

  • Share/Bookmark

JavaScript alphabetical sorting (A is less than a)

So A < a, which means if you use the sort() function and your array contains elements starting with upper and lowercase then the uppercase will appear first, i.e.:

Art, ASP.NET, LawDeed, LINQ will appear as:
ASP.NET
Art
LawDeed
LINQ

To get this working correctly you need the following function:

    charOrdA: function(a, b) {
        a = a.toLowerCase(); b = b.toLowerCase();
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
    }

This function will make sure your alphabetical sortorder is correct so that the list appears like this:
Art
ASP.NET
LawDeed
LINQ

You have to pass the function name to the sort function like this:


arrCategories.sort(charOrdA);

Note that there are no parenthesis.

  • Share/Bookmark

Getting to understand JavaScripts prototypal nature

One of the things that are quite weird to get use to, from a C# developer’s perspective, is JavaScript’s prototypical nature. Check out this basic example:


var objXMLHTTP =
{
    getXMLHTTPObject: function(url,elementName) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
};
objXMLHTTP.getXMLHTTPObject("http://localhost/YieldTester/Handler.ashx", "testDiv");

The code above creates a simple XMLHTTPRequest object, but you do not create an instance of the object, you call it directly. Note objXMLHTTP.getXMLHTTPObject. In C# you might have created an object and then you instantiate it through an instance of that object. I have taken the code as is given on W3Schools and modified it a little.

  • Share/Bookmark

Understanding JavaScript from a C# developer’s perspective

So during the week I did a lot of JavaScript and the thing that I found most, what shall I say, mindshiftable, is that you cannot think in the classical OOP way with JavaScript, as you do with C#. JavaScript does everything in functions, and everything within JavaScript is prototypical. Inheritance is prototypical, everything is prototypical. You dont create instances of objects but rather use the objects themselves. So its kinda like a static class, where you invoke members directly.

I started this week by looking at a SOAP client written in JavaScript that makes calls to web services. What the SOAP client basically does is cache the WSDL with all the functions in it, from a web service (in this case an asmx file), and then it sends SOAP requests, processes the request and if there is a callback it does the callback function. The code for the SOAP client is based on this code.

  • Share/Bookmark

Unobtrusive JavaScript and a Session-less shopping cart

What is the idea behind unobtrusive JavaScript? What makes JavaScript unobtrusive? Does it mean removing any onlclick events in your markup and handling those click events with an approach as provided with jQuery? With jQuery its very (extremely) easy to traverse between DOM elements and its even easier associating events to elements and executing them.

I havent been doing a lot of JavaScript recently but you cannot really avoid it, but you can also not build an entire website with JavaScript and HTTPRequests alone (not search engine friendly), but you can also not rely entirely on server side code to do all the magic for you.

The other issue that has been bugging me of late is the idea of creating a session-less shopping basket, a shopping basket that uses a combination of web services and traditional classes. Within the .NET environment the only reason you might need to use sessions is to store DataTables or DataSets, but the question is how expensive is that on server resources. Would I be able to create the same session-based application with web services and traditional classes? After all you are adding web references to your web applications, and those web references all contain class declarations.

  • Share/Bookmark

Demystifying some .NET Issues

What seemed a little odd to me today was that SQL Server Express 2005 is download-able from two places. Both shows different file sizes.

Another issues that needs clarity is ASP.NET and .NET framework versions. .NET 3.5 is an ‘extension’ of .NET 2.0 and replaces .NET 3.0. .NET 3.5 covers AJAX (Asynchronous JavaScript and XML) and LINQ (Language Integrated Query)

  • Share/Bookmark

jQuery and Microsoft

I susbscribe to The Code Project’s newsletter and today I got some great news, jQuery will be supported in Visual Studio 2008. Now this is some awesome news. Makes one wonder if the Microsoft AJAX library will become redundant.

You can read the full article on Scott Gu’s website.

  • Share/Bookmark

Light up the Web – Mix Essentials 2008 Review

I attended the Mix Essentials 2008 event at Canal Walk (Cape Town, South Africa) today and there were quite a few things that interested me. There were five speakers at the event:

  1. David Ives – Developer and Platform Strategy Group for Microsoft in South Africa – Microsoft
  2. Brad Abrams – Group Program Manager for the UI Framework and Services Team – Microsoft
  3. Michael Koester – Designer Marketing Manager for Middle East and Africa and Central and Eastern Europe – Microsoft
  4. Julian Harris – Conchango
  5. David Pugh-Jones – Microsoft

The event was split into two tracks, a developer track and a designer track, but it generally focussed on Silverlight, and more specifically on two software packages, Visual Studio 2008 and Expression Studio, and even more specifically it introduced XAML as a common way for these packages to share content between them. XAML, Extensible Application Markup Language is an XML-like language that defines graphic elements in a human readable form that can be used in vector-imaging programs as well as Visual Studio 2008. This gives designers the flexibility to design interfaces without having to worry about programmers not being able to replicate their designs in a programming environment. Julian Harris demonstrated that you can export files from Adobe Illustrator into XAML format and import that XAML into Visual Studio 2008. XAML is also used in the Expression Studio range of products which includes amongst other two interesting products:

  • Expression Blend
  • Expression Design

Expression Blend is, almost like Adobe’s Flash Studio, which is an IDE that allows you to create WPF (Windows Presentation Foundation) and Silverlight applications. WPF is a technology that allows developers (and designers) to create applications that give users a better user experience (UX). Contemporary windows applications generally use square (often mundane) windows, whereas WPF applications allow designers to implement creative graphics into the interface. Rounded corners and transparent backgrounds for instance are used, and because Expression Blend can read and understand XAML, none of a designer’s creative flair is lost. The developer no longer has any excuses to develop interfaces that do not exactly meet the designer’s design.

  • Share/Bookmark

What is AJAX? Part2

This article and its contents are based on the articles on the W3C Website, and is a great place to start learning.

AJAX uses the XMLHTTPRequest JavaScript object to communicate directly with the web server and has three important properties:

  • the onreadystatechange property
  • the readystate property
  • the responsetext property

It’s important to note that the XMLHTTPRequest object is not supported by Internet Explorer which uses an ActiveX object, and for that reason when you create an XMLHTTPObject in JavaScript you have to add a few try/catch statements so that it returns the correct object for the correct browser.

If you want to use AJAX on a webpage it is thus important to understand that you need an XMLHTTPRequest object to make it possible. JavaScript is used to create the XMLHTTPRequest object and looks like this:

function GetXMLHTTPObject()
{
     var xmlHttp = null;
     try
     {
          xmlHTTP = new XMLHttpRequest();
      }
      catch(e)
      {
          try
          {
              xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch(e)
          {
              xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
      }
     return xmlHttp;
}
  • Share/Bookmark

What is AJAX? Part1

I downloaded the LiveValidation script recently and I realised after implementing it on a webpage I did not understand how it interacts with a PHP or ASP.NET application and it got me thinking that maybe I need to just try and understand how server-side and client-side code interacts with JavaScript.

What is AJAX? I know it’s an acronym for Asynchronous JavaScript and XML, but what does it really mean and how does it work. Client- and Server-side scripting is easy to understand on their own and its easy to understand how both technologies are used, but where it becomes tricky for myself is when the server-side and client-side code need to interact with each other. Developing web applications with ASP.NET does not always expose a developer to the inner workings of that specific technology. AJAX is not unique to PHP or ASP.NET. Both ASP.NET and PHP are server side scripting languages. The first thing to understand is that AJAX is not a technology on its own, nor is it something that has not been there before, because it uses existing technologies (JavaScript, XML) to do what it does. AJAX uses a combination of programming tools to create web-based applications that react more like software applications – this means that the web-based application responds much smoother and nicer and the page does not reload to retrieve new content.

I still have not defined what AJAX looks like or what it exactly does. AJAX is based on open standards such as HTML, CSS, XML and JavaScript. AJAX uses XML and HTTP Requests to communicate with a web server. Another important thing to note is that with AJAX web applications do not re-submit a web page every time a user makes a request. If for example a user enters data on a form and submits the information to a web server, the web server will traditionally create a new page after the submit has occurred, but AJAX communicates with the web server in such a way that updates to the page only happen to the sections of the page that are affected.

  • Share/Bookmark
Get Adobe Flash playerPlugin by wpburn.com wordpress themes