Get Data from PHP in angular unhandled error - 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));

Related

How do I display the MySQL data in Angular

I've been trying to learn some SQL for my covid-19 timepass and I managed to make data and all but I'm now stuck with this, I'm lost on how to repeat with angular the table that I got from my SQL DB in the TABLE BELOW!, I looked at W3School and couple other websites but I didn't get it.
PHP
if($connectServer->connect_error){
die("Connection failed :".$connectServer->connection_error);
}
$result = $connectServer->query("SELECT * FROM Users");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"ID":"' . $rs["userID"] . '",';
$outp .= '"First Name":"' . $rs["FName"] . '",';
$outp .= '"Last Name":"' . $rs["FName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Email":"'. $rs["Email"] . '"}';
}
$outp ='{"names":['.$outp.']}';
echo($outp);?>
HTML
<table ng-controller="customersCtrl" ng-app="myApp">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
<th>Email</th>
</tr>
<tr ng-repeat="a in names">
<td>{{a.ID}}</td>
<td>{{a.First Name}}</td>
<td>{{a.LName}}</td>
<td>{{a.City}}</td>
<td>{{a.Email}}</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("php/fetchDATA.php")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
fetchDATA.PHP
{"names":[{"ID":"32","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"},{"ID":"33","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"},{"ID":"34","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"}]}
There are some mistakes in each of your code like variable {{a.First Name}} having space and {{a.LName}} is not defined anywhere.
So you must change the variable declaration in php for the code to work.
Further the response you are expecting must have the variable records but the php you have defined does not have any such variable. Thus I will suggest you to read PHP and Angular tutorial again before asking the question.

JSONP in Angularjs [duplicate]

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);

Return Count of Array Fetched as JSON friendly output

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.

Angular crashing while there is a "Enter" in json file

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.

Fetch php response using angularjs

I'm using angularjs for my app and php to fetch data from server...
The php file gets all the needed variables but when i'm trying to see the answer using angular I only get [object Object], [object Object] and so on...
Any ideas?
Thanks!
Angular code:
app.controller('FormController', ['$scope', '$http', function($scope, $http){
$scope.submit = function() {
var data = {
'days': $scope.days,
'age_18': $scope.age_18,
'age_13_17': $scope.age_13_17,
'age_8_12': $scope.age_8_12,
'age_3_7': $scope.age_3_7,
'water': true,
'outside': true
}
$http.post('php/get_data.php', data)
.success(function(data, status, headers, config) {
alert(data);
})
}
}])
Php Code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "nathan", "nathan", "nathan");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$age_18 = $request->age_18;
$age_13_17 = $request->age_13_17;
$age_8_12 = $request->age_8_12;
$age_3_7 = $request->age_3_7;
$days = $request->days;
$water = $request->water;
$outside = $request->outside;
$result = $conn->query("SELECT id, modal_name, name,('$age_18'*18_rating + '$age_13_17'*13_17_rating
+ '$age_8_12'*8_12_rating + '$age_3_7'*3_7_rating) as total
FROM parks
WHERE (water_park LIKE '$water' OR water_park LIKE 0)
and (outside_orlando LIKE '$outside' OR outside_orlando LIKE 0)
ORDER BY total DESC");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"name":"' . $rs["name"] . '",';
$outp .= '"modal_name":"' . $rs["modal_name"] . '",';
$outp .= '"id":"' . $rs["id"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
The output you get is an array of objects.
Try the following :
$http.post('php/get_data.php', data)
.success(function(data, status, headers, config) {
for (var j = 0; j < data.length; j++) {
alert(data[j].name);
}
})
Please check this and tell me if it is working for you:
$http.post('php/get_data.php', JSON.stringify(data))
.success(function(data, status, headers, config) {
alert(data);
})

Categories