Posts Tagged ajax

NaggieInside JSF 2.0’s Ajax and HTTP GET Support

Wednesday, March 17th, 2010

With support for these techniques, this newest version of the Java component UI framework enables developers to build truly dynamic web pages simply and easily.

At the highest level, JSF technology provides an API for creating, managing, and handling UI components and a tag library for using components within a web page. The JSF 2.0 release simplifies the web developer’s life by providing the following:

  • Reusable UI components for easy authoring of web pages
  • Well defined and simple transfer of application data to and from the UI
  • Easy state management across server requests
  • Simplified event handling model
  • Easy creation of custom UI components

For GET requests and Ajax integration, we need to drill down into JSF 2.0’s support, as well as the productive features that this support makes possible. The demo application is an online quiz that allows a registered user to answer five simple questions that test his or her general knowledge. Towards the end of the quiz, the application displays the score.

Using GET Requests in JSF 2.0

To support GET requests, JSF 2.0 introduced the concept of View Parameters. View Parameters provide a way to attach query parameters to URLs. You use the tag <f:viewParam> to specify the query parameters.
Take this code for example:
<f:metadata>
<f:viewParam name=”previousScore” value=”#{recordBean.oldScore}” />
</f:metadata>
In this example, the value of the parameter previousScore will be automatically picked up and pushed into the property oldScore of the recordBean. So, when a request like this comes for a URL:
displayData.jspx?previousScore=10

To support GET requests, JSF 2.0 introduced the concept of View Parameters. View Parameters provide a way to attach query parameters to URLs. You use the tag <f:viewParam> to specify the query parameters.

Take this code for example:

<f:metadata>

<f:viewParam name=”previousScore” value=”#{recordBean.oldScore}” />

</f:metadata>

In this example, the value of the parameter previousScore will be automatically picked up and pushed into the property oldScore of the recordBean. So, when a request like this comes for a URL:

displayData.jspx?previousScore=10

The value of the bean property oldScore will be set to 10 when the request is processed, which avoids manually setting the value or using a listener. Another interesting point to notice is that like any other component the tag <f:viewParam> supports conversion and validation. Hence, there is no need for separate conversion/validation logic.

The new tags in JSF 2.0 related to support for the GETrequest.

h:button :- Renders a button that generates a GET request without any handcoding of URLs

h:link :- Renders a link that generates a GET request without any handcoding of URLs

h:outputStylesheet :- Refers to a CSS resource

h:outputScript :- Refers to a JavaScript resource

f:event :- Registers a specification-defined or a user-defined event

f:ajax :- Enables associated component(s) to make Ajax calls

f:metadata :- Declares the metadata facet for this view

f:viewParam :- Used in to define a view parameter that associates a request parameter to a model property

f:validateBean :- Delegates the validation of the local value to the Bean Validation API

f:validateRegex :- Uses the pattern attribute to validate the wrapping component

f:validateRequired :- Ensures the presence of a value

Bookmarking Support

Because all JSF 1.x interactions with the server use only HTTP POST requests, those JSF versions don’t support bookmarking pages in a web application. Even though some tags supported the construction of URLs, it was a manual process with no support for dynamic URL generation. JSF 2.0’s support for HTTP GET requests provides the bookmarking capability with the help of new renderer kits.

A new UI component UIOutcomeTarget provides properties that you can use to produce a hyperlink at render time. The component allows bookmarking pages for a button or a link.

The two HTML tags that support bookmarking are h:link and h:button. Both generate URLs based on the outcome property of the component, so that the author of the page no longer has to hard code the destination URL. These components use the JSF navigation model to decide the appropriate destination.

Take the following code for example:

<h:link outcome=”login” value=”LoginPage” >

<f:param name=”Login” value=”#{loginBean.uname }” />

</h:link>

This bookmarking feature provides an option for pre-emptive navigation (i.e., the navigation is decided at the render response time before the user has activated the component). This pre-emptive navigation is used to convert the logical outcome of the tag into a physical destination. At render time, the navigation system is consulted to map the outcome to a target view ID, which is then transparently converted into the destination URL. This frees the page author from having to worry about manual URL construction.

Support for Ajax

The default implementation provides a single JavaScript resource that has the resource identifier jsf.js. This resource is required for Ajax, and it must be available under the javax.faces library. The annotation@ResourceDependency is used to specify the Ajax resource for the components, the JavaScript function jsf.ajax.request is used to send information to the server in an asynchronous way, and the JavaScript function jsf.ajax.response is used for sending the information back from the server to the client.

On the client side, the API jsf.ajax.request is used to issue an Ajax request. When the response has to be rendered back to the client, the callback previously provided by jsf.ajax.request is invoked. This automatically updates the client-side DOM to reflect the newly rendered markup.

The two ways to send an Ajax request by registering an event callback function are:

  • Use the JavaScript function jsf.ajax.request
  • Use the <f:ajax> tag

JavaScript Function jsf.ajax.request

The function jsf.ajax.request(source, event, options) is used to send an asynchronous Ajax request to the server. The code snippet below shows how you can use this function:

<commandButton id=”newButton” value=”submit”

onclick=”jsf.ajax.request(this,event,

{execute:’newButton’,render:’status’,onevent: handleEvent,onerror: handleError});return false;”/>

</commandButton/>

The first argument in the function represents the DOM element that made an Ajax call, while the second argument (which is optional) corresponds to the DOM event that triggered this request. The third argument is composed of a set of parameters, which is sent mainly to control the client/server processing. The available options are execute, render, onevent, onerror, and params.

<f:ajax> Tag

JSF 2.0 enables page authoring with <f:ajax>, which is a declarative approach for making Ajax requests. You can use this tag instead of manually coding the JavaScript for Ajax request calls. This tag serves two roles, depending on the placement. You can nest it within any HTML component or custom component. If you nest it with a single component, it will associate an Ajax action with that component.

The <f:ajax> tag has four important attributes:

  • render – ID or a space-delimited list of component identifiers that will be updated as a result of the Ajax call
  • execute – ID or a space-delimited list of component identifiers that should be executed on the server
  • event – The type of event the Ajax action will apply to (refers to a JavaScript event without the on prefix)
  • onevent – The JavaScript function to handle the event

Consider the following code from the login page of the online quiz application. The code validates the input of the email field by sending an Ajax call for every keystroke. The validation is done by a managed bean method that acts as a value change listener.

<h:inputText label=”eMail ID”   id=”emailId” value=”#{userBean.email}” size=”20″

required=”true” valueChangeListener=”#{userBean.validateEmail}”>

<f:ajax event=”keyup” render=”emailResult”/>

</h:inputText>

<h:outputText id=” emailResult” value=”#{userBean.emailPrompt}” />

 Inside JSF 2.0s Ajax and HTTP GET Support

Using Ajax to Validate the Input: The online quiz application validates email field input by sending an Ajax call for every keystroke.

Here, <f:ajax> is nested within the emailId inputText component. For every keyup event that is generated, an Ajax call is sent to the server, which invokes the valueChangeListener. By default, the component in which the tag is nested is executed on the server. So, the execute attribute is not specified. Also, for an input component, the default event is valueChange, so the event attribute is also not used. The render attribute indicates that the outputText component emailResult should be updated after the Ajax call.

If you place this tag around a group of components, it will associate an Ajax action with all the components that support the events attribute.

<f:ajax event=”mouseover”>

<h:inputText id=”input1″ …/>

<h:commandLink id=”link1″ …/>

</f:ajax>

In this example, input1 and link1 will exhibit Ajax behavior on a mouseover event.

<f:ajax event=”mouseover”>

<h:inputText id=”input1″ …>

<f:ajax event=”keyup”/>

</h:inputText>

<h:commandLink id=”link1″ …/>

</f:ajax>

In this example, input1 and link1 exhibit Ajax behavior on keyup and mouseover events, respectively.

Using the Ajax tag enhances the markup of the associated component to include a script that triggers the Ajax request. This the page author to issue Ajax requests without having to write any JavaScript code.

These new features enable developers to build truly dynamic web pages simply and easily.

http://www.developer.com

http://www.all1sourcetech.com

Tags: , , , , , ,
Posted in Expert's Opinions, Purely Technical | No Comments »

SuzanneWordPress Plugin Releases for 03/01

Saturday, March 6th, 2010

All these new wordpress plugins releases this month as follows:

123 Flash Chat- This new plugin can be used to create your own chat room in WordPress. It allows you to insert chat room to your sidebar, with either a light chat client or a link to standard chat client in popup mod. And you can define the width and height of 123 Flash Chat as well as its skin & language. The chat room displays a “hosted by 123flashchat.com free of charge” message.

Asynchronous Widgets- It allows you to have any registered widget on your WordPress.org-powered site be loaded asynchronously via an AJAX call.

WP-Tabbity- WP-Tabbity allows authors to create one or more tab groups containing one or more tabs, animated by the WordPress-included
version of jQuery.

WP Function Reference- It provides a box on the dashboard with a list of the functions that are available for you to use in your Wordpress installation.

Disable WordPress Updates- Disables the theme; plugin and core update checking, the related cronjobs and notification system.

http://www.all1martpro.com

http://get-a-designer.com

Tags: , , , ,
Posted in New Product Release | No Comments »

Naggie4 Steps to Consume Web Services using Ajax

Thursday, March 4th, 2010

Normally the browser Ajax controls calls the ASP.NET code and the ASP.NET code consumes the web service, but there are scenarios where you would like to call the web services directly from the Ajax JavaScript functions rather than calling via the behind code.

Here, you can get the same following 4 steps-

Step 1: Create your Customer Class

The first step is to create the customer class as shown below. So the customer class has 4 properties on customer id, first name, address and designation.

public class Customers
{
// private properties
private int _intCustomerID;
private string _strFirstName;
private string _strAddress;
private string _strDesignation;

// Public property and
public int CustomerID
{
get
{
return _intCustomerID;
}
set
{
_intCustomerID = value;
}
}
public string FirstName
{
get
{
return _strFirstName;
}
set
{
_strFirstName = value;
}
}

public class Customers
{
// private properties
private int _intCustomerID;
private string _strFirstName;
private string _strAddress;
private string _strDesignation;
// Public property and
public int CustomerID
{
get
{
return _intCustomerID;
}
set
{
_intCustomerID = value;
}
}
public string FirstName
{
get
{
return _strFirstName;
}
set
{
_strFirstName = value;
}
}

Step 2: Create your Web Service

The next step is to create the web service which exposes the customer class to UI. Here is a simple web service which has encapsulated customer collection. In the constructor, we are loading some dummy data into the list of customers as shown in the below code snippet:

[System.Web.Script.Services.ScriptService]
public class Customer : System.Web.Services.WebService {

// Customer collection
List<Customers> listcust = new List<Customers>();
public Customer ()
{
//Load some dummy data in to customer collection.
listcust.Clear();

Customers cust = new Customers();
cust.CustomerID = 1;
cust.FirstName = “Dan”;
cust.Address = “Live in UK”;
cust.Designation = “Software Developer”;
listcust.Add(cust);

cust = new Customers();
cust.CustomerID = 2;
cust.FirstName = “Sheen”;
cust.Address = “Live in Austrailia”;
cust.Designation = “Web Designer”;
listcust.Add(cust);

cust = new Customers();
cust.CustomerID = 3;
cust.FirstName = “Koraine”;
cust.Address = “Live in London”;
cust.Designation = “Architect”;
listcust.Add(cust);
}

// This function exposes all customers to the end client’
[WebMethod]
public List<Customers> LoadCustomers()
{
return listcust;
}

// This function helps us to get customer object based in ID
[WebMethod]
public Customers LoadSingleCustomers(int _customerid)
{
return (Customers)listcust[_customerid-1];
}

Two functions have been exposed with the web service, one which gives out a list of customers and another which gives out individual customer data based on customer id.

Step 3: Reference your Web Service using the asp:servicereference

Using the ‘asp:ServiceReference’, the path to the ASMX file will be pointed as shown in the below code snippet. This will generate the JavaScript proxy which can be used to call the customer object.

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="Customer.asmx" />
    </Services>
</asp:ScriptManager>

Step 4: Call the Webservice and the JavaScript Code

Once you have defined the proxy, you can now call the ‘Customer’ proxy directly to make method calls.

function LoadAll()
{
Customer.LoadCustomers(LoadCustomerToSelectOption, ErrorHandler, TimeOutHandler);
}

When you call the JavaScript proxy object, then you need to provide three functions; the first function (‘LoadCustomerToSelectOption’) will be called when the web service finishes and returns data. The data will be returned in the fill variable which will then be looped and added to the customer combo box.

function LoadCustomerToSelectOption(Fill)
{
var select = document.getElementById(”cmbCustomers“);

for (var i = 0; i < Fill.length; i++)
{
var value = new Option(Fill[i].FirstName, Fill[i].CustomerID);
select.options.add(value);
}
}

There are two more functions which are attached; one which handles error and the other which handles time out.

function ErrorHandler(result)
{
var msg = result.get_exceptionType() + “\r\n“;
msg += result.get_message() + “\r\n“;
msg += result.get_stackTrace();
alert(msg);
}
function TimeOutHandler(result)
{
alert(”Timeout :” + result);
}

http://www.all1martpro.com
http://get-a-designer.com

Tags: , , , , , ,
Posted in Microsoft Technology, Purely Technical | No Comments »

SuzannePostback Text Processing with the AJAX Modal Dialog

Friday, February 26th, 2010

In this case the developer wanted to use an AJAX Editor Control inside a ModalPopup control.

This isn’t a problem but, the user needed to clicking the OK button to cause a post-back so that he could execute some server –side logic.

The ”Ok” Button is an ASP.NET control but adding a Click Event Handler for the button didn’t solve the problem because it didn’t get executed when the use Clicked on the “Ok” button.

Normally the ModalPopupExtender would be used like this.

    <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
                 TargetControlID="LinkButton1"
                 PopupControlID="Panel1"
                 BackgroundCssClass="modalBackground"
                 DropShadow="true"
     1.)         OkControlID="OkButton"
     2.)         OnOkScript="onOk()"
                 CancelControlID="CancelButton" />

Line number 1 tells the control to catch the click event for the Ok Button Control instance and line 2 specifies when CLIENT SIDE JavaScript code to execute when the control specifies in line 1 is clicked.

The post-back doesn’t happen (even if the ASP.NET Button control has a click event handler defined in code behind because the control doesn’t propagate it.)

So Just delete those two lines !

It turns out that they are optional and if you delete them the click event is not trapped and the code behind will execute as expected.

So just nake it look like this:

    <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
                 TargetControlID="LinkButton1"
                 PopupControlID="Panel1"
                 BackgroundCssClass="modalBackground"
                 DropShadow="true"
                 CancelControlID="CancelButton" />

http://www.all1sourcetech.com

http://www.all1martpro.com

Tags: , , , , ,
Posted in Microsoft Technology, Purely Technical | No Comments »

NaggieVisual Studio 2010 clean application level web.config

Friday, February 19th, 2010

Introducing new small improvement that has been made in Visual Studio 2010 & .NET 4 to reduce the size of the ASP.NET application level web.config 3.0 and 3.5 web.config

As ASP.NET technology evolved, the application level Web.config had new things added to it. Since the earlier frameworks were using the same set of machine level configuration files, incremental feature that was added subsequent to the 2.0 release resulted in additional config settings included in the file.
.NET 4 web.config

With .NET 4, the web.config is tremendously reduced in size to improve the simplicity of ASP.NET

The config settings have been moved down to the machine config file. This includes registers all of the ASP.NET tag sections, handlers, modules and settings for the following:
• ASP.NET AJAX
• ASP.NET Dynamic Data
• ASP.NET Routing
• ASP.NET Chart Control

You can look at the trimmed down web.config by creating a .Net 4 ‘ASP.NET Empty Web Application’ in Visual Studio 2010.

Following is the web.config file for .NET 4 C# ‘ASP.NET Empty Web Application’:

image thumb Visual Studio 2010 clean application level web.config

The config file above has settings to tell ASP.NET to enable debugging by default for the application and provides the version of .NET framework to use.

http://www.all1tunes.com

http://www.all1social.com

Tags: , , , , , , ,
Posted in Microsoft Technology, Purely Technical | No Comments »