Atul Gurnule Atul Gurnule - 4 months ago 9
PHP Question

Error: StringServices.insertString(...) is undefined

I am New to angularjs, I am doing basic demo, in that I am inserting data into database using php and angularjs services and passing it to controller, the data is inserting into database but m getting error in console log. can anyone help me solve this error?

here is my app.js



var app = angular.module('myApp', [])
//controller
app.controller("myController",['$scope','StringServices', function($scope,StringServices){
$scope.User= {};
$scope.insert = function(User){
StringServices.insertString($scope.User, function(response){
if(response.FLAG === "_SUCCESS"){
console.log('Success');
}
else{
console.log('Error');
}
}).error(function(error){
console.error(error);
});
}
}])
//services

app.factory('StringServices', function($http){
return {
insertString: function(User){
var data = {name: User.name};

$http.post('http://localhost/anjali_services/server/insert.php',data)
.success(function(response){
return response;
});
}
};
});


index.html



<table>
<tr>
<td>Your Name</td>
<td><input type= "text" ng-model="User.name"></td>
</tr>
<tr>
<td></td>
<td><input type="button" ng-click="insert(User)" value="Insert"></td>
</tr>
</table>


insert.php



<?php
$db = new PDO("mysql:host=localhost;dbname=anjali;port=3306","root","");
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$resp = array();
$q = "INSERT INTO udata (name) VALUES (:name)";
$query = $db->prepare($q);
$execute = $query->execute(array(
":name" => $name
));
if($execute == true){
$resp['FLAG'] = "_SUCCESS";
print json_encode($resp);
}else{
echo "ERROR";
}

?>


i am getting this error



See this screenshot

Answer

Your insertString function in StringServices takes only one argument that is User, however in your controller you are passing two arguments, i.e User and a function. thus no function insertString with two parameters.

You can have something like this:

var app = angular.module('myApp', [])
//controller
app.controller("myController",['$scope','StringServices', function($scope,StringServices){
    $scope.User= {};
    $scope.insert = function(User){
        StringServices.insertString($scope.User, function(response){
            if(response.FLAG === "_SUCCESS"){
                console.log('Success');
            }
            else{
                console.log('Error');
            }
        });
    }
}])
//services

app.factory('StringServices', function($http){
    return {
        insertString: function(User, callbackFn){
            var data = {name: User.name};

            $http.post('http://localhost/anjali_services/server/insert.php',data)
            .success(callbackFn);
        }
    };
});