i am trying to create a service that will return a json data from php api, but instead of return pure json data, the angular seem to return JSON together with its config.
services.js
.service('DistinctAPIService', function($http){
var base = 'http://localhost/onseral/api/';
this.listDistinct = function(table, field){
return $http({
method: 'POST',
url: base + '/listDistinct.php',
params: {
table: table,
field: field
}
});
}
})
.controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(data){
$scope.data = data;
console.log(JSON.stringify(data));
})
})
listdistinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
instead of returning the correct JSON data, it returned
{"data":{"data":[{"expr1":"CFFBPS16"}]},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/onseral/api//listDistinct.php","params":{"table":"material_copy","field":"matcode"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
any idea?
try this
controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(response){
$scope.data = response.data.data;
console.log(JSON.stringify(data));
})
Use header function before sending data to the client side.
i modified your listdistinct.php file. try it , let me know if issue persist.
<?php $sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
header('Content-Type: application/json');
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
Related
I'm trying to set a session variable in php using Slim. I want the users id to be stored as a variable to use elsewhere. I think I have the syntax or order wrong in my functions.
Here is my function to set the variable:
function loadAdmin()
{
//Set new session and save user id to variable
if (!isset($_SESSION)) {
session_start();
}
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('token');
$token_exists = getToken_Validate();
if($token_exists) {
$sql = "SELECT id, title AS admin_title, last_name AS admin_last_name
FROM admin WHERE token=:token";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':token', $token);
$stmt->execute();
$admin = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($admin);
$_SESSION['uid'] = $stmt['id'];
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} else {
echo '{"err": "failed"}';
}
}
Here is my function to use the variable when fetching specific data:
function loadDashboard()
{
session_start();
$uid = $_SESSION['uid'];
$token_exists = getToken_Validate();
if ($token_exists) {
//Get number of rows from multiple tables
$sql = "SELECT
(SELECT COUNT(*) FROM users WHERE id=:uid) AS total_students,
(SELECT COUNT(*) FROM subjects) AS total_subjects,
(SELECT COUNT(*) FROM notes) AS total_notes";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':uid', $uid);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} else {
echo '{"err": "failed"}';
}
}
The Slim error I get after trying to loadDashboard is:
Undefined index: uid
Sorry if my PHP is awful, any help is appreciated.
Turns out it had nothing to do with Slim.
$_SESSION['uid'] = $stmt['id']; was not storing anything to the variable.
I had to first bind the id column to a variable:
$stmt->bindColumn('id', $uid);
Then I could set that variable as a session variable:
$_SESSION['uid'] = $uid;
Here is the full working function:
function loadAdmin()
{
if (!isset($_SESSION)) {
session_start();
}
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('token');
$token_exists = getToken_Validate();
if($token_exists) {
$sql = "SELECT
id,
title AS admin_title,
last_name AS admin_last_name
FROM admin WHERE token=:token";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':token', $token);
$stmt->execute();
$stmt->bindColumn('id', $uid);
$admin = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
$_SESSION['uid'] = $uid;
echo json_encode($admin);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
else {
echo '{"err": "failed"}';
}
}
I am trying to connect my angularjs application to a simple php script which is simply returning a sql query from sqlite3 database.
Here is my PHP script:
<?php
date_default_timezone_set('UTC');
try {
$objDb = new PDO('sqlite:../dbase/shopper');
$objDb -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT item.* ,
t.name AS type_name
FROM items item
INNER JOIN types t
ON t.id = item.type
ORDER BY item.date ASC";
$result = $objDb->query($sql);
if(!$result) {
throw new PDOException("The result returned no object");
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$items = $result->fetchAll();
$sql = "SELECT *
FROM types
ORDER BY id";
$result = $objDb->query($sql);
echo var_dump($result);
if(!$result) {
throw new PDOException("The result returned no object");
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$types = $result->fetchAll();
echo json_encode(array(
'error' => false,
'items' => $items,
'types' => $types
), JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
} catch (PDOException $e) {
echo json_encode(array(
'error' => true,
'message' => $e->getMessage()
),JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
}
When I check the php file address I can get the result :
object(PDOStatement)#3 (1) { ["queryString"]=> string(41) " SELECT * FROM types ORDER BY id " }
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
If I use angularjs I get undefined results.
.controller('ShoppingListController', function($scope, $http, $log ){
$scope.types = [];
$scope.items = [];
$scope.item = '';
$scope.qty = '';
$scope.types = '';
$scope.select = function( ) {
$http({method: 'GET',url: 'mod/select.php'})
.success(function(data){
console.log(data)
$scope.items = data.items;
if(data.types) {
$scope.types = data.types;
$scope.type = $scope.types[0].id;
}
})
.error(function(data,status,header){
throw new Error('Something went wrong with selecting record');
});
};
$scope.select();
});
console.log(data) shows :
object(PDOStatement)#3 (1) {
["queryString"]=>
string(41) " SELECT *
FROM types
ORDER BY id "
}
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
How can I fix this ?
You must return a JSON response. Fetch an associative array from your database and return this:
echo json_encode($db_query);
In Angular, you can then set the scope equal to the response ex:
$scope.items = data.items;
You can then access this in your view (be sure to have ng-controller="ShoppingListController").
To iterate over the data:
ng-repeat="item in items"
You can then access each piece via item.id or whatever your key in the array may be.
Also, no need to set $scope.items at the top.
Edit:
.controller('ShoppingListController', function($scope, $http, $log) {
function select() {
$http.get('mod/select.php')
.success(function(data) {
$scope.items = data.items;
if(data.types) {
$scope.types = data.types;
$scope.type = $scope.types[0].id;
}
});
}
select();
});
Remove the var_dump(); And BTW you don't need to echo with var_dump(), it already appends to the output buffer. The var_dump() makes your response invalid JSON.
I have trouble deleting record from my MYSQL Database(with Slim PHP framework). My code is:
PHP
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->delete('/delete_article', 'deleteArticle');
$app->run();
function deleteArticle() {
$request = Slim::getInstance()->request();
$article = json_decode($request->getBody());
$sql = "DELETE FROM articles WHERE article_name = ':article_name'";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("article_name", $article->name);
$stmt->execute();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Template controller:
'use strict';
app.controller('clankyCtrl', ['$scope', '$http', '$location',
function ($scope, $http, $location) {
$scope.delete_article = function(article) {
$http.delete('data/api/delete_article', article).success(function(){
$location.path('home/clanky');
});
};
}]);
Template:
<tr ng-repeat="article in articles">
<td>{{article.article_name}}</td>
<td ng-bind-html="article.article_content | cut:true:100"></td>
<td class="text-right">{{article.article_datetime}}</td>
<td>edit/<button ng-click="delete_article(article)">Delete</button></td>
</tr>
Since HTTP response is 200 I suppose the mistake is probably in data selection.
You don't need quotation marks around :article_name in your query. PDO bindParam takes care of this for you. You also need to colon in front of the name when binding. Try this:
$sql = "DELETE FROM articles WHERE article_name = :article_name";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":article_name", $article->name);
$stmt->bindParam(":article_name", $article->name);
I'm playing with jQuery's $.ajax and I'm not sure how I should be doing the following:
Here's my javascript (right now its just embedded in the html page)
$.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {
console.dir(data);
},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
Here is what DBConnect.php looks like:
$username = "root";
$pass = "pass";
$host = "127.0.0.1";
$dbname = "test";
//queries
$table = "events";
$fetchAll = "SELECT * FROM $table";
try {
$DB = new PDO("mysql:host=$host;dbname=$dbname", $username, $pass);
//_WARNING uncommented when debugging
$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
//$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = $DB->query($fetchAll);
$query->setFetchMode(PDO::FETCH_OBJ);
while($row = $query->fetch()) {
echo json_encode($row);
}
} catch(PDOException $e) {
echo $e->getMessage();
}
$DB = null;
Doing this I get a syntax error. I thought I could get away with returning every row as a json object, but clearly that doesn't work. I could just add all the row objects to one array and convert that to json, but I wanted to know if there was a better\more efficient way to do this.
Change the while loop:
$temp = array();
while($row = $query->fetch()) {
$temp[] = $row;
}
echo json_encode($temp);
Try this, and let me know if that helps!
I am trying to fill a dropdown list from a mysql database by using ajax and jquery. The data is should be in json format. But I keep getting syntax error: JSON.parse: unexpected character. Please advise. Thank you for your help.
This is my code in Dreamweaver
$(document).ready(function(){
$.getJSON("http://localhost:8000/states.php", function(data) {
$.each(jsondata, function(index, item) {
$('<option></option>').val(item.state_code).html(item.state).appendTo("select#personalstate");
});
});
});
Database code:
database.php
<?php
$dsn = 'mysql:host=localhost;dbname=elihu';
$username = 'admin';
$password = 'password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$db = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include ('index.php');
exit();
}
?>
json php file
<?php
require('database.php');
function getStates() {
global $db;
$query = 'SELECT * FROM states';
try {
$statement = $db->prepare($query);
$statement->execute();
$states = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
echo json_encode($states);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include ('index.php');
exit();
}
}
?>
$.getJSON("Model/php/states.php", function(data) {
// No need to parse the json data, it's already been parsed by getJSON
// jsondata = $.parseJSON(data);