app.controller('userController', ["$scope","$http", function($scope,$http){
$scope.newFriend = {
fName:"",
lName:""
};
$scope.friends = new Array();
$scope.addNewFriend = function(){
$http.post("php/insert.php",$scope.newFriend)
.success(function(data, status, headers, config){
$scope.friends.push($scope.data);
console.log("inserted Successfully");
});
};
}]);
PHP database angularjs
Question
I am trying to send some data to a MySQL database. Nothing happens when I press the button to add new users. I do not see any errors so I do not know where it goes wrong. Could someone help me with this?
index.html
<html ng-app="myApp">
<head>
<title> AngularJS Sample</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/userController.js"></script>
</head>
<body>
<div class="container" style="margin:0px 100px 0px 500px;">
<fieldset style="width:200px;">
<legend>Add Friend</legend>
<form name="addcustomer" method="POST">
First Name:<input type="text" ng-model="newFriend.fname" name="firstname"/>
<br/>
Last Name :<input type="text" ng-model="newFriend.lname" name="lastname"/>
<br/>
<button ng-click="addNewFriend()" name="add">Add Friend</button>
</form>
</fieldset>
</div>
</body>
</html>
insert.php
if(isset($_POST['add']))
{
$data = json_decode(file_get_contents("php://input"));
$fstname = mysql_real_escape_string($data->fname);
$lstname = mysql_real_escape_string($data->lname);
$con = mysql_connect("localhost","root","") or die('Could not connect: ' .
mysql_error());
mysql_select_db('angularjs') or die (mysql_error());
mysql_query("INSERT INTO friends (fname,lname) VALUES ('$fstname', '$lstname')");
Print "Your information has been successfully added to the database.";
}
userController.js
app.controller('userController', ["$scope","$http", function($scope,$http){
$scope.addNewFriend = function(add){
var data = {
fname:$scope.newFriend.fname,
lname:$scope.newFriend.lname
};
$http.post("php/insert.php",data)
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
$scope.friends.push($scope.data);
$scope.newFriend = {
fname:"",
lname:""
};
};
}]);
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow