This question already has answers here:
Unexpected token colon JSON after jQuery.ajax#get
(2 answers)
Closed 4 years ago.
I want to get data from my Database into my Angluar.js.
So i created a php file, which selects my data.
I read that i have to use jsonp, elsewhise i will not get the data.
data.php
<?php
$db = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$select = "select * from product;";
$result = mysqli_query($db,$select);
if ($result) {
$i=0;
$outp = "";
while ($row = mysqli_fetch_assoc($result))
{
if ($outp != "") {$outp .= ",";}
$outp .= '"preis":"' . $row["preis"] . '",';
$outp .= '"name":"'. $row["name"] . '"}';
}
$outp ='{"records":['.$outp.']}';
echo($outp);
}
?>
App.js
var url = "http://server/data/data.php?callback=JSON_CALLBACK"
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
Now i get a syntax error:
"SyntaxError: unexpected token: ':'"
Thanks for your help
Don't build JSON by yourself. Try this instead. Main thing is, just create an array the way you'd like it, then use json_encode()
$result = [];
while ($row = mysqli_fetch_assoc($result))
{
$result[] = $row;
}
echo json_encode($result);
Related
I am coding a PHP file to select all records in a table which matches the criterias, before counting the number of records retrieved.
What I'm trying to do is:
Assuming it retrieves 5 records, I want the PHP file to return only [{"count":5}]
Can someone propose a way to make the file return the above?
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "userid", "password", "dbname");
$admin_no = $_GET['admin_no'];
$result = $conn->query("Select lecturer_id,admin_no,message,date_time_sent,sender from chat where lecturer_id = 'shizukakudo' and admin_no = '". $admin_no ."'");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"lecturer_id":"' . $rs["lecturer_id"] . '",';
$outp .= '"admin_no":"' . $rs["admin_no"] . '",'; $outp .= '"message":"' . str_replace('"','',$rs["message"]) . '",';
$outp .= '"date_time_sent":"' . $rs["date_time_sent"] . '",';
$outp .= '"sender":"' . $rs["sender"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp.length);
?>
Use json_encode() like so:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "userid", "password", "dbname");
$admin_no = $_GET['admin_no'];
$result = $conn->query("Select lecturer_id,admin_no,message,date_time_sent,sender from chat where lecturer_id = 'shizukakudo' and admin_no = '". $admin_no ."'");
$data = $result->fetch_array(MYSQLI_ASSOC);
$arrData = [
"count" => count($data)
];
$json = json_encode($arrData);
?>
What I'm trying to do is: Assuming it retrieves 5 records, I want the PHP file to return only [{"count":5}]
If this is your requirement, then there's no point using that while loop. After executing the query, simply do this:
// your code
$result = $conn->query("Select lecturer_id,admin_no,message,date_time_sent,sender from chat where lecturer_id = 'shizukakudo' and admin_no = '". $admin_no ."'");
$outp = array();
$outp[]['count'] = $result->num_rows;
echo json_encode($outp);
Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
I get an error which doesn't say anything to me. I'm kinda new to Angular so it might be a really stupid error but I can't figure out.
It says there's a Syntax Error:
SyntaxError: Unexpected token /
at Object.parse (native)
at fromJson (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:1252:14)
at defaultHttpResponseTransform (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9414:16)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9505:12
at forEach (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:336:20)
at transformData (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9504:3)
at transformResponse (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:10276:23)
at processQueue (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:14745:28)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:14761:27
at Scope.$eval (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:15989:28)
My html Code where I'm calling the controller:
<div ng-controller="dbTestCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
My Angular controller:
module.controller('dbTestCtrl', function($scope, $http) {
$http.get(PHP_API + "datahandler/dbTest.php")
.then(function (response){
$scope.names = response.data.records;});
});
And my php file which is working as far as i can see:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "cmweb");
$result = $conn->query("SELECT loginName, userID, createDate FROM users");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {
$outp .= ",";
}
$outp .= '{"Name":"' . $rs["loginName"] . '",';
$outp .= '"ID":"' . $rs["userID"] . '",';
$outp .= '"Created":"'. $rs["createDate"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
As I said I'm really new to angular and I just couldn't figure out by myself so it would be great if someone could help me out :)
Thx
May be your json format is wrong. Try using json_encode to avoid writing all those quotes and brackets by yourself.
$outp = array();
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = array('Name' => $rs["loginName"],
'ID' => $rs["userID"],
'Created' => $rs["createDate"]);
}
echo json_encode(array('records' => $outp));
On my website, I'm using ajax to send data to an external php script, which queries a database and returns the result to the website. I ran into the problem, that I can only return strings with php, but I want to return an array of objects (which is valid json). My code looks like this at the moment:
php
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
if($_GET["feed"] == "hausaufgaben") {
$query = "SELECT fach, aufgabe, datum FROM hausaufgaben WHERE fachgruppe != '";
if($_GET["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_GET["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = mysqli_query($connection, $query);
$data = [];
while($row = mysqli_fetch_row($result)) {
$object = '{"fach": "' . $row[0] . '", "datum": "' . $row[2] . '", "aufgabe": "' . $row[1] . '"}';
array_push($data, json_decode($object));
}
echo $data;
}
ajax
$.ajax({
type: "GET",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data, textStatus, jqXHR) {
alert(typeof(data));
this.hausaufgaben = data;
})
.fail(function(jqXHR, textStatus, error) {
alert("error: " + error);
});
It always throws the error "Unexpected token A". I got it to return each single line in the array as string, but I can't use a string in my website. My problem is, that I can't echo an array of objects with php and get the array with ajax.
Instead of trying to build a json string yourself you can do it all much easier by building the $data array using PHP data structures and then using json_encode() to convert it all to a JSON string for sending to your javascript.
Reference json_encode and json_decode
Like this :-
$data = [];
while($row = mysqli_fetch_object($result)) {
$data[] = $row;
}
echo json_encode($data);
You will also have to change you javascript to process an array of objects rather than a string, but that should be easy
So basically i have json file made from SLQ database by PHP script
Geting angular to read json and binds to scope
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://kserwach.nazwa.pl/extremerun/data.php")
.success(function (response) {$scope.names = response.records;});
});
You can look at json file by simply enterning this link
[http://kserwach.nazwa.pl/extremerun/data.php][1]
My problem is that, while i put any "new line" in SQL angular crashes. How can i make angular to not crash while someone press "enter button" while writing new desc? Or else how to make json file to replace this "enter" with some html tag, and then how to make angular to read this html tag?
This is how i read mySQL data
<?php
$user='user_name';
$password='password';
$dbname='db_name';
$host='host';
try
{
$db = new PDO('mysql:host='.$host.';dbname='.$dbname.';',$user,$password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>"; die();
}
$stmt = $db-> query('SELECT name,description,surname,photo FROM mates');
$temp = 0;
$outp = "";
foreach($stmt as $row)
{
if($temp == 0) {
$outp .= '{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
$temp = 1;
} else {
$outp .= ',{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
}
}
$outp ='{"records":['.$outp.']}';
echo($outp);
?>
And then, sorry for my bad english. Just not primary, or even secondary language.
I've got a working version of the code on my local machine using xampp but when I uploaded it to my Raspberry Pi it seems to go haywire.
Basically I've got an angularjs script calling a file called dbConn.php which is in the same directory and works on a local machine but doesn't when uploaded to a Pi.
function raspberryController($scope, $http, $timeout) {
var poll = function() {
$timeout(function() {
try{
$http.get("dbConn.php")
.success(function(response) {$scope.names = response;})
.error(function(data, status, header, config) {
console.log(alert, status, header, config);
});
} catch (e) {
console.log("Got an error!",e);
throw e;
// rethrow to not marked as handled
}
poll();
}, 1000);
}
poll();
}
dbConn.php
<?php
//$db = new SQLite3('system/modules/test.db');
header("Access-Control-Allow-Origin: *");
try{
$dbh = new PDO('sqlite:system/test.db') or die("cannot open db");
} catch(Exception $e) {
echo $e->getMessage();
}
$query = 'SELECT * FROM connected;';
$results = $dbh->query($query);
$outp = '[';
foreach($dbh->query($query) as $row){
if ($outp != "[") {
$outp .= ",";
}
$outp .= ' { "ID":"' . $row[0] .'",';
$outp .= '"IP":"' . $row[1] .'",';
$outp .= '"CONNECTED":"' . $row[2] .'",';
$outp .= '"LEASE_TIME":"' .$row[3] .'" } ';
}
$outp .= ']';
echo($outp);
?>
You have:
try { $dbh = new PDO('sqlite:system/test.db') or die("cannot open db"); } catch(Exception $e) { echo $e->getMessage(); }
You're trying to call the query() function on the $dbh object outside of the try.
Here's a link to variable scoping in PHP: http://php.net/manual/en/language.variables.scope.php
To solve your problem either have an empty $dbh variable outside the try block and then initialise it within the try eg:
$dbh = null;
try {
$dbh = new PDO('sqlite:system/test.db') or die('cannot open db');
} catch (Exception $e) {
//some code to handle it in here
exit(); //to stop anything else from executing
}
$result = $dbh->query();
The other way to solve the problem would be to put the rest of your code in the try/catch block you've created for the initialisation of the $dbh variable.
try {
$dbh = new PDO('sqlite:system/test.db') or die('cannot open db');
$query = 'SELECT * FROM connected;';
$results = $dbh->query($query);
$outp = '[';
foreach($results as $row){
if ($outp != "[") {
$outp .= ",";
}
$outp .= ' { "ID":"' . $row[0] .'",';
$outp .= '"IP":"' . $row[1] .'",';
$outp .= '"CONNECTED":"' . $row[2] .'",';
$outp .= '"LEASE_TIME":"' .$row[3] .'" } ';
}
$outp .= ']';
echo $outp;
} catch (Exception $e) {
echo $e->getMessage();
}
You'd be better off abstracting DB logic into a separate class and using it like a Singleton or a static class as detailed in this other post: Best practices for a PDO class?.
Oh and for future reference, the easiest way to find out what's going wrong if you're met with a unhelpful err 500 is to use tail -f /var/log/apache2/error.log from your terminal if you're using a Debian distro such as Raspbian.