I'm receiving the following error when I load my page (on alert box)
DataTables warning: table id= entry-grid - Ajax error. For more information about this eror, please see http://datatables.net/tn/7
What is wrong. I've run the web application in debug and my C# works fine, records are taken from the DataBase, but something goes wrong with the Angular js
When i debug in the browser the entire code after var app = angular.module('MyApp', ['datatables']); is just being ignored. This is the error in the console POST http://localhost:10575/teachers/getdata 500 (Internal Server Error)
Here is my MVC Controllers
public ActionResult Index()
{
return View();
}
public ActionResult getData()
{
//Datatable parameter
var draw = Request.Form.GetValues("draw").FirstOrDefault();
//paging parameter
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//sorting parameter
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//filter parameter
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
List<tblTeacher> allCustomer = db.tblTeachers.ToList();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//Database query
using (RSEntities dc = new RSEntities())
{
var v = (from a in dc.tblTeachers select a);
//search
if (!string.IsNullOrEmpty(searchValue))
{
v = v.Where(a =>
a.FirstName.Contains(searchValue) ||
a.SecondName.Contains(searchValue) ||
a.Title.Contains(searchValue) ||
a.TDepartment.Contains(searchValue)
);
}
//sort
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
//for make sort simpler we will add Syste.Linq.Dynamic reference
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
recordsTotal = v.Count();
allCustomer = v.Skip(skip).Take(pageSize).ToList();
}
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = allCustomer });
}
Now the Angular Js
/// <reference path="angular.js" />
/// <reference path="angular.min.js" />
/// <reference path="angular-route.min.js" />
/// <reference path="angular-route.js" />
var app = angular.module('MyApp', ['datatables']);
app.controller('homeCtrl', ['$scope', '$http', 'DTOptionsBuilder', 'DTColumnBuilder',
function ($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
$scope.dtColumns = [
//here We will add .withOption('name','column_name') for send column name to the server
DTColumnBuilder.newColumn("FirstName", "Име").withOption('name', 'FirstName'),
DTColumnBuilder.newColumn("SecondName", "Фамилия").withOption('name', 'SecondName'),
DTColumnBuilder.newColumn("Title", "Титла").withOption('name', 'Title'),
DTColumnBuilder.newColumn("TDepartment", "Факултет").withOption('name', 'TDepartment'),
]
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
dataSrc: "data",
url: "/teachers/getdata",
type: "POST"
})
.withOption('зареждане', true) //for show progress bar
.withOption('serverSide', true) // for server side processing
.withPaginationType('full_numbers') // for get full pagination options // first / last / prev / next and page numbers
.withDisplayLength(10) // Page size
.withOption('aaSorting', [0, 'asc']) // for default sorting column // here 0 means first column
}])
Finally the View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/angular.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.5.5/angular-datatables.js"></script>
<script src="~/Scripts/myApp.js"></script>
<div ng-app="MyApp" class="container">
<div ng-controller="homeCtrl">
<table id="entry-grid" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-hover"></table>
</div>
</div>
Related
Hello I am beginner in mean Stack. and I have data in localstorage and I want to fetch the data from the local storage and show in html file but I don't know How to get it. on the view file.
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
when I type localStorage; into console it show
ngStorage-userData
:
"{
"_id":"5846692617e0575c0e0c2211",
"password":123456,
"email":"montyy1981#gmail.com",
"name":"digvijay12","__v":0
}"
How to get it value into the view file.I used like
<div>{{userData.email}}</div>
But it is not showing data.please help me how to fetch localstorage data and show into view file.
You can use core concept without ngStorage....
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
localStorage.setItem("userData", $scope.Data);
$scope.storageData = localStorage.getItem("userData");
<p>{{storageData.email}}</p>
How to get the localStoragedata anywhere this is very simple we have to pass localStorage data into the controller global variable suppose
we have the data into localstorage
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
we have to define pass $localStorage.userData into the other variable after controller start.
app.controller("usercontroller",function($scope,$http, $localStorage,$location){
$scope.registeruser = $localStorage.userData;
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
});
For better understanding click this DEMO
In the controller you need to inject "ngStorage" angular.module('MyApp', ["ngStorage"]).
And add the dependency script link <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
HTML
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MyController">
<input type="button" value = "Save" ng-click = "Save()" />
<input type="button" value = "Get" ng-click = "Get()" />
</div>
</body>
</html>
Script.js
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.email = "xyz#gmail.com";
}
$scope.Get = function () {
$window.alert($localStorage.email);
}
});
Hope it will be usefull for you.
I'm a newbie in Javascript and Angular JS programming and I'm trying to make a currency converter using Yahoo Finance API, but also I want to input directly the initial value in the script without clicking the button or pressing enter, so i figured that using Angular JS would be great. But it doesn't work properly and I think the problem might be in function calculate($scope). Please, can you help me?
<html ng-app>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
function currencyConverter(currency_from,currency_to,currency_input){
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var http_response = httpGet(yql_query_url);
var http_response_json = JSON.parse(http_response);
return http_response_json.query.results.rate.Rate;
}
//The problem starts here?
function calculate($scope)
{
$scope.total= function(){
var currency_from = "USD";
var currency_to = "INR";
var rate = currencyConverter(currency_from,currency_to,$scope.currency_input);
return rate;
};
}
</script>
<script src="js/angular.js"></script>
</head>
<body>
<div ng-controller="calculate">
<div style="float:left;">
<form>
<input type="text" ng-model="currency_input" value="0"/> =
</form>
</div>
<div style="float:left">
{{total()}}
</div>
</div>
<div style="clear: both;"></div>
</body>
</html>
There are a few erros in your code using AngularJS. You forgot to start your application module and add a controller.
I made a few corrections and I tested, it is working:
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<div style="float:left;">
<form>
<input type="text" ng-model="currency_input" ng-change="total()" value="0"/> =
</form>
</div>
<div style="float:left">
{{ rate }}
</div>
</div>
<div style="clear: both;"></div>
<script>
angular.module('app', [])
.controller('MyController', function($scope, $http) {
function currencyConverter(currency_from,currency_to) {
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$http.get(yql_query_url).then(function(response) {
$scope.rate = $scope.currency_input*response.data.query.results.rate.Rate;
});
}
$scope.total = function() {
var currency_from = "USD";
var currency_to = "INR";
currencyConverter(currency_from, currency_to);
};
});
</script>
</body>
</html>
I don't recommend you to use jquery to make http calls. Use $http instead!
One problem, which should be the first to be corrected and go from there, is that you are referencing an angular concept $scope in your scripts before you actually declare the angular library.
To correct this, move your angular library script tag up above your other script tag (but below the jquery script tag.
You should take a look at services (https://docs.angularjs.org/guide/services).
With that you can just create a service and put all of your 'Yahoo' related functions in one place. Then just inject it into your directive/controller.
ex:
.service('yahooRelatedLogicSrvc', function () {
return {
httpGet: function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
}
})
.controller('sampleCtrl', function ($scope, yahooRelatedLogicSrvc) {
var url = 'http://yahoo.com';
$scope.httpGet = yahooRelatedLogicStvc.httpGet(url);
}
And you can just put returns of your service functions as $scope properties etc.
I really can see why you should use in line javascript in that scenario.
Angular makes something like this much easier than what you're attempting. There's an $http service for performing a GET, for one, so you can leave out jquery and create something much simpler like ConverterService in my example.
Since your input is bound to a scope variable, you don't need to set value="0", simply set $scope.currency_input to your default value in your controller. I created a convert function on the scope, which will update the output whenever its called. It's called once at the bottom of the controller, but could be bound to a button in your html by simply doing something like this: <button ng-click="convert()">Convert value</button>
var app = angular.module('calc', []);
app.controller('MainCtrl', function($scope, ConverterService) {
// default your currency input
$scope.currency_input = 10;
var currency_from = "USD";
var currency_to = "INR";
$scope.convert = function() {
ConverterService.getConversions(currency_from, currency_to)
.then(function(response) {
// put your logic to convert the value here
var convertedVal = null; // = $scope.currency_input * response.something etc...
$scope.result = convertedVal;
});
};
$scope.convert();// run once when the controller loads to get defaulted input conversion
});
app.factory('ConverterService', function($http) {
return {
getConversions: function(from, to, val) {
var endpoint = ''; // build your endpoint here
return $http.get(endpoint);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="calc">
<div ng-controller="MainCtrl">
<input type="text" ng-model="currency_input">= {{result}}
</div>
</html>
I would like to use this plunk locally on my machine. However, when I either run it with the local Python server or http-server, I keep getting the following Error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
My html file looks like this:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<script scr="main.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.1/papaparse.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/1.1.5/angular-file-upload.min.js"></script>
<link rel="stylesheet" href="main.css">
</head>
<body ng-controller="MyCtrl">
<h1>CSV</h1>
<div>
<input type="checkbox" ng-model="append">
Append to existing on drag & drop
</div>
<div class="drop-container" nv-file-drop nv-file-over uploader="uploader">
<textarea ng-model="csv" placeholder="Enter your CSV here, or drag/drop a CSV file"></textarea>
</div>
<h1>D3 Flare JSON</h1>
<div>
<input type="checkbox" ng-model="compact"> Compact
</div>
<div>
<input type="text" ng-model="tags.parent" placeholder="parent tag">
<input type="text" ng-model="tags.children" placeholder="children tag">
<input type="text" ng-model="tags.leaf" placeholder="leaf tag">
<input type="text" ng-model="tags.size" placeholder="size tag">
</div>
<textarea readonly ng-model="json"></textarea>
</body>
</html>
And the main.js file looks like this:
CSV to D3 Flare JSON converter in AngularJSPreview Edit Code
index.html
main.js
main.css
main.js
angular.module('myApp', ['angularFileUpload'])
.factory('FlareJson', ['$q', function($q) {
function updateTree(curr, arr, tags) {
if ((arr.length || 0) < 2) {
return;
}
if (!curr.hasOwnProperty(tags.children)) {
curr[tags.children] = [];
}
var elem;
if (arr.length == 2) {
elem = {};
elem[tags.leaf] = arr[0];
elem[tags.size] = arr[1];
curr[tags.children].push(elem);
} else {
curr[tags.children].some(function(e) {
if (e[tags.parent] == arr[0] || e[tags.leaf] == arr[0]) {
elem = e;
return true;
}
});
if (!elem) {
elem = {};
elem[tags.parent] = arr[0];
curr[tags.children].push(elem);
}
updateTree(elem, arr.slice(1), tags);
}
}
function buildJson(csv, compact, tags) {
var deferred = $q.defer();
var result = {};
result[tags.parent] = 'flare';
Papa.parse(csv, {
header: false,
dynamicTyping: true,
complete: function(csvArray) {
csvArray.data.forEach(function(line) {
if (line.length) {
updateTree(result, line, tags);
}
});
if (compact) {
deferred.resolve(JSON.stringify(result));
} else {
deferred.resolve(JSON.stringify(result, null, 2));
}
}
});
return deferred.promise;
}
return buildJson;
}])
.controller('MyCtrl', ['$scope', 'FileUploader', 'FlareJson',
function($scope, FileUploader, FlareJson) {
$scope.csv = "";
$scope.compact = false;
$scope.json = "";
$scope.tags = {
parent: 'skill',
children: 'children',
leaf: 'name',
size: 'level'
};
$scope.uploader = new FileUploader();
$scope.uploader.onAfterAddingFile = function(fileItem) {
var reader = new FileReader();
reader.onloadend = function(event) {
$scope.$apply(function() {
if ($scope.append) {
$scope.csv += event.target.result;
} else {
$scope.csv = event.target.result;
}
});
};
reader.readAsText(fileItem._file);
};
function update() {
FlareJson($scope.csv, $scope.compact, $scope.tags).then(function(json) {
$scope.json = json;
});
}
$scope.$watchGroup(['csv', 'compact'], update);
$scope.$watchCollection('tags', update);
}]);
I don't understand what I'm doing wrong. I already searched for similar error messages, but nothing that I found could help me to solve my problem.
You load your script file before angularjs file that's why you are getting this error.
So, Add your "main.js" file after "angular.js" file.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script scr="main.js"></script>
I believe it's because you're loading your main.js before you load Angular. Try putting your script at the end of the script definitions:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.1/papaparse.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/1.1.5/angular-file-upload.min.js"></script>
<script scr="main.js"></script>
Oh, solved! Turns out, that the following couple of first lines in main.js were causing the trouble:
CSV to D3 Flare JSON converter in AngularJSPreview Edit Code
index.html
main.js
main.css
main.js
I removed them from main.js, now it works - yuhuu! :)
This question already has answers here:
connect AngularJS to mysql using my PHP service?
(2 answers)
Closed 8 years ago.
I am looking for a solution for almost 3 days but i can't figure it out. This is my problem:
I have file called: index.php
<html>
<head>
<title>AngularJS-FlowChart</title>
<!--
LiveReload support.
http://livereload.com/
-->
<script src="http://localhost:35729/livereload.js?snipver=1"></script>
</head>
<body
ng-app="app"
ng-controller="AppCtrl"
mouse-capture
ng-keydown="keyDown($event)"
ng-keyup="keyUp($event)"
>
<div style="width: 100%; overflow: hidden;">
<!--<div style="width: 600px; float: left;">
<textarea
style="width: 100%; height: 100%;"
chart-json-edit
view-model="chartViewModel"
>
</textarea>
</div>-->
<div style="margin-left: 0px;">
<button
ng-click="addNewNode()"
title="Add a new node to the chart"
>
Add Node
</button>
<button
ng-click="addNewInputConnector()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0"
title="Add a new input connector to the selected node"
>
Add Input Connector
</button>
<button
ng-click="addNewOutputConnector()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0"
title="Add a new output connector to the selected node"
>
Add Output Connector
</button>
<button
ng-click="deleteSelected()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0 && chartViewModel.getSelectedConnections().length == 0"
title="Delete selected nodes and connections"
>
Delete Selected
</button>
<!--
This custom element defines the flowchart.
-->
<flow-chart
style="margin: 5px; width: 40%; height: 70%; float: right"
chart="chartViewModel"
>
</flow-chart>
<flow-chart
style="margin: 5px; width: 40%; height: 70%; float: left"
chart="chartViewModel"
>
</flow-chart>
</div>
</div>
<link rel="stylesheet" type="text/css" href="app.css">
<!-- Library code. -->
<script src="lib/jquery-2.0.2.js" type="text/javascript"></script>
<script src="lib/angular.js" type="text/javascript"></script>
<!-- Flowchart code. -->
<script src="debug.js" type="text/javascript"></script>
<script src="flowchart/svg_class.js" type="text/javascript"></script>
<script src="flowchart/mouse_capture_service.js" type="text/javascript"></script>
<script src="flowchart/dragging_service.js" type="text/javascript"></script>
<script src="flowchart/flowchart_viewmodel.js" type="text/javascript"></script>
<script src="flowchart/flowchart_directive.js" type="text/javascript"></script>
<!-- App code. -->
<script src="app.js" type="text/javascript"></script>
</body>
</html>
And I have another file called: app.js
//
// Define the 'app' module.
//
angular.module('app', ['flowChart', ])
//
// Simple service to create a prompt.
//
.factory('prompt', function () {
/* Uncomment the following to test that the prompt service is working as expected.
return function () {
return "Test!";
}
*/
// Return the browsers prompt function.
return prompt;
})
//
// Application controller.
//
.controller('AppCtrl', ['$scope', 'prompt', function AppCtrl ($scope, prompt) {
//
// Code for the delete key.
//
var deleteKeyCode = 46;
//
// Code for control key.
//
var ctrlKeyCode = 65;
//
// Set to true when the ctrl key is down.
//
var ctrlDown = false;
//
// Code for A key.
//
var aKeyCode = 17;
//
// Code for esc key.
//
var escKeyCode = 27;
//
// Selects the next node id.
//
var nextNodeID = 10;
//
// Setup the data-model for the chart.
//
var chartDataModel = {};
//
// Event handler for key-down on the flowchart.
//
$scope.keyDown = function (evt) {
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = true;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Event handler for key-up on the flowchart.
//
$scope.keyUp = function (evt) {
if (evt.keyCode === deleteKeyCode) {
//
// Delete key.
//
$scope.chartViewModel.deleteSelected();
}
if (evt.keyCode == aKeyCode && ctrlDown) {
//
// Ctrl + A
//
$scope.chartViewModel.selectAll();
}
if (evt.keyCode == escKeyCode) {
// Escape.
$scope.chartViewModel.deselectAll();
}
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = false;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Add a new node to the chart.
//
$scope.addNewNode = function () {
var nodeName = prompt("Enter new node!", "New node");
if (!nodeName) {
return;
}
//
// Template for a new node.
//
var newNodeDataModel = {
name: nodeName,
id: nextNodeID++,
x: 50,
y: 50
};
$scope.chartViewModel.addNode(newNodeDataModel);
};
//
// Add an input connector to selected nodes.
//
$scope.addNewInputConnector = function () {
var connectorName = prompt("Enter a connector name:");
if (confirm(connectorName)) {
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addInputConnector({
name: connectorName
});
}
} else return;
};
//
// Add an output connector to selected nodes.
//
$scope.addNewOutputConnector = function () {
var connectorName = prompt("Enter a connector name:");
if (confirm(connectorName)) {
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addOutputConnector({
name: connectorName,
});
}
} else return;
};
//
// Delete selected nodes and connections.
//
$scope.deleteSelected = function () {
$scope.chartViewModel.deleteSelected();
};
//
// Create the view-model for the chart and attach to the scope.
//
$scope.chartViewModel = new flowchart.ChartViewModel(chartDataModel);
}])
;
The thing I want to achieve is to read data from MySQL and use that same data inside app.js file. I'd really need any help please.
I was reading all articles about this thema on first 5 google pages but without any success. I tried all sorts of "tutorials" but i could find the solution.
Use jQuerys AJAX function to send data to a PHP Service:
$.ajax({
type: 'POST',
url: path + '/php/yourService.php',
data: 'var=' + var,
success: function (response) {
// Do smth with the response
}
});
In your PHP Service read out data of the database:
// connect to your database first
$username = $_POST["var"];
$sql="SELECT * FROM users WHERE anything = '$var'";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result)){
return $row["variable"];
}
Should do the trick. Don´t matter if angular or not. The returned data is accessibly through the response variable in ajax onSuccess function. Hope this helps
i am developing an application using angular js in which i have to populate the customer list using data in database for that i write a web method to get the data like
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getname()
{
SqlHelper sql = new SqlHelper();
DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,cust_L_name from customer");
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count];
List<CustName> custName = new List<CustName>();
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
CustName c = new CustName();
c.cust_F_name = dt.Rows[i]["cust_F_name"].ToString();
custName.Add(c);
}
dict.Add("JsonCustomer", custName);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
//return "Rhsuhikesh";
}
}
public class CustName
{
public string cust_F_name { get; set; }
}
catch that Json data as
var DemoApp = angular.module('DemoApp', []);
DemoApp.factory('SimpleFactory', function ($http) {
return {
getCustomer: function () {
return $http.post('Home.aspx/getname', { name: "" });
}
};
});
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customer) {
$scope.Customer = customer.data;
}, function (error) {
// error handling
});
});
and view it as
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
<title></title>
</head>
<body data-ng-controller="SimpleController">
<form id="form1" runat="server">
<div>
Name<input type="text" data-ng-model="Name" />{{ Name }}
<ul>
<li data-ng-repeat="customerName in Customer | filter:Name">{{ customerName }} </li>
</ul>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>
and I am getting o/p as
but i want it as
data in json i have to access in name value pair but i am not understand how to do it please help me to out if it.
thanks in advance.
Since you get your results as JSON string you need to convert it to JavaScript object using angular.fromJson
For example:
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customerData) {
var customersRawObject = angular.fromJson(customerData);
}, function (error) {
// error handling
});})
Then you can do somthing like this:
$scope.customerA=customersRawObject.JsonCustomer[0];