Call asmx Web Service using jQuery AJAX in ASP.Net

Last Reply one year ago By dharmendr

Posted one year ago

Hi I am getting the [object object error] while calling the webservice in asp.net using jquery Ajax. I have made a simple web Application. In this Application i have made one simple Webservice named EmployeeService and calling it through one Asp.net Webform. But i am not getting he proper results.I am getting the [object object error]  But when i call the same Webservice using HTML page iam getting the proper results. Please help me with this. I am copying the same codes below....

Please reply As soon as Possible....i am waiting for your help...

Thanking you,

 

EmployeeService.asmx Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;

namespace Jquery_Practise_Application
{
/// <summary>
/// Summary description for EmployeeService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.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 EmployeeService : System.Web.Services.WebService
{

[WebMethod]

public Employee GetEmployeeById(int employeeId)
{
Employee employee = new Employee();

string cs = ConfigurationManager.ConnectionStrings["Om"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
cmd.CommandType = CommandType.StoredProcedure;


cmd.Parameters.Add(new SqlParameter("@Id", employeeId));

con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
employee.Id = Convert.ToInt32(rdr["Id"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Salary = Convert.ToInt32(rdr["Salary"]);
}
}

return employee;
}
}
}

Webform2.aspx Page Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Jquery_Practise_Application.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Jquery Ajax</title>
<script src="jquery-3.3.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" type= "application/xml, text/xml",>
$(document).ready(function () {
$('#btnGetEmployee').click(function () {
debugger;
var empId = $('#txtId').val();

$.ajax({
url:'<%= Page.ResolveUrl("~/EmployeeService.asmx/GetEmployeeById")%>',


//%= Page.ResolveUrl("~/Customers.aspx/GetCurrentTime")%
data: { employeeId: empId },
type: 'post',
dataType: 'xml',
success: function (data) {
var jQueryXml = $(data);
$('#txtName').val(jQueryXml.find('Name').text());
$('#txtGender').val(jQueryXml.find('Gender').text());
$('#txtSalary').val(jQueryXml.find('Salary').text());
},
error: function (err) {
alert(err);
}
});
});
});
</script>

</head>
<body style="font-family:Arial">

<form id="form1" runat="server">
<div>
ID :<asp:TextBox ID="txtId" runat="server" style="width:100px"></asp:TextBox>
<asp:Button ID="btnGetEmployee" runat="server" Text="Get Employee" />
<br /><br />
<table border="1" style="border-collapse:collapse">
<tr>
<td>Name</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Gender</td>
<td><asp:TextBox ID="txtGender" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Salary</td>
<td><asp:TextBox ID="txtSalary" runat="server"></asp:TextBox></td>
</tr>
</table>
</div>
</form>
</body>
</html>

Webform2.aspx.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;

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

 

Posted one year ago

Hi Omega,

Refer below code.

SQL

CREATE PROCEDURE spGetEmployeeById
	@Id INT
AS
BEGIN
	SELECT * FROM Employee WHERE Id = @Id
END

EmployeeService.asmx

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

/// <summary>
/// Summary description for EmployeeService
/// </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 EmployeeService : System.Web.Services.WebService
{

    public EmployeeService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public Employee GetEmployeeById(int employeeId)
    {
        Employee employee = new Employee();

        string cs = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@Id", employeeId));
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                employee.Id = Convert.ToInt32(rdr["Id"]);
                employee.Name = rdr["Name"].ToString();
                employee.Gender = rdr["Gender"].ToString();
                employee.Salary = Convert.ToInt32(rdr["Salary"]);
            }
        }

        return employee;
    }

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}

HTML

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnGetEmployee').click(function () {
                var empId = $('#txtId').val();
                $.ajax({
                    url: '<%= ResolveUrl("EmployeeService.asmx/GetEmployeeById")%>',
                    data: { employeeId: empId },
                    type: 'post',
                    dataType: 'xml',
                    success: function (data) {
                        var jQueryXml = $(data);
                        $('#txtName').val(jQueryXml.find('Name').text());
                        $('#txtGender').val(jQueryXml.find('Gender').text());
                        $('#txtSalary').val(jQueryXml.find('Salary').text());
                    },
                    error: function (err) {
                        alert(err.responseText);
                    }
                });

                return false;
            });
        });
    </script>
</head>
<body style="font-family: Arial">
    <form id="form1" runat="server">
    <div>
        ID :<asp:TextBox ID="txtId" runat="server" Style="width: 100px"></asp:TextBox>
        <asp:Button ID="btnGetEmployee" runat="server" Text="Get Employee" />
        <br />
        <br />
        <table border="1" style="border-collapse: collapse">
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Gender
                </td>
                <td>
                    <asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Salary
                </td>
                <td>
                    <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Screenshot