Search code examples
javascriptphpmysqlangularjsxmlhttprequest

Check if php insert was successful when using AngularJS $http


I'm a beginner when it comes to AngularJS but I have just figured out how to pass POST data using the $http service to a PHP file to insert to my database.

This is my add.php file. It displays my form and has the insert code block at the bottom:

<h2>Add Car</h2>
<div ng-controller="formCtrl">
    <form method="POST">
        <label>Make:</label>
        <select ng-model="car.make">
            <option>Make 1</option>
            <option>Make 2</option>
            <option>Make 3</option>
        </select>
        <label>Model:</label>
        <input type="text" ng-model="car.model">
        <input type="submit" ng-click="addCar(car)">
    </form>

    <pre>
        {{message}}
    </pre>
</div>


<?php
$data = json_decode(file_get_contents("php://input"));
$make = $data->make;
$model = $data->model;

$con = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');

$stmt = $con->prepare("INSERT INTO cars (model, make) VALUES(?, ?)");
$stmt->bindParam(1, $model);
$stmt->bindParam(2, $make);
$stmt->execute();
?>

This is my controller:

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

    $scope.addCar = function (car) {

        $http({
            method: 'POST',
            url: 'tools/add.php',
            data: car,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        })
        .then(function (response) {
           $scope.message = "great!"; 
        });
    }
});

Now is there anyway to check to see if the insert was successful? I know you can use the rowCount() function to check on the PHP side and then set your message to either be an error or a successful insert, but I'd like to know if there's anyway for my JS to know whether a row was actually inserted or not.


Solution

  • Check if insert was successful:

    if ($stmt->execute()) { 
       // It worked
    } else {
       // It didn't
    }
    

    Why not add something like die('Not successful'); in PHP. Then get angular to check if an error message was provided:

    $http({
        method: 'POST',
        url: 'tools/add.php',
        data: car,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    })
    .then(function (response) { 
        if(!response) {
             // Success
             $scope.message = "great!"; 
        } else {
             // Fail
             alert(response);
        }
    });
    

    Dont forget you can also use .success() and .error() in Angular too.

    One final thing! I've found that keeping my JSON request files separate to partials has made everything easier and manageable. The above solution won't work as there is HTML data sent before it gets to the JSON stuff!