how to use PHP/Mysql generated json in AngularJS Application - php

I generated some Json data from Mysql Database with PHP as below:
equipments.php
<?php
require("config.inc.php");
//initial query
$query = "Select * FROM equipment";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Equipment Available!";
$response["equipments"] = array();
foreach ($rows as $row) {
$post = array();
$post["EquipmentId"] = $row["EquipmentId"];
$post["Name"] = $row["Name"];
$post["Ip"] = $row["Ip"];
$post["Brand"] = $row["Brand"];
$post["Location"] = $row["Location"];
//update our repsonse JSON data
array_push($response["equipments"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Equipment Available!";
die(json_encode($response));
}
?>
this returned the following data:
//localhost/equip/equipments.php (on my local apache server)
{
success: 1,
message: "Equipment Available!",
equipments: [
{
EquipmentId: "1",
Name: "UCH-NET",
Ip: "172.16.32.4",
Brand: "Engenius",
Location: "Top of ITD"
},
{
EquipmentId: "2",
Name: "UCH-PHOUSE",
Ip: "172.16.32.5",
Brand: "Mikrotik",
Location: "Top of ITD"
},
{
EquipmentId: "3",
Name: "UCH-SON",
Ip: "172.16.32.9",
Brand: "MIkrotik",
Location: "SON"
},
{
EquipmentId: "4",
Name: "UCH-GERIATRIC",
Ip: "172.16.32.10",
Brand: "Mikrotik",
Location: "Geriatric"
}
]
}
But when i try to use the returned Json like this in my AngularJS application no data is returned in the web page
services.js
'use strict';
var equipServices = angular.module('equipServices', ['ngResource']);
equipServices.factory('Equip', ['$resource',
function($resource){
return $resource( '/equip/equipments.php/');
}]);
equipment.js
function EquipmentsCtrl ($scope, Equip) {
$scope.setActive('equipments');
$scope.sidebarURL = 'partials/equipment.html';
$scope.currentEquipment = null;
$scope.setEquipment = function (EquipmentId) {
$scope.currentEquipment = $scope.equipments[EquipmentId];
};
$scope.equipments = Equip.query();
}
}
index.html
<title>IP Library</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
<script type="text/javascript" src="js/controllers/equipments.js"></script>
<script type="text/javascript" src="js/controllers/admins.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.min.css">
</head>
<body>
<div class="container" ng-controller="AppCtrl" >
<h1>IP Library</h1>
<ul class="nav nav-pills">
<li ng-class="equipmentsActive">
<a href="#equipments" >Equipments</a>
</li>
<li ng-class="adminsActive">
Administrators
</li>
</ul>
<div ng-view></div>
</div>
</body>
</html>
Is there something wrong with the way I am calling the php generated Json in my services.js?
Thanks

Use Equip.get() instead of Equip.query() because you are getting from server an object, not an array:
Equip.get(function(result){
if(result.success === 1) // isn't better to return boolean?
$scope.equipments = result.equipments;
// else handle error
});

Related

Update Datatable with Db records returned from AJAX Request

I have a very basic HTML Table. The data is from the database. I have now set up a datepicker with a button and as soon I click the button I do a AJAX request to get specific data for a specific date. (To make it easier my query just looks for id=1 as an example). I now want to return the data abnd update the datatable, but unfortunately the data is returned, but not shown.
data […]
0 {…}
id 1
category_id 1
title Technology Post One
This above is what gets returned. Am I doing a mistake in the format of the above or how do I update the datatable? I get the following error:
DataTables warning: table id=example - Requested unknown parameter '0' for row 0, column 0
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM posts WHERE id = 1";
result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 results";
}
$conn->close();
$msg = ["data" => $rows];
// handle request as AJAX
echo json_encode($msg);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Practise</title>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20 js/jquery.dataTables.js"></script>
</head>
<body>
<?php
$sql = "SELECT * FROM posts";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$conn->close();
?>
<table id="example" border="1"><thead>
<th>id</th>
<th>title</th>
<th>created at
<p>Date: <input type="text" id="datepicker"><button>Click</button> </p>
</th>
</thead>
<?php
foreach ($rows as $value){
echo '<tr>';
echo '<td>'.$value['id'].'</td>';
echo '<td>'.$value['title'].'</td>';
echo '<td>'.$value['created_at'].'</td>';
echo '</tr>';
}
echo '</table>'
?>
</body>
<script>
$(document).ready(function() {
$('#example').DataTable({
"columns": [
{"data": "id"},
{"data": "author"},
{"data": "created_at"}
],
},
);
$( "#datepicker" ).datepicker();
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
created_at: $("#datepicker").val()
},
success: function(data) {
$('#example').DataTable().ajax.reload();
},
error: function(result) {
alert('error');
}
});
});
} );
You can update the js script and create a new php file for ajax call which will return the new datatable. Try out this code it will work -
<script>
var created_at = '';
$(document).ready(function() {
var datatable = $('#example').DataTable({
'processing': true,
'scrollX': true,
'serverSide': true,
'serverMethod': 'post',
'searching' : true,
'ajax': {
url:'new-file.php',
data: function(data){
data.created_at = created_at;
}
},
"columns": [
{"data": "id"},
{"data": "author"},
{"data": "created_at"}
],
});
$( "#datepicker" ).datepicker();
$("button").click(function(e) {
e.preventDefault();
created_at = $("#datepicker").val();
datatable.draw();
});
} );
</script>

how to fetch json data to Intel XDK from php file

I have written php code to select specific patient info, i used pdo to connect with database, the result of file is json format.
{"success":1,"message":"patient info Available!","patient_info":[{"name":"Nora","gender":"M","email":"NouraSaeed#yahoo.com","Date":"2016-10-17"}]}
but when i wrote js code in intel xdk to display json data ,no output displayed on screen.How can i display the value of success or message in xdk !
<html>
<body>
<?php
require("config.inc.php");
$pid = $_GET["id"];
$query = " SELECT * FROM patient where PatientID=$pid";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch (PDOException $e) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "patient info Available!";
$response["patient_info"] = array();
foreach ($rows as $row) {
$post = array();
$post["name"] = $row["PName"];
$post["gender"] = $row["Gender"];
$post["email"] = $row["email"];
$post["Date"] = $row["BDate"];
array_push($response["patient_info"], $post);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No patient_info Available!";
die(json_encode($response));
}
?>
</body>
</html>
This xdk code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<script type="text/javascript">
function createXHR() {
if (typeof XMLHttpRequest != "undefined")
return new XMLHttpRequest();
else
return new ActiveXObject("Microsoft.XMLHttp");
}
function requestPatientInfo() {
var pid = document.getElementById("pid").value;
var oXmlHttp = createXHR();
oXmlHttp.open("get", "http://localhost/hospital/GetPatientData2.php?id=" + pid);
oXmlHttp.onload = function () {
if (oXmlHttp.readyState == 4) {
if (oXmlHttp.status == 200 || oXmlHttp.status == 304) {
var patients = json.parse(oXmlHttp.responseText);
divPatientInfo.innerHTML = patients.message;
}
else
divPatientInfo.innerHTML = oXmlHttp.statusText;
}//end if
}; //end ready state
oXmlHttp.send(null);
}//end function requestPatientInfo
</script>
</head>
<body>
Enter Patient ID to get All Information
<p>
Patient ID: <input type="number" id="pid"/>
</p>
<input type="button" value="Get Info" onClick="requestPatientInfo();"/>
<div id="divPatientInfo"></div>
<iframe name="hiddenFrame" style="width:0 ; height:0"></iframe>
</body>
</html>
Looks you have not defined divPatientInfo.. change as following
var divPatientInfo = document.getElementById('divPatientInfo');
if(oXmlHttp.readyState==4){
if(oXmlHttp.status==200 || oXmlHttp.status== 304 ){
var patients= json.parse(oXmlHttp.responseText);
divPatientInfo.innerHTML=patients.message;
}
else
divPatientInfo.innerHTML=oXmlHttp.statusText;
}//end if
If not resolved check once ajax response using firebug, if possible paste here so that help more.

JTables php giving error

I am trying to run the jtable demos for php, but am always having an error that is :
"An error occured while communicating to the server".
I know that i can list the json encode , because i tried to print it, but cant get the data inside the table because of that error.
Thanks in advance
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Datatable with mysql</title>
<link href="themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="Scripts/jtable/themes/lightcolor/blue/jtable.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="Scripts/jtable/jquery.jtable.js" type="text/javascript"></script>
<div class="container">
<div class="">
<h1>jTable Demo Server Side</h1>
<div class="col-sm-8" id="employee_grid">
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').jtable({
title: 'List of Employees',
           defaultSorting: 'Name ASC',
actions: {
listAction: 'response.php?action=list',
createAction: 'response.php?action=create',
updateAction: 'response.php?action=update',
deleteAction: 'response.php?action=delete'
},
fields: {
personID: {
title: 'EMPId',
width: '10%',
edit: false
},
name: {
title: 'Employee Name',
width: '40%'
},
age: {
title: 'Employee Salary',
width: '20%'
},
recordDate: {
title: 'Age',
width: '30%'
}
}
});
$('#employee_grid').jtable('load');
});
</script>
response.php
<?php
try
{
//Open database connection
$con = mysqli_connect('localhost', 'root', '','aaa') or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db( $con,"aaa");
//Getting records (listAction)
if($_REQUEST["action"] == "list")
{
//Get records from database
$result = mysqli_query($con,"SELECT * FROM `people`;");
//Add all records to an array
$rows = array();
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
echo json_encode($jTableResult);
}
else if($_REQUEST["action"] == "create")
{
//Insert record into database
$result = mysqli_query($con, "INSERT INTO people(Name, Age, RecordDate) VALUES('" . $_POST["Name"] . "', " . $_POST["Age"] . ",now());");
//Get last inserted record (to return to jTable)
$result = mysqli_query($con , "SELECT * FROM people WHERE PersonId = LAST_INSERT_ID();");
$row = mysqli_fetch_array($result);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
//Close database connection
mysqli_close($con);
}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
echo json_encode($jTableResult);
}
?>
That is I cant put this demo to work.

Ajax JSON passing more then one variable

Hello guys i am new to both ajax and JSON and i have followed this guide on making a jquery slider and getting some result from DB it is working but right now i can only get one result from the slider range but i want to get all results from that range so i need to pass more then one result variable from my php and cant seem to get it to work i have included my code below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script src="slider.js"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div>
<span id="deal_min_price"></span>
<span id="deal_max_price" style="float: right"></span>
<br /><br />
<div id="slider_price"></div>
<br />
<span id="number_results"></span> Abonnementer fundet
</div>
</body>
</html>
$(document).ready(function()
{
$( "#slider_price" ).slider({
range: true,
min: 0,
max: 349,
step:1,
values: [ 0, 349 ],
slide: function( event, ui ) {
$( "#deal_min_price" ).text(ui.values[0] + "KR");
$( "#deal_max_price" ).text(ui.values[1] + "KR");
},
stop: function( event, ui ) {
var dealsTotal = getDeals(ui.values[0], ui.values[1]);
$("#number_results").text(dealsTotal);
},
});
$("#deal_min_price").text( $("#slider_price").slider("values", 0) + "KR");
$("#deal_max_price").text( $("#slider_price").slider("values", 1) + "KR");
});
function getDeals(min_price, max_price)
{
var numberOfDeals = 0;
$.ajax(
{
type: "POST",
url: 'deals.php',
dataType: 'json',
data: {'minprice': min_price, 'maxprice':max_price},
async: false,
success: function(data)
{
numberOfDeals = data;
}
});
return numberOfDeals;
}
PHP:
<?php
$result = 0;
define('MYSQL_HOST', 'db564596075.db.1and1.com');
define('MYSQL_USER', 'dbo564596075');
define('MYSQL_PASSWORD', '12345678');
define('MYSQL_DB', 'db564596075');
try
{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
}
catch (PDOException $e)
{
echo 'Fejk: ' . $e->getMessage() . '<br/>';
}
if(isset($_POST['minprice']) && isset($_POST['maxprice']))
{
$minprice = filter_var($_POST['minprice'] , FILTER_VALIDATE_INT);
$maxprice = filter_var($_POST['maxprice'] , FILTER_VALIDATE_INT);
$query = '
SELECT
*
FROM
mobilabonnement
WHERE
Prisprmdr
BETWEEN
:minprice
AND
:maxprice
';
$stmt = $dbh->prepare($query);
try
{
$stmt->bindParam(':minprice', $minprice);
$stmt->bindParam(':maxprice', $maxprice);
$stmt->execute();
}
catch (PDOException $e)
{
print($e->getMessage());
die;
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $row['Selskab'];
}
if ($result == true)
{
echo json_encode($result);
}
else{
echo json_encode(0);
}
?>
Here is why You got only Selskab - $result = $row['Selskab'];
Try that:
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $row;
if ($result)
{
echo json_encode($result);
}
else
{
echo json_encode(0);
}
You need to loop over all the results or use PDO::fetchAll, if you want all the columns you also need to use the whole row not just Selskab:
$result = array();
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$result[] = $row;
}
if (count($result)
{
echo json_encode($result);
} else{
echo json_encode(0);
}
OR using PDO::fetchAll:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result)
{
echo json_encode($result);
} else{
echo json_encode(0);
}
However it also seems you really only want Selskab and id as opposed to all of the columns and in that case you should probably adjust your query as well:
SELECT id, Selskab
FROM mobilabonnement
WHERE Prisprmdr BETWEEN :minprice AND :maxprice

how to render multiple jqplot's pie charts in single page

I am using JQplots for rendering the piecharts.I have 2 piecharts.Individually they are working fine. But when I want them in a single page, they are overlapping on one another. Please let me know how can I show them one beside the other? Thanks in advance.
chart 1 code:
<!-- for jqplot graphs -->
<script src="../../assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="../../js/jqplot.js"></script>
<script type="text/javascript" src="../../assets/plugins/jqplot.pieRenderer.min.js"></script>
<link rel="stylesheet"href="../../css/graphs.css" type="text/css">
<!-- end of jqplot graphs js -->
<?php
/* Your Database Name */
$dbname = 'finalCMS';
/* Your Database User Name and Passowrd */
$username = 'root';
$password = 'password';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT ComplianceStatus,count FROM indexonboard WHERE zone='SEA' and country='SG'");
$rows = array();
foreach($result as $r) {
$rows[] = array( $r['ComplianceStatus'],(int)$r['count']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
print_r($jsonTable);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//mysql_close($conn);
$conn=null;
?>
<script>
function drawchart(){
//function drawchart()
var data1 =<?php echo $jsonTable;?>;
alert(data1);
var plot1 = jQuery.jqplot ('chartsg', [data1],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show:true, location: 'e' }
}
);
}
drawchart();
</script>
<div id="chartsg"></div>
The code for chart 2:
<!-- for jqplot graphs -->
<script src="../../assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="../../js/jqplot.js"></script>
<script type="text/javascript" src="../../assets/plugins/jqplot.pieRenderer.min.js"></script>
<link rel="stylesheet"href="../../css/graphs.css" type="text/css">
<!-- end of jqplot graphs js -->
<?php
/* Your Database Name */
$dbname = 'finalCMS';
/* Your Database User Name and Passowrd */
$username = 'root';
$password = 'password';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT Compliancestatus,value FROM COUNT_VALUE WHERE Zone='PZ' and country='AU' and `Compliancestatus` is not null
");
$rows = array();
foreach($result as $r) {
$rows[] = array( $r['Compliancestatus'],(int)$r['value']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
print_r($jsonTable);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//mysql_close($conn);
$conn=null;
?>
<script>
$(document).ready(function(){
//var data1=[
// ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
// ['Out of home', 16],['Commuting', 7], ['Orientation', 9]
// ];
var data1 =<?php echo $jsonTable;?>;
alert(data1);
var plot1 = jQuery.jqplot ('chart1', [data1],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show:true, location: 'e' }
}
);
});
</script>
<div id="chart1"></div>
query("SELECT ComplianceStatus,count FROM indexonboard WHERE zone='SEA' and country='SG'");
use different holders for both and fixed the width and height
<div id="piechartHolder" >
<div style="width:50%">
<span id="Chart1Title">Chart1</span>
<div id="chart1" style="width:100%">
</div>
<div style="width:50%">
<span id="Chart2Title">Chart2</span>
<div id="chart2" style="width:100%">
</div>
</div>
Try specifying div sizes, it should help
<div id="chart" style="height:300px; width:600px;"></div>

Categories