Click here to Skip to main content
Click here to Skip to main content

Retrieval of a record into an array using AJAX

By , 15 Apr 2013
 

Introduction

This tip is based on the retrieval of data from the database by using AJAX in a web method in an array.
 
Generally while retrieving data from the database through a SQL query most of the time, the database operations take time so loading of data takes longer. To reduce this time we can use AJAX which will do it in a short period of time, and it will be admirable by clients and end users.

Here is a simple example of how to use a simple array in AJAX.

Form Structure

The form structure is as follows:

<div id="EditDiv" class="editdv" runat="server" clientidmode="Static">
    <div class="leftDiv" id="left" runat="server">
        <asp:Label class="labelprop" ID="lblProductName" 
          runat="server" Text="ProductName:"></asp:Label>
        <asp:Label class="labelprop" ID="lblDescription" 
          runat="server" Text="Description:"></asp:Label>
        <asp:Label class="labelprop" ID="lblPrice" 
          runat="server" Text="ListPrice:"></asp:Label>
        <asp:Label class="labelprop" ID="lblDiscount" 
          runat="server" Text="Discount:"></asp:Label>
        <asp:Label class="labelprop" ID="lblQuantity" 
          runat="server" Text="Quantity:"></asp:Label>
        <asp:Label class="labelprop" ID="lblColor" 
          runat="server" Text="Color:"></asp:Label>
        <asp:Label class="labelprop" ID="lblRating" 
          runat="server" Text="Rating:"></asp:Label>
        <asp:Label class="labelprop" ID="lblOS" 
          runat="server" Text="OS:"></asp:Label>
        <asp:Label class="labelprop" ID="lblMFGDate" 
          runat="server" Text="ManufacturingDate:"></asp:Label>
        <asp:Label class="labelprop" ID="lblItemSold" 
          runat="server" Text="ItemSold:"></asp:Label>
    </div>
    <div class="centerDiv" id="centerDiv">
        <asp:TextBox class="textBoxprop" ID="txtProductName" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtProductdesc" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtPrice" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtDiscount" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtQuantity" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtColor" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtRating" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtOS" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtMFGDate" runat="server"></asp:TextBox>
        <asp:TextBox class="textBoxprop" ID="txtItemSold" runat="server"></asp:TextBox>
    </div>
    <div class="imageUpdate" runat="server">
    <span id="spnReturnVal" runat="server"></span>
        <img id="image" src="Photos/jackass-logo-wallpaper.JPG" alt="Image" 
                    align="bottom"  width="200" height="200" /><br />
            <asp:LinkButton ID="lbtChange" runat="server" OnClientClick="return Upload();" 
                  style="display:block;" >Change Image</asp:LinkButton><br />
        <asp:FileUpload ID="upldImage" runat="server" Width="216px" />
    </div>
    <div class="bottomDiv">
        <asp:Button ID="btnUpate" runat="server" 
          Text="update" Width="100px" OnClick="btnUpate_Click" />
        <asp:Button ID="btnCancel" runat="server" 
          Text="cancel" Width="98px" OnClick="btnCancel_Click" />
        <br />
        
    </div>
</div> 

WebMethod

The Web Method is as follows:

[WebMethod]
public static string[] editItems(string tableName, string productId)
{
    SqlConnection myConnection = null;
    string[] myarray = null;
    DataSet ds = new DataSet();
    try
    {
        //Database connection is set here.
        myConnection = newSqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
                    myConnection.Open();
        string query = @"select productName,
                     description,
                     listPrice,
                     discount,
                     quantity,
                     color,
                     rating,
                     OS,
                     manufacturingdate,
                     itemSold,
                     pic
          from
          " + tableName
          + " where productId = '" +
          productId + "'";
        SqlDataAdapter adp = new SqlDataAdapter(query, myConnection);
        adp.Fill(ds);
        myarray = new string[11]; 
        //Assigning the values into the array. 
        myarray[0] = ds.Tables[0].Rows[0]["productName"].ToString();
        myarray[1] = ds.Tables[0].Rows[0]["description"].ToString();
        myarray[2] = ds.Tables[0].Rows[0]["listPrice"].ToString();
        myarray[3] = ds.Tables[0].Rows[0]["discount"].ToString();
        myarray[4] = ds.Tables[0].Rows[0]["quantity"].ToString();
        myarray[5] = ds.Tables[0].Rows[0]["color"].ToString();
        myarray[6] = ds.Tables[0].Rows[0]["rating"].ToString();
        myarray[7] = ds.Tables[0].Rows[0]["OS"].ToString();
        myarray[8] = ds.Tables[0].Rows[0]["manufacturingdate"].ToString();
        myarray[9] = ds.Tables[0].Rows[0]["itemSold"].ToString();
        myarray[10] = ds.Tables[0].Rows[0]["pic"].ToString();
    }
    catch (Exception)
    {
        return null;
    }
    Finally
    {
        MyConnection.Close();  //closing the connection.
    }
    return myarray;
}

AJAX Function

The AJAX function is as follows:

 function editItems() {
//Assigning the hiddenfield value to the ID.
var id = $("input[id*='hfProductId']").val();
$.ajax({
    type: "post",
    url: "HomePage.aspx/editItems",
    contentType: "application/json; charset=utf-8",
    //Parameters are passed to the WebMethod.
    data: "{tableName: 'productDetails' , productId: '" + id + "'}", 
    dataType: "json",
    beforeSend: function () {
        $("[id$= 'spnReturnVal']").html(
           "<img src='Photos/processing.gif' />"); //Processing image.
    },
    success: function (msg) {
    //Applying the css property to the div.
    $("[id$='EditDiv']").css("display", 'block');
    //Hiding the div using the css property.
    $("[id$='hiddenDiv']").css("display", 'inline');
    $("[id$='upldImage']").css("display", 'none');
    if (msg.d != null) {
    //Assigning the data according to the control IDs.
    $("[id$='txtProductName']").val(msg.d[0]);
    $("[id$='txtProductdesc']").val(msg.d[1]);
    $("[id$='txtPrice']").val(msg.d[2]);
    $("[id$='txtDiscount']").val(msg.d[3]);
    $("[id$='txtQuantity']").val(msg.d[4]);
    $("[id$='txtColor']").val(msg.d[5]);
    $("[id$='txtRating']").val(msg.d[6]);
    $("[id$='txtOS']").val(msg.d[7]);
    $("[id$='txtMFGDate']").val(msg.d[8]);
    $("[id$='txtItemSold']").val(msg.d[9]);
    $("[id$='image']").attr('src', msg.d[10]);    
    }    
    else {
        alert("Null Value");
    }
    alert("Now You  Can Change The ItemProoerties...");
    },
    //Error Block.
    error: function (msg) {
        alert("Sorry for the inconvinience. Please try again.");
    }
});
return false;
} 

Conclusion

This above function returns the record from the database using AJAX and fills it into the form. One can use this function for pre-population of the data from the database into a form.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

sisirp88
Software Developer
India India
Member
I love learning...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5professionalTadit Dash2 May '13 - 0:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130513.1 | Last Updated 15 Apr 2013
Article Copyright 2013 by sisirp88
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid