Accessing Web Services Using Javascript

I will demonstrate how to acccessing WebMethod(WebServices) using Javascript, this is very simple, and sometimes you will need it when you face the condition to validate the field plus you should check/validate it by sending the data to server, not neccessary when you validate at the server, but when comes up to validate in client side, I meant the trigger was on client script, using javascript as example, then this point can be your solution.

I build DataAccess class with implement with “IDisposable” to manage garbage collection, I named this DataAccess.cs.

using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
/// <summary>
/// Summary description for DataAccess
/// </summary>
public class DataAccess : IDisposable
{
    private static SqlCommand command;
    private static SqlConnection sqlConnection;
    private DataTable dataTable;
    private SqlDataAdapter adap;
    public SqlConnection SqlConnection
    {
        get { return sqlConnection; }
        set { sqlConnection = value; }
    }
    public SqlCommand Command
    {
        get { return command; }
        set { command = value; }
    }
    public DataAccess()
    {
         string  _sqlConnectiong = ConfigurationManager.ConnectionStrings["LucianConString"].ConnectionString;
            SqlConnection = new SqlConnection(_sqlConnectiong);
        if (SqlConnection.State == ConnectionState.Closed)
        SqlConnection.Open(); 
    }
    public void SqlCommand(string sqlcommandText)
    {
        if (command == null)
            command = new SqlCommand(sqlcommandText);
        command.CommandType = System.Data.CommandType.StoredProcedure;
             command.Connection = SqlConnectiong;
    }
    public void SetParameter(SqlParameter parameter)
    {
        command.Parameters.Clear();
        command.Parameters.Add(parameter);
    }
    public DataTable ExecuteDataTable()
    {
        adap = new SqlDataAdapter(command);
        dataTable = new DataTable();
        adap.Fill(dataTable);
        return dataTable;
    }
    private string sqlConnectiong;
    public SqlConnection SqlConnectiong
    {
        get { return sqlConnection; }
        set { sqlConnection = value; }
    }
    public void Dispose()
    {
        if (SqlConnection.State == ConnectionState.Open)
            SqlConnection.Close();
        
        SqlConnection.Dispose();
        dataTable.Dispose();
        Command.Dispose();
    }
}

I created WebServices to access this DataAccess, as note, you should uncomment this attribute [System.Web.Script.Services.ScriptService] by doing this this webservices can be accessed by javascript

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
/// <summary>
/// Summary description for WebServices
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebServices : System.Web.Services.WebService
{
    public WebServices()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod]
    public bool Validate(string usernmae)
    {
        using (DataAccess db = new DataAccess())
        {
            db.SqlCommand("SELECT_USERNAME");
            db.SetParameter(new System.Data.SqlClient.SqlParameter("@USERNAME", usernmae));
            DataTable table = db.ExecuteDataTable();
            if (table.Rows.Count >= 1)
                return false;
            else
                return true;
        }
    }
}

The next step is creating javascript to access that web service, but before proceed you should remember, previously i already mentioned that I create the example just for input validation only, wheather the text or data already exist or not in database, so this would be very simple and you can read the code easily even though i didn't expalin it

 function ValidateField(myvalue) {
     var resultField = myvalue.value;
     var userContext = null;
     WebServices.Validate(resultField, onCompleting, OnValidateFieldError, userContext);
 }
 function onCompleting(result, usercontext) {
    if (result)
     document.getElementById("resultField").innerHTML = "<img src='Images/ClickIcon.png' >";
   else
       document.getElementById("resultField").innerHTML = "<img src='Images/xIcon.png' >";
 
 }
 function OnValidateFieldError(result) {
     alert('There is something problems');
 }


The last step was we set up your UI, in this context was aspx page, for note, that you should put  scriptmanager to load webservices, unless the WebService method can not be identified by javascript,  here for the detail



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>
<!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>Dummy Page</title>
    <script src="ClientScript.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scriptManager" runat="server">
      <Services>
        <asp:ServiceReference Path="~/WebServices.asmx" />
      </Services>
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td>
                    <asp:TextBox runat="server" ID="TxtUsername" onblur="ValidateField(this)"></asp:TextBox>
                </td>
                <td>
                  <span id="resultField">
                  </span>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

The result would be like this when ever you make a change to the field, if the data was exist on the database then X icon will be shown, unless checklist will be showing up. ResultScreen

Hope this post was useful.



Thanks,

0 comments:

Post a Comment