15

I am trying to insert data from front end to mysql db using angularjs. But it is not geting inserted to the db even though there are no error messages. Following is the code that I use.

index.html

<html ng-app="demoApp">
   <head>
        <title> AngularJS Sample</title>
        <script src="js/angular.min.js"></script>
        <script src="js/angular-route.min.js"></script>
        <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <div class="container" ng-view>
        </div>
    </body>
</html>

script.js

    demoApp.config( function ($routeProvider,$locationProvider) {
    $routeProvider
        .when('/',
        {
            controller: 'SimpleController',
            templateUrl: 'Partials/view1.html'
        })
        .when('/view2',
        {
            controller: 'SimpleController',
            templateUrl: 'Partials/view2.html'
        })
        .otherwise({redirectTo: '/'});
    });
    demoApp.controller('SimpleController',function ($scope,$http){
    $http.post('server/view.php').success(function(data){
        $scope.friends = data;
    });;
    $scope.addNewFriend = function(add){
        var data = {
            fname:$scope.newFriend.fname,
            lname:$scope.newFriend.lname
        }
        $http.post("server/insert.php",data).success(function(data, status, headers, config){
            console.log("inserted Successfully");
        });
        $scope.friends.push(data);
        $scope.newFriend = {
            fname:"",
            lname:""
        };
    };   
});

View1.html

<div class="container" style="margin:0px 100px 0px 500px;">
    Name:<input type="text" ng-model="filter.name">
    <br/>
    <ul>
        <li ng-repeat="friend in friends | filter:filter.name | orderBy:'fname'">{{friend.fname}} {{friend.lname}}</li>
    </ul>
    <br/>
    <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 data-ng-click="addNewFriend()" name="add">Add Friend</button>
        </form>
    </fieldset>
    <a href="#/view2" style="margin:auto;">Next</a>
</div>

and following is my php file

insert.php

<?php
    if(isset($_POST['add']))
    {
        $firsname=$_POST['firstname'];
        $laname = $_POST['lastname'];
        mysql_connect("localhost", "root", "") or die(mysql_error()); 
        mysql_select_db("angularjs") or die(mysql_error()); 
        mysql_query("INSERT INTO friends (fname,lname) VALUES ('$firsname', '$laname')"); 
        Print "Your information has been successfully added to the database."; 
    }
?> 

I know I am doing something stupid here. I have just started to learn angularjs today. when i try the php code with plain html to insert into db it works perfectly.I am not getting what I am doing wrong here. Hope someone will help me out here

Midhun Mathew
  • 2,147
  • 8
  • 28
  • 45
  • If the php is working without the angular, then we can discount it as the cause, but you should be using mysqli_* or PDO rather than the mysql_* functions. Using the Chrome developer tool, or similar, can you see the XHR doing the POST to your script? Does it have a value for "add"? I can't see where you are setting the post "add" value, but I am unfamiliar with angular. More information on why not to use mysql_* can be found [here](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – boodle Nov 15 '13 at 15:23
  • 1
    do you get a callback or at least some response code for request code ? – Vinod Louis Nov 15 '13 at 15:26
  • Definitely looks like you are not sending a _POST["add"] value, and so not entering the if. – boodle Nov 15 '13 at 15:27
  • But the same code is working perfectly in regular php... @boodle – Midhun Mathew Nov 15 '13 at 15:33
  • i am not geting the response...if i am right I should get "Your information has been successfully added to the database." as response . But not geting it when done with angularjs. But i gets the response in regular php @VinodLouis – Midhun Mathew Nov 15 '13 at 15:35
  • i'm asking about console are you sure the call is made to server ? – Vinod Louis Nov 15 '13 at 15:36
  • I can see insert.php in the network and it is not showing any error...@VinodLouis – Midhun Mathew Nov 15 '13 at 15:37

1 Answers1

17

Your script for inserting the data is wrong. Replace it with the following

$http.post("server/insert.php",{'fstname': $scope.newFriend.fname, 'lstname': $scope.newFriend.lname})
        .success(function(data, status, headers, config){
            console.log("inserted Successfully");
        });

and also change the php as follows.

$data = json_decode(file_get_contents("php://input"));
$fstname = mysql_real_escape_string($data->fstname);
$lstname = mysql_real_escape_string($data->lstname);
mysql_connect("localhost", "root", "") or die(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."; 

This worked for me when I tried with your code.

MidhuN
  • 423
  • 4
  • 17