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.
php
end and handle the same in controller.. – Rayon Dabre Jan 7 at 7:16{"status":"ok"}
or{"status":"error"}
. In angular, you can then get this data by catching the promise, which is returned by the $http service (like in your code). The response then contains an object data, which is exactly the response from the server (response.data.status
is eitherok
orerror
). You could also send another HTTP status code (200 vs. e.g. 400 or 500). Then you can catch the success case in the first argument function of then, and the error in the 2nd. – ssc-hrep3 Jan 7 at 7:21if ($stmt->rowCount()) { $status = json_encode('{"status" : 1}'); } else { $status = json_encode('{"status" : 0}');}
be a waste of time vs. echoing it out into a page and then using another ajax call to get the json? Is there a better way after I encode the json that I could just pass the data back to my JS without making another call? - I apologize in advance for my ignorance, very new to the JS world, especially Angular. – Bryner Jan 7 at 8:24{"status":1,"data":[{"model":"Audi"},{....}]}
or any other data structure you have in PHP. (use json_encode for that) – ssc-hrep3 Jan 7 at 8:52