Onlineatoz.net | All posts by admin

Samples programs for working with Ajax

AJAX Overview

AJAX stands for Asynchronous Javascript And XML which is based on the Javascript and HTTP Requests.moreover its a new way of technology to use existing standards since its not a programming language.it can be used to creating better, faster, and more interactive web applications.

we can using JavaScript to communicate directly with the server by using Ajax with the XMLHttpRequest object. it helps to accessing the web server without reloading the page.AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server that allowing web pages to request small bits of information from the server instead of whole pages.

AJAX based on the Following

  • JavaScript
  • XML
  • HTML
  • CSS
AJAX Provide better Internet-applications

Normally, Website applications are using more than the desktop applications; they can reach a much more audience, they are easier to handling, and easier to develop. However, Internet-applications are not always as "rich" and user-friendly as desktop applications. we can using AJAX to provide Internet applications with richer and more user-friendly.

How AJAX is Working?

Ajax working as a programming model with display and events. These events are user actions, they call functions associated to elements of the web page.

To read and retrieve the contents from the server, XMLHttpRequest provides two methods:

  • open: create a connection.
  • send: send a request to the server.

Server Provided the Data by using attributes of XMLHTTPRequest objects as:

  • responseXml for an XML file or
  • responseText for a plain text.

along the time of processing the data, the state of data is given by the readyState attribute of XMLHttpRequest.those ready states are as follows,

  • 0: not initialized.
  • 1: connection established.
  • 2: request received.
  • 3: answer in process.
  • 4: finished.
AJAX with DHTML

Dynamic HTML contains the following

  • HTML
  • CSS
  • JavaScript

DHTML can be used to change the page display according to the user commands or user text. Ajax allows also to send requests asynchronously and load data from the server.

The XMLHttpRequest object

the following Objects are used by AJAX to interact with the Server

Attributes
  • readyState -the code successively changes value from 0 to 4 that means for "ready".
  • status -200 : ok, 404 : page not found
  • responseText -holds loaded data as a string of characters.
  • responseXml -holds an XML loaded file, DOM's method allows to extract data.
  • onreadystatechange property that takes a function as value that is invoked when the readystatechange event is dispatched.
Methods
  • open(mode, url, boolean)  here mode: GET or POST   url: the location of the file, with a path.  boolean: true (asynchronous) / false (synchronous).
  • send("string") null for a GET command.
Performing a request Step1: Create instance

use the following code snippets that denotes Instance of the Class, and two options for browser compatibility,

if (window.XMLHttpRequest)  // Object of the current windows
{
xhr = new XMLHttpRequest(); // Firefox, Safari, ...
}
else
if (window.ActiveXObject) // ActiveX version
{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
}
 
Step2: wait for the Response

The response of the server will be assigned to the onreadystatechange attribute of the object previously created.

 xhr.onreadystatechange = function()
if (xhr.readyState == 4)
{
// Received, OK
} else
{
// Wait...
}
Step3: Perform a Request

Two methods of XMLHttpRequest are used:

  • open: GET or POST
  • send: with POST only, the data to send to the server.

 

xhr.open('GET', 'http://www.xul.fr/somefile.xml', true);                  
xhr.send(null);
 
Examples

Get a Text

                  
<html>
<head>
<script>
function submitForm()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}

xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};

xhr.open(GET, "data.txt", true);
xhr.send(null);
}
</script>
</head>

<body>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>

Get a XML
To get data from an XML file, we have just to replace the code as:

                  
var doc = xhr.responseXML; // Assign the XML file to a var
var element = doc.getElementsByTagName('root').item(0); // Read the first element
document.ajax.dyn.value= element.firstChild.data; // Assign the content to the form

Write on Body
the text read is put into the body of the page

                  
document.getElementById("zone").innerHTML = "Received:" + xhr.responseText;

Post a Text
a text is sent to the server and is written into a file.

                  
xhr.open("POST", "ajax-post-text.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
Using an external file

here,we can include a JavaScript file and calling a function using following code,

                  
<script src="ajax.js" type="text/javascript"></script>
var xhr = createXHR();
 
Disadvantages
  • Ajax will not works when a JavaScript is not activated, . The user must be asked to set JavaScript from within options of the browser, with the "noscript" tag.
  • Since data to display are loaded dynamically, they are not part of the page, and the keywords inside are not viewed by search engines.
  • The asynchronous mode may change the page with delays (when the processing on the server take some times), this may be disturbing.
  • The back button may be deactivated (this is not the case in examples provided here). This may be overcomed.

f67ef5e2-6921-4ca5-8e9c-f2cd44813b2f|1|


Posted by: Admin
Posted on: 9/14/2011 at 8:44 AM
Categories: Ajax
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Bind Data into gridview in asp.net

Gridview Control

in .Net,it is an one of the major control. The GridView control helps you to display the number of items on a page from the Database without taking much space, with the help of paging. here, you can easily includes the paging in your application. The built-in paging concept of the Gridview is pretty good.

As soon as the number of items increases, the performance suffers. The main reason for the performance kill is that whenever you go to a new page of the GridView, it fetches all the items from the database.The GridView control helps you to selecting the item, sorting the item, and edit these items. in Gridview, every column denotes a field,every row denotes a record

Gridview features

The GridView control supports the following features:

  • Binding to data source controls, such as SqlDataSource.
  • Built-in sorting
  • Built-in paging
  • Built-in update and delete
  • Built-in row selection
  • Multiple key fields.
  • Multiple data fields for the hyperlink columns.
  • pretty themes and styles
  • Built-in row selection
Column Fields

in Gridview,Each column can be denoted by a DataControlField object. By default, the AutoGenerateColumns property is true, than generates all the columns in the gridview underneath the data source.but if you are set the AutoGenerateColumns as false,then you want to generate columns manually.

Column Field Types
  • BoundField -Displays the value of a field in a data source. This is the default column type of the GridView control.
  • ButtonField -Displays a command button for each item in the GridView control. This enables you to create a column of custom button controls, such as the Add or the Remove button.
  • CheckBoxField -Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value.
  • CommandField -Displays predefined command buttons to perform select, edit, or delete operations.
  • HyperLinkField -Displays the value of a field in a data source as a hyperlink. This column field type enables you to bind a second field to the hyperlink's URL.
  • ImageField -Displays an image for each item in the GridView control.
  • TemplateField -Displays user-defined content for each item in the GridView control according to a specified template. This column field type enables you to create a custom column field.
Binding Data to Gridview

The following 2 methods can be used to bind the GridView control to the appropriate data source type:

  • For binding data source control, set the DataSourceID property of the GridView control to the ID value of the data source control.
  • or programmatically set the DataSource property of the GridView control to the data source and then call the DataBind() method.
Gridview Properties

The following properties enables you to customizing the Gridview appearance.

  • AlternatingRowStyle -The style settings for the alternating data rows in the GridView control. When this property is set, the data rows are displayed alternating between the RowStyle settings and the AlternatingRowStyle settings.
  • EditRowStyle -The style settings for the row being edited in the GridView control.
  • EmptyDataRowStyle -The style settings for the empty data row displayed in the GridView control when the data source does not contain any records.
  • FooterStyle -The style settings for the footer row of the GridView control.
  • HeaderStyle -The style settings for the header row of the GridView control.
  • PagerStyle -The style settings for the pager row of the GridView control.
  • RowStyle -The style settings for the data rows in the GridView control.
  • SelectedRowStyle -The style settings for the selected row in the GridView control.
  • ShowFooter -Shows or hides the footer section of the GridView control.
  • ShowHeader -Shows or hides the header section of the GridView control.
Gridview Events
  • PageIndexChanged -Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different page in the control.
  • PageIndexChanging -Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This event is often used to cancel the paging operation.
  • RowCancelingEdit -Occurs when a row's Cancel button is clicked, but before the GridView control exits edit mode. This event is often used to stop the canceling operation.
  • RowCommand -Occurs when a button is clicked in the GridView control. This event is often used to perform a task when a button is clicked in the control.
  • RowCreated -Occurs when a new row is created in the GridView control. This event is often used to modify the contents of a row when the row is created.
  • RowDataBound -Occurs when a data row is bound to data in the GridView control. This event is often used to modify the contents of a row when the row is bound to data.
  • RowDeleted -Occurs when a row's Delete button is clicked, but after the GridView control deletes the record from the data source. This event is often used to check the results of the delete operation.
  • RowDeleting -Occurs when a row's Delete button is clicked, but before the GridView control deletes the record from the data source. This event is often used to cancel the deleting operation.
  • RowEditing -Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode. This event is often used to cancel the editing operation.
  • RowUpdated -Occurs when a row's Update button is clicked, but after the GridView control updates the row. This event is often used to check the results of the update operation.
  • RowUpdating -Occurs when a row's Update button is clicked, but before the GridView control updates the row. This event is often used to cancel the updating operation.
  • SelectedIndexChanged -Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. This event is often used to perform a task after a row is selected in the control.
  • SelectedIndexChanging -Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. This event is often used to cancel the selection operation.
  • Sorted -Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. This event is commonly used to perform a task after the user clicks a hyperlink to sort a column.
  • Sorting -Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. This event is often used to cancel the sorting operation or to perform a custom sorting routine.
 
Example 1

the following examples represents that assigned data source to the Gridview through SqlDataSource Control

<html>
<head id="Head1" runat="server">
<title>GridView Example</title>
</head>
<body>
<form id="form2" runat="server">
<h3>
GridView Example</h3>
<asp:GridView ID="CustomersGridView" DataSourceID="CustomersSource"
AutoGenerateColumns="true" EmptyDataText="No data available."
AllowPaging="true" runat="server">
</asp:GridView>
<asp:SqlDataSource ID="CustomersSource" SelectCommand="Select
[CustomerID], [CompanyName], [Address], [City], [PostalCode],
[Country] From [Customers]"
ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server" />
</form>
</body>
</html>
 
Example 2

the following examples represents that assigned data source to the Gridview through Programmatically

in .aspx page

<asp:GridView ID="CustomersGridView" DataSourceID="CustomersSource"
AutoGenerateColumns="false" EmptyDataText="No data available." AllowPaging="true"
runat="server"> </asp:GridView>

in .aspx.cs page

    protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings[1].ConnectionString);
string query = "select UserId,UserName from UserDetails";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt=new DataTable();
sda.Fill(dt);
CustomersGridView.DataSource = dt;
CustomersGridView.DataBind();
}

//for Paging
protected void gvImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
CustomersGridView.PageIndex = e.NewPageIndex;
SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings[1].ConnectionString);
string query = "select UserId,UserName from UserDetails";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt=new DataTable();
sda.Fill(dt);
CustomersGridView.DataSource = dt;
CustomersGridView.DataBind();
}

Posted by: Admin
Posted on: 9/14/2011 at 8:33 AM
Categories: Asp.net
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed