Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

How to return data from ajax call

In this post,I will show you how to return data from ajax request.As you know that you can not return data from ajax request but if you want to perform some action on return data of ajax.The better approach is to organize your code properly around callbacks. In the example,you can make GetUsers accept a callback and use it as success callback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReturnAjax.aspx.cs" Inherits="ReturnAjax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            function GetUsers(name, callback) {
                $.ajax({

                    type: "POST",
                    async: true,
                    url: "ReturnAjax.aspx/GetUsers",
                    data: "{name:'" + name + "'}",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        //Pass return data to callback function and do the operation
                        callback(data.d);
                    }
                });
            }
            $("#check").click(function () {
                GetUsers($("#txtName").val(), function (users) {
                    $('#result').empty();
                    $.each(users, function (index, user) {
                        $('#result').append('<p><strong>' + user.UserId + ' ' + user.Name + '</br>');

                    });
                });
            });
        });

      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <input type="button" name="check" value="check " id="check" /><br />
        <div id="result">
        </div>
    </div>
    </form>
</body>
</html>
AjaxReturn.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static UserData[] GetUsers(string name)
    {
        return UserData.Users.Where(x => x.Name.StartsWith(name)).ToArray();
    }
}
public class UserData
{
    public string UserId { get; set; }
    public string Name { get; set; }

    public static List<UserData> Users
    {
        get
        {
            return new List<UserData>()
                      {
                          new UserData(){UserId = "1",Name = "Bill"},
                          new UserData(){UserId = "2",Name = "Booler"},
                          new UserData(){UserId = "3",Name = "Scott"},
                          new UserData(){UserId = "4",Name = "Anders"},
                      };
        }
    }
}

How To Check That Your Browser support ajax

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Untitled Page</title>
<script type = "text/javascript">
function GetXmlHttpObject() {
 var xml_Http = null;
 try {
    // Firefox, Opera 8.0+, Safari
    xml_Http = new XMLHttpRequest();
    }
 catch (e) {
    // Internet Explorer
    try {
       xml_Http = new ActiveXObject("Msxml2.XMLHTTP");
       }
    catch (e) {
       xml_Http = new ActiveXObject("Microsoft.XMLHTTP");
       }
    }
 return xml_Http;
 }
function check() {
 window.xmlHttp = GetXmlHttpObject();
 if (window.xmlHttp == null) {
    alert ("Your browser does not support AJAX!");
    return null;
    }
 else {
    alert("Your Browser support ajax");
    }
 }

</script>
</head>
<body onload="check();">
</body>
</html>

How To Use ASP.NET and HTTPrequest POST method

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserCheck.aspx.cs" Inherits="UserCheck" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>

  <script type = "text/javascript">
  function validateuserid(suserid) {
  document.body.style.cursor = 'wait';
  // Create an instance of the XML HTTP Request object
  var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
  //debugger;
  // Prepare the XMLHTTP object for a HTTP POST to our validation ASP.net page
  var sURL = "http://localhost/MyPractice/check.aspx";
  oXMLHTTP.open( "POST", sURL, false );
  oXMLHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  // Execute the request
  oXMLHTTP.send("userID=" + suserid);
  //alert(oXMLHTTP.responseText);
  if (oXMLHTTP.responseText == "exists")
   document.getElementById("test").innerText = "Sorry - the User ID already exists.";
  else
  document.getElementById("test").innerText = "the User ID is available.";
  }
</script>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <input type="text" name="userid" value="" onchange="validateuserid(this.value)">
           <span id="test"></span>
       </div>
     
   </form>
</body>
</html>
Check.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Check.aspx.cs" Inherits="Test" %>

Check.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string sUserID = Request.Form["userID"].ToString();
        if (sUserID == "Me")
        {
            Response.Write("exists");
        }
    }
}

How TO Use XMLHTTP Object in C#

Step 1 . Add a reference to the Microsoft,Ver3.0 (Msxml 3/4) in your project Step 2.Import the namespace using MSXML2;
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MSXML.aspx.cs" Inherits="MSXML" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MSXML2;

public partial class MSXML : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // to get page data (using msxml4)
        XMLHTTP40 http = new XMLHTTP40();
        http.open("GET", "http://localhost/MyPractice/Result.aspx?search=" + TextBox1.Text + "", false, null, null);
        http.send(null);
        string value = http.responseText;
        Response.Write(value.ToString());
    }
}

How To Create Ajax Based Search Page using xmlHTTP








<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
//global variable for hold XMLHttpRequest Object
var xmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to a "xmlHttp" variable
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
//it will work if IE have JavaScript version 5.0
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
xmlHttp = null;
}
}
//Creating object of XMLHTTP for non-IE browsers
if(!xmlHttp && typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
}
}
//function to search
function doSearch(searchText) {
//create XMLHttpRequest Object
CreateXmlHttp();
//Requested url
var ajaxRequest = "http://localhost/MyPractice/Result.aspx?search=" + searchText;
//set callback function
xmlHttp.onreadystatechange = callBackMethod;
//Initializes request
xmlHttp.open("GET", ajaxRequest, true);
//send request
xmlHttp.send(null);
}
function callBackMethod() {
//if request completed sucessfully clear the previous result and show the new search results
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearResults();
showResults();
}
}
}
//function clear previous results
function clearResults() {
var tableBody = document.getElementById("tbSearchResults");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
//function show search results in a table
//dynamically creating table rows for show the results
function showResults() {
//debugger;
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var results = xmlHttp.responseXML;


var customerid = "";
var companyname = "";
var ContactName = "";
var customers = results.getElementsByTagName("Customer");
if(customers.length < 1)
return;
//add header of the search table
addHeader();
//dynamically add search results in a table
for(var i = 0; i < customers.length; i++) {


customerid = results.getElementsByTagName("CustomerID")[i].firstChild.data;
companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data;
ContactName = results.getElementsByTagName("ContactName")[i].firstChild.data;
//creating new table row
addTableRow(customerid, companyname, ContactName);
}
document.getElementById("tblSearchResults").setAttribute("border", "1");
document.getElementById("tblSearchResults").setAttribute("class", "searchtable");
}
}
}
//function for creating new table row
function addTableRow(customerid, companyname, ContactName) {
var row = document.createElement("tr");
var cell = createCellWithText(customerid);
row.appendChild(cell);
cell = createCellWithText(companyname);
row.appendChild(cell);
cell = createCellWithText(ContactName);
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}
//function for create a cell with text
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode(text);
cell.appendChild(textNode);
return cell;
}
//add headers of the search result table
function addHeader() {
var row = document.createElement("tr");
var cell = createCellWithText("CustomerID");
row.appendChild(cell);
cell = createCellWithText("CompanyName");
row.appendChild(cell);
cell = createCellWithText("ContactName");
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}

</script>

</head>
<body>
<form id="Form1" method="post" runat="server">
<b>Search For Books</b> <span id="header"></span>
<table width="500" border="0">
<tbody>
<tr>
<td>
Search</td>
<td>
<input type="text" onkeyup="doSearch(this.value);" size="40">
</td>
</tr>
<tr>
<td colspan="2">
<table id="tblSearchResults" width="100%" border="0">
<tbody id="tbSearchResults">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>


Result.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Result.aspx.cs" Inherits="a" %>



Result.aspx.cs



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string search = Request["search"];
if (search.Length > 0)
{
Response.Clear();
DataSet dsResults = new DataSet();
//call business layer method for search results
dsResults = getvalue(search);
Response.Clear();
Response.ContentType = "text/xml";
Response.Charset = "utf-8";
string resultsString = dsResults.GetXml();
Response.Write(resultsString);
//end the response
Response.End();
}
else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}
}

else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}

}
private DataSet getvalue(string s)
{

SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
SqlDataAdapter da = new SqlDataAdapter("select * from customers where customerid like '%" + s + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds,"Customer");
return ds;

}
}

Asynchronous Request to Server (JavaScript)




I this post i will show how to send Asynchronous Request to Server which will Query the Database for certain information. Here, I am giving one example, which will send an Asynchronous Request to server for Checking the availablity of the Customerid by the user against database.

Step1.Create a new page(Async.aspx) and write down following code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Async.aspx.cs" Inherits="Async" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function CheckUserNameAvailablity1()
{
var name=document.getElementById('<%=TextBox1.ClientID%>').value;
CheckUserNameAvailablity2(name);
return false;
}
function CheckUserNameAvailablity2(Name)
{
try
{
var Source = new ActiveXObject("Microsoft.XMLDOM");
var XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
var ElemList;
var Request = "DOM.aspx?Name=" + Name;
XmlHttp.open("POST",Request,false);
XmlHttp.send();
Source.async = false;
if (Source.loadXML(XmlHttp.responseText) == true)
{
ElemList = Source.getElementsByTagName("tblAjaxEx");
if(ElemList.length > 0)
alert("Entered USerName is already Exists..");
else
alert("Entered UserName is available..");
}
}
catch(Ex)
{
alert(Ex.message);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="UserName:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return CheckUserNameAvailablity1()" />
</div>
</form>
</body>
</html>

Step2.Create a second Page Dom.aspx and remove all the html except Page attribute and write down the following code

DOM.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DOM.aspx.cs" Inherits="DOM" %>



DOM.aspx.cs



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class DOM : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CheckUserNameAvailablity(Convert.ToString(Request.QueryString["Name"]).ToUpper());
}
}
private void CheckUserNameAvailablity(string Name)
{
DataSet dsDataSet = new DataSet();
string strSQL = "Select customerid From customers Where Upper(customerid) = '" + Name + "'";
SqlConnection cn = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
cn.Open();
SqlDataAdapter adAdapter = new SqlDataAdapter(strSQL, cn);
adAdapter.Fill(dsDataSet, "tblAjaxEx");
Response.Clear();
if (dsDataSet != null)
dsDataSet.WriteXml(Response.OutputStream);
Response.End();
}
}

Autosugget Using xmlHTTP in Asp.net




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoSuggest.aspx.cs" Inherits="AutoSuggest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type="text/javascript">
var req;

function Initialize()
{
try
{
req=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
req=null;
}
}

if(!req && typeof XMLHttpRequest!="undefined")
{
req= new XMLHttpRequest();

}

} function SendQuery(key)
{
Initialize();
var url="http://localhost/MyPractice/AutoSuggest.aspx?k="+key;
//debugger;
if(req!=null)
{
req.onreadystatechange = Process;
req.open("GET", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

req.send(null);

}

}

function Process()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
if(req.responseText=="")
HideDiv("autocomplete");
else
{
ShowDiv("autocomplete");
var result=req.responseText;
document.getElementById("autocomplete").innerHTML =result;



}
}
else
{
document.getElementById("autocomplete").innerHTML=
"There was a problem retrieving data:<br>"+req.statusText;
}
}
}

function ShowDiv(divid)
{
if (document.layers) document.layers[divid].visibility="show";
else document.getElementById(divid).style.visibility="visible";
}

function HideDiv(divid)
{
if (document.layers) document.layers[divid].visibility="hide";
else document.getElementById(divid).style.visibility="hidden";
}

function BodyLoad()
{
HideDiv("autocomplete");
document.form1.keyword.focus();

}
</script>

</head>
<body onload="BodyLoad();">
<form name="form1">
<input name="keyword" onkeyup="SendQuery(this.value)" style="width: 500px" autocomplete="off">
<div align="left" class="box" id="autocomplete" style="width: 500px; background-color: #ccccff">
</div>

</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class AutoSuggest : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs args)
{
string keyword = Request["k"];
if (keyword != null && keyword.Trim() != "")
{
string sql = "select top 10* from customers where companyname like '" + keyword.Trim().Replace("'", "''") + "%'";
SqlConnection conn = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=12345");
conn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
conn.Close();

foreach (DataRow row in dt.Rows)
{
string meaning = row["Customerid"].ToString();
Response.Write("<html><body><table><tr><td>");
Response.Write("<strong>" + row["companyname"].ToString() + "</strong> <i>");
Response.Write(row["contactname"].ToString() + "</i>: " + meaning + "<br>");
Response.Write("</td></tr></body></html></table>");
}
}


}

}
(Only works in Mozila)

Performing a Server Request Asynchronously






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="XmlHTTP2.aspx.cs" Inherits="XmlHTTP2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type = "text/javascript" language="javascript">
var xmlHttpObj;
if (window.ActiveXObject) {
try {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
}
else xmlHttpObj = new XMLHttpRequest();
function LoadCustomers() {
if (xmlHttpObj) {
// We want this request synchronous
xmlHttpObj.open("GET", "http://" + location.host + "/MyPractice/DataFile.xml", false);
// Execute the request
xmlHttpObj.send(null);
// If the request was ok (ie. equal to a Http Status code of 200)
if (xmlHttpObj.status == 200) {
var xmlDoc = xmlHttpObj.responseXML;
// Our list of <CUSTOMER> nodes selected using the X Path argument
//var nodes = xmlDoc.selectNodes("//Customers/Customer");
var nodes = xmlDoc.selectNodes("//Customers/Customer/Lastname/text()");
// Obtain a reference to the <SELECT> drop list control.
var ctrl = document.getElementById("ddlCustomers");
for (var i = 0; i < nodes.length; i++) {
// Get the lastname element from our XML data document
var lastName = nodes[i].nodeValue;
// Create a new <OPTION> node.
var htmlCode = document.createElement('option');
// Add the new <OPTION> node to our <SELECT> drop list
ctrl.options.add(htmlCode);
// Set the <OPTION> display text and value;
htmlCode.text = lastName;
htmlCode.value = lastName;
}
}
else {
alert('There was a problem accessing the Customer data on the server.!');
}
}
}

function DisplayCustomerDetails() {
if (xmlHttpObj) {
// We want this request asynchronous
//debugger;
xmlHttpObj.open("GET", "http://" + location.host + "/MyPractice/DataFile.xml", true);
xmlHttpObj.onreadystatechange = function() {
if ( xmlHttpObj.readyState == 4 ) {
var ctrl = document.getElementById("ddlCustomers");
var doc = xmlHttpObj.responseXML;
var lastName = ctrl.options[ctrl.selectedIndex].value;
var node = doc.selectSingleNode("//Customers/Customer[Lastname='" +lastName + "']");
var details = 'Fullname : ' + node.selectSingleNode('Firstname / text()').nodeValue + '' + lastName + '. Email : ' + node.selectSingleNode('email / text()').nodeValue;
document.getElementById("spnDetailDisplay").childNodes[0].nodeValue = details;
}
}
// Execute the request
xmlHttpObj.send(null);
}
}
</script>
</head>
<body onload="LoadCustomers();">
<form id="form1" runat="server">
<div>
<select id="ddlCustomers" onchange="DisplayCustomerDetails();">
<option value="">- Select a Customer -</option>
</select>
<hr />

<p>
Details:</p>
<span id="spnDetailDisplay">(You have not made a selection yet.)</span>

</div>
</form>
</body>
</html>
DataFile.xml



<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer>
<Firstname>Joe</Firstname>
<Lastname>Bloggs</Lastname>
<email>joe@bloggs.com</email>
</Customer>
<Customer>
<Firstname>Alan</Firstname>
<Lastname>Anonymous</Lastname>
<email>anon@ymous.com</email>
</Customer>
<Customer>
<Firstname>Marvin</Firstname>
<Lastname>Martian</Lastname>
<email>marvin@mars.com</email>
</Customer>
</Customers>