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

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.

Related

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

Get Data from PHP in angular unhandled error

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

AngularJS .get Method Causing Internal Error 500

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.

Trouble retrieving MySQL data using JSON

I am trying to use JSON w/PHP to retrieve data from MySQL database and have run into a problem. I get my table back from Server except when I include the Comments field in my query. I checked out the JSON in JSON LInt and that came back ok. The MySQL query checks out on its own. And looking in firebug I see SyntaxError: JSON.parse: bad control character in string literal at line 1 column 184 of the JSON data. I just get my header on the page. the code is:
example.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "*****", "*****", "inventory_form");
$result = $conn->query("SELECT Comments, FName, LName, Eqpmnt_Brwd, Date_Taken, Brwd_Rsn, Service_Tag FROM Inventory");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Comments":"' . $rs["Comments"] . '",';
$outp .= '"FirstName":"' . $rs["FName"] . '",';
$outp .= '"Eqpmnt_Brwd":"'. $rs["Eqpmnt_Brwd"] . '",';
$outp .= '"Date_Taken":"'. $rs["Date_Taken"] . '",';
$outp .= '"Brwd_Rsn":"'. $rs["Brwd_Rsn"] . '",';
$outp .= '"ServiceTag":"'. $rs["Service_Tag"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
index.html:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>SHS Inventory Form</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "inventory_table.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Comments +
"</td><td>" +
arr[i].FirstName +
"</td><td>" +
arr[i].Eqpmnt_Brwd +
"</td><td>" +
arr[i].Date_Taken +
"</td><td>" +
arr[i].Brwd_Rsn +
"</td><td>" +
arr[i].ServiceTag +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
and a sample of response text is:
"[{"Comments":"","FirstName":"Nadine","Eqpmnt_Brwd":"Apple Video Dongle","Date_Taken":"2014-09-05","Brwd_Rsn":"Returned","ServiceTag":""},{"Comments":"Wants to check out hovercam. Can retrieve it if anyone needs a hovercam.","FirstName":"Nicole ","Eqpmnt_Brwd":"Hovercam","Date_Taken":"2014-09-04","Brwd_Rsn":"Borrowed","ServiceTag":"075642"},{"Comments":"with SD card All six cameras borrowed on 9/8/14 will be used throughout that school week.Expected return date is Monday 9/15/14","FirstName":"George","Eqpmnt_Brwd":"Nikon D3100 Camera","Date_Taken":"2014-09-08","Brwd_Rsn":"Borrowed","ServiceTag":"074753"},{"Comments":"w/ SD card "
Is there a problem with some of the text in the Comments field needing to be escaped? I've looked online but cant find much on the topic. Realize you should probably use PDO for this but good luck finding examples. I will work on that once I get this example working properly.
As #Barmar said use json_encode instead of trying to construct a JSON string by hand. For example:
$data = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $rs;
}
$conn->close();
echo json_encode($data);
In response to your comment/question about PDO... With PDO you can simplify this by using PDOStatement::fetchAll:
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->query("SELECT Comments, FName, LName, Eqpmnt_Brwd, Date_Taken, Brwd_Rsn, Service_Tag FROM Inventory");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

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