I am a newbie in AngularJS. Need your help guys on what did I miss. I'm just trying to read some data from SQL Server for now. Thank you.
products.php
code I use to retrieve the data.
<?php
/* Set Connection Credentials */
$serverName="localhost";
$uid = "sa";
$pwd = "password123";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>"TESTDB",
"CharacterSet"=>"UTF-8");
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
/* TSQL Query */
$tsql = "SELECT pk_products, prodName, prodDescription FROM dbo.products";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
/* Process results */
$json = array();
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
header('Content-Type: application/json');
echo json_encode($json);
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('ProductCtrl', ['$scope', '$http', function($scope, $http) {
$http({
method: 'GET',
url: 'products.php'
}).then(function(success) {
$scope.products = data;
console.log(data);
}, function(error) {
console.log(data);
});
}]);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body ng-app="myApp">
<div ng-controller="ProductCtrl">
<ul>
<li ng-repeat="x in products">
{{x.prodName}}
</li>
</ul>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js"></script>
<script src="controller.js"></script>
</html>
Error
ReferenceError: data is not defined
at http://localhost:2345/ver1/controller.js:10:35
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js:134:167
at m.$eval (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js:148:47)
at m.$digest (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js:145:92)
at m.$apply (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js:148:341)
at l (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js:101:89)
at XMLHttpRequest.t.onload (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js:106:489) Possibly unhandled rejection: {}
(anonymous) # angular.min.js:122
use success.data instead of data
$http({
method: 'GET',
url: 'products.php'
}).then(function(success) {
$scope.products = success.data;
console.log(success.data);
}, function(error) {
console.log(error.data);
});
Related
I'm trying to UPDATE my php page every 5 seconds so the new data can come in into a .json file, so basically what it does, is, it gets the data from the database, and creates a .json file with this data, I need this php file to update every 5 seconds, so the .json file is updating too.
The code (JsonfileAPI.php):
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "nps";
$dBUsername = "nps";
$dBPassword = "nps";
$dBname = "nps";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword,
$dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "JsonfileAPI.php",
type: 'post',
dataType: 'json',
success: function(response) {
$('.time').html(response);
}
});
}, 5000);
});
</script>
You can use this code in your application, I suggest to use separate files like index.php (for your html code) and action.php for PHP script. and don`t need .json file.
Try this, in index.php html part and javascript part like this
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "action.php",
type: 'post',
// dataType: 'json',
success: function(response) {
console.log(response);
$('.time').html(response);
}
});
}, 5000);
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="time">
</div>
</body>
</html>
Then your action.php file should be like this,
<?php
$localhost = "nps";
$username = "nps";
$password = "nps";
$dbname = "nps";
// db connection
$connect = new mysqli($localhost, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("Connection Failed : " . $connect->connect_error);
} else {
// echo "Successfully connected".$dbname;
}
$sql = "SELECT * FROM dados";
$result = $connect->query($sql);
$output = array('data' => array());
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$output['data'][] = array(
$row[0],
$row[1],
$row[2]
);
}
}
$connect->close();
echo json_encode($output);
I have checked and it work fine. Think it will be help.
I have PHP program to pull data from a MS SQL Server and encode the result in JSON
Here is the code below ->
<?php
/*
connect to MS SQL Server using PHP
*/
$serverName = "192.168.0.4,14333"; // ip:port
$connectionInfo = array( "Database"=>"YYY", "UID"=>"XX", "PWD"=>'XX');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br /><pre>";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "
SELECT * FROM projections_sample
";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
$rows1 = array();
$rows1['name'] = 'Revenue';
while ($r1 = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC))
{
$rows1['data'][] = $r1['revenue'];
}
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
$rows2 = array();
$rows2['name'] = 'Overhead';
while ($r2 = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC))
{
$rows2['data'][] = $r2['overhead'];
}
sqlsrv_free_stmt($getResults);
$result = array();
array_push($result,$rows1);
array_push($result,$rows2);
echo json_encode($result, JSON_NUMERIC_CHECK);
sqlsrv_close($conn);
?>
The results seem to be okay(I pasted the results into a JSON file (data.JSON) and pulled the results into highcharts)
The JSON results are not being pulled when the following code is used -
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Dynamic Chart</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="container" style="min-width: 155px; height: 500px; margin: 0 auto"></div>
<script>
let titleText = ' Revenue Vs Overhead'
let categoryLabels = ['Jan','Feb','Mar','Apr','May',Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
let yAxisText = 'Delta';
$(document).ready(function(){
$.ajax({
datatype: "json",
url: "data.php",
success: function(result)
{
Highcharts.chart('container', {
chart: {
type: 'line'
},
credits: {
enabled: false
},
title: {
text: titleText
},
xAxis: {
categories: categoryLabels
},
yAxis: {
min: 0,
title: {
text: yAxisText
}
},
series: result
});
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); //End Ajax Call
});
</script>
</body>
</html>
When I run the code I get a blank web page.
I'm using the IIS localhost for my PHP. The default path is C:\inetpub\wwwroot. I'm using an AJAX request which is in the same folder but I want to pass the data over to a different html file which has a path for instance C:\newfolder. Can it be done ?
<?php
include "connect.php";
$sql = "SELECT FirstName FROM customers where ID=1";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while($row = sqlsrv_fetch_array($stmt)){
//echo $row['FirstName']."<br />";
echo json_encode(array('name'=>$row),JSON_FORCE_OBJECT);
}
sqlsrv_free_stmt( $stmt);
?>
<html>
<head>
<script>
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'test.php', true);
xmlhttp.onload = function(){
if(this.status == 200){
let data = this.responseText;
let jsondata = JSON.parse(data);
retrieve(jsondata.name.FirstName);
}
}
xmlhttp.send();
function retrieve(parser){
console.log("funct",parser);
}
</script>
</head>
<body>
</body>
</html>
I am having an issue where i get a timeout if i run a certain php script with parameters sent from a Jquery Ajax reequest. However if i simply run this script with no parameters I.E just run it on its own its fine.
The php file the Ajax request is in is noteContent.php
noteContent.php:
<script type="text/javascript">
// Submit generalNote to the database
function submitNoteText()
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var notetext = $("#ta1").val();
var dataString = 'noteid1=' + noteid + '¬etext1=' + notetext;
if(noteid == ''||notetext == '')
{
alert("NoteID or Text is blank");
}
else
{
$.ajax({
type: "POST",
url: "submitNoteText.php",
dataType: 'json',
data: dataString,
cache: false,
success: function(result){
alert("Success");
}
});
}
return false;
};
</script>
The script its trying to run
submitNoteText.php:
<?php include 'connectionDetails.php'; ?>
<?php
if (isset($_POST['noteid1'], $_POST['notetext1']))
{
var_dump($_POST['notetext1']);
$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];
$stmt = "UPDATE Notes SET Note = '?' WHERE NoteID = ?";
$params = array($noteid2, $notetext2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
they are all connected with an include to
connectionDetails.php(which has never returned an error before):
<?php
$myServer = "Test";
$connectionInfo = array('Database' => 'Test', 'UID' => 'Test', 'PWD' => 'test');
//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
or die("Couldn't connect to SQL Server on $myServer");
//Test connection to server
// if ($conn)
// {
// echo "connection successful"; # code...
// }
?>
<?php
//Defining my queries
$getNotes = "SELECT NoteID, NoteName, Note FROM Notes ORDER BY NoteName ASC";
$getTemplateNotes = "SELECT TemplateNoteID, TemplateNoteName, TemplateNote FROM TemplateNotes ORDER BY TemplateNoteName ASC";
$getReplaceVariables = "SELECT ReplaceVariableID, ReplaceVariableName, ReplaceVariableNote FROM ReplaceVariables ORDER BY ReplaceVariableName ASC";
$resultNotes = sqlsrv_query($conn, $getNotes);
$resultTemplate = sqlsrv_query($conn, $getTemplateNotes);
$resultVariables = sqlsrv_query($conn, $getReplaceVariables);
if( $resultNotes === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultTemplate === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultVariables === false)
{
die( print_r( sqlsrv_errors(), true) );
}
?>
When i click the button to run the request i get this:
All the text to be submitted is in the params:
Ajax data parameter should be an array :
$.ajax({
type: 'POST',
url: "your urls",
data: {
id: youridval,
anothervar: anothervalvalue
},
beforeSend: function() {
},
complete: function() {
},
success: function(_result) {
}
});
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');