Ritesh Gupta Ritesh Gupta - 6 months ago 24
Ajax Question

Ajax function not calling

I am trying to call web service using ajax call in AngularJS Application and want to display data. But its not reaching to function. what is the problem.

AJAX Call-

function EmpCtrl($scope) {
$scope.getEmployee = function () {
$.ajax({
type: "POST",
url: "EmpWebService.asmx/GetEmployee",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(msg).find('Table').each(function (i, row) {

$scope.Name = $(row).find('empName').text();
$scope.Age = $(row).find('empAge').text();
$scope.City = $(row).find('empCity').text();

});
}
});
};
}


Here is my web service

[WebMethod]
public static string GetEmployee()
{
string connectionStr = ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString;
SqlConnection con = new SqlConnection(connectionStr);
SqlCommand cmd;
DataTable dt;

try
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "select * from Emp_TempTbl";
using(SqlDataAdapter sda=new SqlDataAdapter (cmd))
{
using (DataSet ds=new DataSet ())
{
sda.Fill(ds);
return ds.GetXml();
}
}
}
catch(Exception)
{
throw;
}


And here is Angular JS UI

<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head runat="server">
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
<script>
angular.module('myApp', [])
.controller('EmpCtrl', EmpCtrl);
</script>
</head>
<body>
<form id="form1" ng-controller="EmpCtrl" ng-submit="save()">
<div style="font-family: Verdana; font-size: 12px; margin-left: 450px;">
<div>
<input type="button" id="btnFetch" value="Fetch" ng-click="getEmployee()" />
</div>

</div>
<hr />

<table border="1" style="text-align: center; margin-left: 410px;">
<tr>

<td> Name
</td>
<td> Age
</td>
<td>City
</td>
</tr>
<tr>
<td>{{Name}}
</td>
<td>{{Age}}
</td>
<td>{{City}}
</td>
</tr>
</table>
</form>
</body>
</html>

Answer

Change controller to :

function EmpCtrl($scope, $http) {
        var post_data = {};
        var responsePromise = $http.post("EmpWebService.asmx/GetEmployee", post_data);
        responsePromise.success(function(msg, status1, headers, config) {
            $(msg).find('Table').each(function (i, row) {
                $scope.Name = $(row).find('empName').text();
                $scope.Age = $(row).find('empAge').text();
                $scope.City = $(row).find('empCity').text();

              });
        });
};