i'm doing an angularjs CRUD application using php framework Slim as a backend, this application almost done but my PUT method does not work and i realy can't understand why.
Here is my Slim code:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
// create new Slim instance
$app = new \Slim\Slim();
$app->get('/users', 'getUsers');
$app->post('/addUser', 'addUser');
$app->put('/edit/:id', 'updateUser');
$app->delete('/users/:id', 'deleteUser');
$app->run();
function getUsers() {
$sql = "select * FROM name ORDER BY id";
try {
$db = getConnection();
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function addUser() {
$request = \Slim\Slim::getInstance()->request();
$user = json_decode($request->getBody());
$sql = "INSERT INTO name (name) VALUES (:name)";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("name", $user->name);
$stmt->execute();
$user->id = $db->lastInsertId();
$db = null;
echo json_encode($user);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function updateUser($id) {
$request = Slim::getInstance()->request();
$body = $request->getBody();
$user = json_decode($body);
$sql = "UPDATE name SET name=:name WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("name", $user->name);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
echo json_encode($user);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function deleteUser($id) {
$sql = "DELETE FROM name WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getConnection() {
$dbhost="127.0.0.1";
$dbuser="root";
$dbpass="000000";
$dbname="users";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
?>
Here is my angularjs code:
'use strict';
var app = angular.module('mainApp', ['ngRoute', 'ngResource']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'views/users.html'
})
.when('/addUser', {
controller: 'MainCtrl',
templateUrl: 'views/add.html'
})
.when('/edit/:id', {
controller: 'MainCtrl',
templateUrl: 'views/edit.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('MainCtrl', ['$scope', '$http', '$location', '$routeParams' , function($scope, $http, $location, $routeParams) {
$scope.master = {};
$scope.activePath = null;
$http.get('api/users').success(function(data) {
$scope.users = data;
});
$scope.deleteUser = function (user) {
console.log('service delete ' + user.id);
$http.delete('api/users/' + user.id).success(function(){
$location.path('/adminlist')
});
}
$scope.addUser = function(user, AddNewForm) {
console.log(user);
$http.post('api/addUser', user).success(function(){
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.reset();
};
$scope.updateUser = function(user, AddNewForm) {
console.log(user);
$http.put('api/edit/' + $routeParams.id, {id:$routeParams.id, name:user.name}).success(function(){
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.reset();
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
}]);
and finally my HTML code, this is a template where i display all users:
<!-- Show existing users. -->
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>
{{user.name}}
</td>
<td><a ng-click="deleteUser( user )">delete</a></td>
<td>( edit )</td>
</tr>
</tbody>
</table>
<!-- Add a new friend to the list. -->
And this is my page when i wanna update user:
<h2>Edit user</h2>
<form novalidate name="AddNewForm" id="add-new-form" method="post" action="">
<label for="user">Name:</label>
<input type="text" ng-model="user.name" required />
<br/>
<button class="btn btn-primary" ng-disabled="AddNewForm.$invalid || isUnchanged(user)" id="add-new-btn" ng-click="updateUser(user)">Edit!</button>
</form>
!
It is very strange because when i press edit button i enter some another name into this form, and when i click button i can see in Network what all works, but seems like i've got a mistake somewhere, you can see it on a picture
Maybe somebody can link me some examples how to do this?
Thank you for your attention:)
Rather than writing methods in every controller to get API data, I try to do all API interactions through a factory. You just call the method and pass parameters to it.
// Rest API data factory
function ApiData($http)
{
var query = '';
var domain = 'mydomain.com/';
return {
get: function (endpoint, params) {
return $http({
method: 'GET'
, url: domain + endpoint
, params: params
})
.then(function (response) {
return response.data;
});
},
post: function (endpoint, params) {
return $http({
method: 'POST'
, url: domain + endpoint
, params: params
})
.then(function (response) {
return response.data;
});
},
put: function (endpoint, params) {
return $http({
method: 'PUT'
, url: domain + endpoint
, params: params
})
.then(function (response) {
return response.data;
});
}
}
This makes calling the endpoint really easy and minimizes duplicate code.
// Get data from the API
ApiData.get('items', itemController.params)
.then(function(data) {
itemController.data = data;
}
);
Related
I'm trying to get data from MySQL via vue -> axios -> php. In response to the request, cath(error) fires with the following error:
TypeError: b.split is not a function
at index.js:1:1
at new Promise (<anonymous>)
at t.exports (index.js:1:1)
at t.exports (index.js:1:1)
at h.request (index.js:1:1)
at h.n.forEach.h.<computed> [as get] (index.js:1:1)
at Function.get (index.js:1:1)
at Vue.getDrivers (drivers.php:78:23)
at Vue.mounted (drivers.php:95:18)
at invokeWithErrorHandling (vue.js:1872:59)
in this file (drivers.php)
<script>
var app = new Vue({
el: '#newdriver',
data: {
drivers: [],
},
methods: {
getDrivers() {
axios.get({
url: 'scripts/drivers-action.php',
method: 'get',
})
.then((res) => {
console.log("result");
console.log(res);
this.drivers = res.data.rows;
})
.catch((error) => {
// handle error
console.log(error);
});
},
},
mounted: function() {
this.getDrivers();
},
});
</script>
drivers-action.php:
<?php
include('../dbcon.php');
$sql = "SELECT * FROM drivers";
$rows = getAllDrivers();
function getAllDrivers() {
$data = [];
$statement = $conn->prepare($sql);
if($statement->execute()) {
$data = $statment->fetchAll();
}
return $data;
}
$data = array('rows' => $rows);
echo json_encode($data);
?>
I can't figure out what is the problem and what is causing this error.
EDITED:
dbconn.php, where i define $conn object for database connect
<?php
$conn = new mysqli(
'localhost',
'root',
'',
'beldum'
);
if($conn -> connect_error) {
die('Error: ('.$conn->connect_errno.')'.$conn->connect_error);
}
?>
Hi I'm having a problem with my code, I've checked it multiple times but can't seem to locate it. I'm working with HTML, JS, Slim framework and PHP and getting my data from mysql.
Any help would be appreciated!
JS
$(document).ready(function(){
$("#edit").click(function(){
var coach=new Coach(
$("#CoachFirstName").val(),
$("#CoachLastName").val(),
$("#CoachExperienceYrs").val(),
$("#CoachPastTeam").val());
$.ajax({
type:'PUT',
dataType:"json",
url:"db.php/coachs/1",
data:JSON.stringify(coach),
success: showResponse,
error: showError
});
}); });
function Coach(CoachFirstName, CoachLastName, CoachExperienceYrs, CoachPastTeam){
this.CoachFirstName=CoachFirstName;
this.CoachLastName=CoachLastName;
this.CoachExperienceYrs=CoachExperienceYrs;
this.CoachPastTeam=CoachPastTeam;
} function showResponse(responseData) {
console.log(responseData); }
function showError() {
alert("Error while updating" );
};
PHP - SLIM
$app->put('/coachs/:id', 'updateCoach');
function updateCoach($id){
$request = Slim::getInstance()->request();
$coach = json_decode($request->getBody());
$sql = "UPDATE coach SET CoachFirstName=:CoachFirstName, CoachLastName=:CoachLastName, CoachExperienceYrs=:CoachExperienceYrs, CoachPastTeam=:CoachPastTeam WHERE CoachID=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("CoachFirstName",$coach->CoachFirstName);
$stmt->bindParam("CoachLastName",$coach->CoachLastName);
$stmt->bindParam("CoachExperienceYrs",$coach->CoachExperienceYrs);
$stmt->bindParam("CoachPastTeam",$coach->CoachPastTeam);
$stmt->bindParam("id",$id);
$stmt->execute();
$coach = $stmt->fetchObject();
$db = null;
responseJson(json_encode($coach),200);
}catch(PDOException $e){
responseJson('{"error":{"text":'.$e->getMessage().'}}', 500);
}
}
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
I have to say I can't figure out the root of your problem right-away but I'd suggest you at least return $http promise from your service and handle result using then/catch. At least I find this more easy to read & understand what's going on.
Anyway, modifying your example in this way seems to work just nice. Against mock REST service anyway.
HTML
<body ng-controller="myController as vm">
Your Name:
<input type= "text" ng-model="User.name">
<input type="button" ng-click="insert(User)" value="Insert">
</body>
JavaScript
var app = angular.module('myApp', [])
.controller('myController', function($scope, StringServices) {
$scope.User = {};
$scope.insert = function(User) {
StringServices.insertString(User)
.then(function(response) {
console.log('ok', response);
})
.catch(function(error) {
console.log('failed', error);
});
};
})
.factory('StringServices', function($http){
return {
insertString: function(User){
return $http.post('https://httpbin.org/post', { name: User.name });
}
};
});
Related plunker here https://plnkr.co/edit/MVUSeg
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);
}
};
});
I want to store an image as a blob into my database(MySQL) while using PHP Rest service, but I dont know how to do it. Here is my PHP code (I'm using Slim framework for PHP)
function addProblem() {
global $app;
$postdata = file_get_contents("php://input");
$req = json_decode($postdata); // Getting parameter with names
$paramName = $req->station; // Getting parameter with names
$paramAdres = $req->address; // Getting parameter with names
$paramCity = $req->city;// Getting parameter with names
$parampostal = $req->postalcode;
$parampic = $req->pictureOfDamage;
$paramdescrip= $req->description;
$sql = "INSERT INTO problems (Station,Address,Postalcode,City,PictureOfDamage,Description) VALUES (:station,:address,:postalcode,:city,:pictureOfDamage,:description)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':station', $paramName);
$stmt->bindParam(':address', $paramAdres);
$stmt->bindParam(':city', $paramCity);
$stmt->bindParam(':postalcode', $parampostal);
$stmt->bindParam(':pictureOfDamage', $parampic);
$stmt->bindParam(':description', $paramdescrip);
$stmt->execute();
$dbCon = null;
echo json_encode("toegevoegd ");
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this is my angular code (i'm using fileuploader right now.)
.controller('MeldingController', function ($scope, $upload, $rootScope, $state, $http) {
$scope.station = $rootScope.station;
$scope.PictureOfDamage;
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var pictureOfDamage = files[i];
return pictureOfDamage;
}
}
}
$scope.submit = function () {
console.log($scope.PictureOfDamage);
var data = {
station: $scope.station.name,
address: $scope.station.streetName,
postalcode: $scope.station.postalCode,
city: $scope.station.city,
pictureOfDamage: $scope.upload($scope.files) /* picture*/,
description: document.getElementById("Description").value
}
console.log('NOJSN ', data);
data = JSON.stringify(data);
console.log('JSON', data)
$http({
method: "POST",
url: 'http://localhost/Dats24/problem/add/',
data: data})
.success(function (data, status, headers, config) {
$state.go('GoogleMaps');
}).error(function (data, status, headers, config) {
console.log(data);
});
};
})
For your angular application, you can use the upload method of the $upload service like this:
file_upload: function(file) {
return $upload.upload({
url: 'http://your-upload-url/',
file: file
});
}
as described in here : https://github.com/danialfarid/ng-file-upload
Then on your service in PHP, you can get the file using
move_uploaded_file($_FILES['file']['tmp_name'], $file_path);
It will store the file on the path of your choice, then you can use PHP to do whatever you want with the file data.
I'm working with the plugin ParamQuery grid and to the data source need to get json data,
this what I want to do with $. getJson (...) {}, but I have a PHP class called data.php, which contains
a method called GetData other InsertData, DeleteData, (CRUD-using PDO), GetData returns the infromacion as json.
The problem is how to call the function from jquery?
the code I use is:
data.php
<?php
class Data {
private $db = NULL;
const DB_SERVER = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "usbw";
const DB_NAME = "musicstore";
public function __construct() {
$dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;
try {
$this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD);
} catch (PDOException $e) {
throw new Exception('Connection failed: ' . $e->getMessage());
}
return $this->db;
}
public function getData() {
$statement = $this->db->prepare("Select * from Customer");
$statement->execute();
if ($statement->rowCount() > 0) {
echo json_encode($statement);
}
return false;
}
}
?>
functionjquery.js
$.getJSON('Data.php', function(data) {
var obj = {};
obj.width = 1000;
obj.height = 400;
obj.colModel = [{title: "Rank", width: 150, dataType: "integer"},
{title: "Company", width: 200, dataType: "string"},
{title: "Revenues ($ millions)", width: 200, dataType: "float", align: "right"},
{title: "Profits ($ millions)", width: 200, dataType: "float", align: "right"}];
obj.dataModel = {data: data};
$("#grid_array").pqGrid(obj);
});
You need to create a page which constructs an instance of the Data class and then outputs the results of getData()
You shouldn't be echoing from inside a function though. Change your getData method to something like the following:
public function getData() {
$statement = $this->db->prepare("Select * from Customer");
$statement->execute();
return $statement->rowcount() > 0 ? $statement->fetchAll() : NULL;
}
Then, create a new page let's call it json_data.php for transparency's sake:
require_once "data.php";
$dataObj = new Data();
echo json_encode($dataObj->getData());
Now change your $.getJSON call in jQuery to request the json_data.php page.
$.getJSON('json_data.php', function(data) { ... });
And that should work.
Actually you can pass the parameter data along with the $.getJSON request to identify which method to be executed.
For Eg.
in functionjquery.js
$.getJSON('data.php', { method:'get' }, function(data) { ... });
in data.php
Change it as #Jason stated for best practice, and within that
if(isset($_GET['method'])){
switch (($_GET['method'])) {
case 'get':
echo json_encode(getData());
exit();
//other cases go here
default:
break;
}
}
In this way no need to create additional pages for each method