How to retrieve data from database using JavaScript in asp.net

I was checking how to validate a user email from database without post back, using JavaScript. After some search and RND found the way to call the web service method with the help of Ajax and JavaScript.

Let’s say we have a registration page on which we accept email from the user and we expect it should be unique in entire database. So we need a method to immediately validate the email from database once user leave the email text box (onblur).

Here is the web service:

namespace TestApp.WebServices
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    /*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 Users : System.Web.Services.WebService
    {
         [WebMethod]
         [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
         public bool CheckUserEmail(String email)
         {
             // Code to check and return result    
         }
    }
}

Now we need to register our web service with ScriptManager to call from JavaScript, let's do this

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

Note: path is the folder path where we created our web service

Every thins is set, now we can call our web method "CheckUserEmail" from JavaScript function, before calling it let me clear some points. To call the web method, we need would need to user the full path with namespace as well.

 <asp:TextBox ID="txtemail" runat="server" 
     CssClass="txt2" 
     onblur="ValidateEmail(this)"
     MaxLength="100" />  
  <asp:Literal id="ltErr" runat="server" />

<script type="text/javascript">
 function ValidateEmail(txt)
 {
    TestApp.WebServices.Users.CheckUserEmail(txt.value, onSuccess();
 }

 function onSuccess(data)
 {
    if(data == ture)
          document.getElementById('<%= ltErr.ClientID %>').value = 'Available!';
    else
           document.getElementById('<%= ltErr.ClientID %>').value = 'Already in user!';
 }
</script>

In the same way you can save records to database.

What about if you need a record of address table and want to get the object of address in JavaScript, it simple, clear a class in the same web service namespace before this line " [WebService(Namespace = "http://tempuri.org/")]"

public class AddressInfo   
{        
    public string Street = string.Empty;
    public string City = string.Empty;
    public string State = string.Empty;
    public string ZipCode = string.Empty;
    public string Country = string.Empty;
}

Retrieve the data from database and convert that into AddressInfo and return from web method and you will get an object of Address Info, let me show the the JavaScript code for this:

function onSuccess(data)
{
     var address = data;
     alert(data.Street );
     alert(data.Country );
}
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • javascript
  • sql server
  • asp.net
By Ali Adravi On 24 Jun, 12  Viewed: 14,719

Other blogs you may like

A handy tutorial on creating Page Load Progress Bar using Pace.js

A website isn't complete without the inclusion of all the right elements. Progress bar is one of the key components of every website. It informs the user about the total waiting time for a particular web page or a specific task to load. Apart from adding value to the website, the progress bar is... By Celin Smith   On 18 Feb 2015  Viewed: 4,984

JavaScript isNaN function and usage

In JavaScript we have a function isNan (Not a number) to check whether the value is a number or not. It takes only one parameter, value and returns true or false, we will check here some values and conditions to understand it better. It supports in all browsers. isNaN(123); // false --... By Jason Olivera   On 30 Mar 2013  Viewed: 539

JavaScript Array: Create, Aceess and Methods

ArrayList and JavaScript, How to declare and store an ArrayList inside JavaScript, create an array in javascript, add item to javascript array, delete an item in an array in javascript, find an item in an array in javascript, these are the very basic question which most of the new developer... By Hamden   On 30 Dec 2012  Viewed: 849

Use JavaScript to hide and show text and graphics

You can show and hide the content to get attention of the user on a web page. it's a very useful thing for web designer and web developers. You can use JavaScript and CSS to achieve it. I am going to show some examples of it. There are many libraries available on internet having the feature to... By Hamden   On 30 Dec 2012  Viewed: 785

JavaScript getAttribute() Method

In JavaScript getAttribute() method is used to get the value of an attribute in an object. **Syntax:** object.getAttribute(attributename) **Parameter:** It takes only one parameter *attributename* **Example:** Suppose you have an anchor tag with following attributes <a... By Alicia Gonzalez   On 02 Dec 2012  Viewed: 708