1

I am trying to make a simple function in order to insert data from a form in angularjs to the Mysql database using PHP. The display data works fine but the insert doesn't work, is any body know how to fix it?

that's the angularjs code:

var app = angular.module("myApp", []);

app.controller('usercontroller' , function($scope, $http){


$scope.insertData = function(){
    $http.post(
        "insert.php",
        {
            'name' : $scope.name,
            'age' : $scope.age,
            'email' : $scope.email
        }).success(function(data){
            alert(data);
             $scope.name = null;
            $scope.age= null;
            $scope.email= null;

            $scope.displayData()
        });

}

and that's the PHP code insert.php

<?php

$connection = mysqli_connect("localhost", "root" , "" , "users");

$data = json_decode(file_get_contents("php://input"));

if(count($data)>0)
{
 $name = mysqli_real_escape_string($connection , $data->name);
 $age = mysqli_real_escape_string($connection , $data->age);
 $email = mysqli_real_escape_string($connection , $data->email);
 $query = "INSERT INTO 'myusers' ('name', 'age', 'email') VALUES ('$name', '$age', '$email')";



 if (mysqli_query($connection , $query)) {
  echo "New record created successfully";
  } else {
  echo "Error: xxxxx";
   }
   }
   ?>

and the error is:

    angular.js:15570 TypeError: $http.post(...).success is not a function
at Scope.$scope.insertData (app.js:13)
at fn (eval at compile (angular.js:16421), <anonymous>:4:150)
at callback (angular.js:28954)
at Scope.$eval (angular.js:19396)
at Scope.$apply (angular.js:19495)
at HTMLButtonElement.<anonymous> (angular.js:28958)
at HTMLButtonElement.dispatch (jquery-3.4.1.slim.min.js:2)
at HTMLButtonElement.v.handle (jquery-3.4.1.slim.min.js:2)
13
  • 1
    Use .then() instead of .success() - It is deprecated Commented Jan 25, 2020 at 15:19
  • i already tried also with .(then), the error is gone but i got another issue. when i press submit it shows me (the following is displayed on localhost) [object object] and nothing inserted to database Commented Jan 25, 2020 at 15:27
  • may be there is something in PHP code because there is a warning Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\crud\insert.php on line 6 Error: Commented Jan 25, 2020 at 15:30
  • The $http.post() returns a promise and the response object is different from how it worked with .success() - It should be something like $http.post(...).then(function( response) { var data = response.data; ...... }; Commented Jan 25, 2020 at 15:31
  • 1
    @FunkFortyNiner thx for you anyway :) Commented Jan 25, 2020 at 16:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.