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);
}
}
Related
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;
}
);
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 have a poll and when user click on one of the options, it sends data through ajax:
$.ajax({
type: 'POST',
url: '/poll.php',
data: {option: option, IDpoll: IDpoll},
dataType: 'json',
async: false,
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
if(data.msg == "0") {
$( "#pollArea" ).load( "/pollVote.php", { allow: true }, function() {
alert( "Ďakujeme za Váš hlas!" );
});
}
else {
alert(data.msg);
alert("V tejto ankete ste už hlasovali.");}
}
});
This works fine. Now data are passed to the file poll.php:
if (isset($_POST['option']) && isset($_POST['IDpoll'])) {
require 'includes/config.inc.php';
$ip = $_SERVER['REMOTE_ADDR'];
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
$date = date("d.m.Y H:i:s");
$poll = new Poll();
$msg = $poll->votePoll($IDpoll, $ip, $option, $date);
$arr = array(
'msg' => $msg
);
echo json_encode($arr);
This also works, the problem happened in class Poll - method VotePoll:
public function votePoll($IDpoll, $ip, $option, $date)
{
try {
$query = "SELECT * FROM `votes` WHERE `IDpoll` = '$IDpoll' AND `ip` = '$ip'";
$result = $this->pdo->query($query);
if ($result->rowCount() == 0) {
/* do stuff */
}
catch (PDOException $e) {
return $e->getMessage();
}
}
And the error message from the ajax call is following: Call to a member function rowCount() on a non-object. I know what this message means, but I can't find out why the variable $result isn't considered as PDO object. Strange thing is, that when I try to call function votePoll manually, it works perfectly and when I use var_dump on result it is PDO object. So where is the mistake?
EDIT: I forgot to say I was just editing this function. Originally it worked with mysqli but I wanted to switch to pdo (so query and stuff like that are okay).
So, this problem was in these lines:
$option = $pdo->quote($_POST['option']);
$IDpoll = $pdo->quote($_POST['IDpoll']);
PDO quote function add quotes to the string so option became 'option' etc. Then it was sent to query where additional quotes were added, so the result was ''option'' and that is error.
Could someone please help me?
I have this 500 error when making a post request... Can't understand what it is
NOTE: If i run this api on from a rest client Chrome Extension it works Otherwise i get the following error...
The application could not run because of the following error:
Details
Type: ErrorException
Code: 8
Message: Trying to get property of non-object
Line:114
Routes:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/events','getEvents');
$app->get('/events/:year/:month', 'getMonth');
$app->get('/events/:year/:month/:day','getAllAfter');
$app->post('/events', 'addEvent');
$app->run();
This is My Function:
function addEvent() {
$app = \Slim\Slim::getInstance();
$request = $app->request();
$body = $request->getBody();
$event = json_decode($body);
//Line 114
$submited_date = $submited_date = $event->{'date_submit'} .' '.$event->{'time_submit'};
$sql = "INSERT INTO events (edate, title, performers, address) VALUES (:edate, :title, :performers, :address)";
try {
$conx = getconx();
$stmt = $conx->prepare($sql);
$stmt->bindParam("edate", $submited_date);
$stmt->bindParam("title", $event->etitle);
$stmt->bindParam("performers", $event->performers);
$stmt->bindParam("address", $event->address);
$stmt->execute();
$event->id = $conx->lastInsertId();
$conx = null;
$result = array("status"=>"success","events"=>$event);
echo json_encode($result);
} catch(PDOException $e) {
$result = array("status"=>"error","message"=>'Exception: ' . $e->getMessage());
echo json_encode($result,JSON_PRETTY_PRINT);
}
}
This is the json sent:
{
"date":"24 March, 2014",
"date_submit":"2014-03-24",
"time":"4:00 PM",
"time_submit":"16:00:00",
"etitle":"Event Title",
"performers":"david",
"address":"Place"
}
jquery code:
fixed by using JSON.stringify(); to the data before sending request
function addEvent(jsondat) {
console.log('addEvent');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL,
dataType: "json",
data: JSON.stringify(jsondat); ,
success: function(data, textStatus, jqXHR){
alert(Event created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
alert('addEvent error: ' + textStatus);
}
});
}
jQuery(document).on('ready', function() {
jQuery('form#myForm').bind('submit', function(event){
event.preventDefault();
var form = this;
var pson = ConvertFormToJSON(form);
//document.write(JSON.stringify(pson));
addEvent(pson);
});
});
The problem was found and it wasn't in my index.php
it was in the ajax request...
This was fixed by using JSON.stringify() to my serialized array.
That's why just in the rest client worked because the json there was sent correctly...
Thanks to Matt from slim framework support
http://help.slimframework.com/discussions/problems/6789-not-able-to-handle-post-request
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});