JSON data with AngularJS from PHP connecting to SQL - php

connect.php
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=Northwind";
$credentials = "user=postgres password=qwer1234";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from customers;
EOF;
$ret = pg_query($db, $sql);
if(!$ret){
echo pg_last_error($db);
exit;
}
$rows = array();
while($r = pg_fetch_assoc($ret)){
$rows[] = $r;
echo json_encode($rows);
}
?>
JSON
[{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209","Country":"Germany","Phone":"030-0074321","Fax":"030-0076545"}][{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209"...........
AngularJs.html
<html ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-controller="customersCtrl">
<div>
<table class="table table-striped">
<thead>
<tr>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in customers">
<td>{{item.CustomerID}}</td>
<td>{{item.CompanyName}}</td>
<td>{{item.ContactName}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</html>
<script>
var app = angular.module("myApp", []);
app.controller('customersCtrl', ['$scope', '$http', function($scope,$http) {
console.log("Initiating the controller");
$http.get('http://localhost:8080/connect.php').success(function(data) {
$scope.customers = data;
});
}]);
</script>
The result of this is that nothing shows up on angularjs.html Help Me! Thanx.

Initiating the controller
XMLHttpRequest cannot load http://localhost:8080/connect.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Related

Everything in mysql is printing to only one cell in html table

When I print the data from mysql, everything is going into one cell in the first row instead of being spread out through the whole html table.
I've included below all of the code I've written, but the problem is in the get_input.js and get_input.php files at the bottom of this page.
How can I fix this?
vocab_input.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="vocab_input.js"></script>
<script type="text/javascript" src="get_input.js"></script>
<style>
th {
text-align: center;
}
td {
text-align: center;
}
form {
margin-top: 50px;
}
</style>
</head>
<body>
<!-- INPUT -->
<div class="container">
<h1></h1>
<form action="vocab_input.php" method="post" id="input_form">
<label>Word:</label>
<input type="text" name='word'>
<label>POS:</label>
<input type="text" name='pos'>
<label>Translation:</label>
<input type="text" name='trans'>
<label>Definition:</label>
<input type="text" name='definition'>
<label>Sentence:</label>
<input type="text" name='sen'>
<input type="submit">
</form>
</div>
<!-- BUTTONS -->
<div class="btn-group btn-group-justified" role="group" aria-label="..." style="margin-top: 50px;">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" id="list">Vocab List</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Matching</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Scrambled</button>
</div>
</div>
<!-- OUTPUT -->
<table class="table">
<tr>
<th>Word</th>
<th>Part of Speech</th>
<th>Translation</th>
<th>Definition</th>
<th>Sentence</th>
</tr>
<tr>
<td id="mytable"></td>
</tr>
</table>
</body>
</html>
vocab_input.js
$(function() {
$('#input_form').on('submit', function(e) {
var data = $("#input_form :input").serialize();
$.ajax({
type: "POST",
url: "vocab_input.php",
data: data,
});
e.preventDefault();
});
});
vocab_input.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "vocab";
$word = $_POST['word'];
$pos = $_POST['pos'];
$trans = $_POST['trans'];
$definition = $_POST['definition'];
$sen = $_POST['sen'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data
$sql = "INSERT INTO user_input (word, pos, trans, definition, sen)
VALUES ('$word', '$pos', '$trans', '$definition', '$sen')";
$conn->query($sql);
$conn->close();
?>
Here is where the problem is:
get_input.js
$(document).ready(function(){
$("#list").click(function(){
$.ajax({
type: 'GET',
url: 'get_input.php',
success: function(data) {
$("#mytable").text(data);
}
})
})
})
get_input.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "vocab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM user_input";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
foreach($row as $field) {
echo htmlspecialchars($field);
}
}
$conn->close();
?>
Change html to :
<table class="table">
<tr>
<th>Word</th>
<th>Part of Speech</th>
<th>Translation</th>
<th>Definition</th>
<th>Sentence</th>
</tr>
<tr id="mytable">
</tr>
</table>
And PHP :
while ($row = mysqli_fetch_assoc($result)) {
echo '<td>'.htmlspecialchars($row[0]).'</td>';
echo '<td>'.htmlspecialchars($row[1]).'</td>';
echo '<td>'.htmlspecialchars($row[2]).'</td>';
echo '<td>'.htmlspecialchars($row[3]).'</td>';
}

AngularJS + PHP + MySQL to display data from database

Can somebody tell me what am I missing here for the code to display data from my database? Much appreciated!
HTML
<!DOCTYPE html>
<html lang="en" ng-app="VinylApp">
<head>
<meta charset="utf-8">
<title>Vinyl Record Store</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="script.js"></script><script src="app.js"></script>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div ng-app="VinyApp" ng-controller="VinylListController">
<table>
<tr ng-repeat="vinyl in vinyls">
<td>{{vinyl.Vinyl_ID}}</td>
<td>{{vinyl.VinylName}}</td>
<td>{{vinyl.Artist}}</td>
<td>{{vinyl.Price}}</td>
</tr>
</table>
</div>
</body>
</html>
JS
var app= angular.module('VinylApp', []);
app.controller('VinylListController', function($scope, $http){
$http.get("db_con.php")
.then(function(response){
$scope.vinyls = response.data.records;
});
});
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type:application/json; charset=UTF-8");
$conn = new mysqli("myServer","myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT * FROM vinyl");
$outp= "";
while($rs=$result->fetch_array(MYSQLI_ASSOC)){
if ($outp != "") {$outp .= ",";}
$outp .= '{"VinylID":"' . $rs["VinylID"] . '",';
$outp .= '"VinylName":"' . $rs["VinylName"] . '",';
$outp .= '"Artist":"'. $rs["Artist"] . '",';
$outp .= '"Price":"'. $rs["Price"] . '"}'; } $outp ='{"records":['.$outp.']}'; $conn->close();
echo($outp);
}
?>
i have solve issue. Please try this code is working g fine for me. here add new angular.min.js and some changes added
var app= angular.module('VinylApp', []);
app.controller('VinylListController', function($scope, $http){
$http.get("db_con.php")
.then(function(response){
$scope.vinyls = response.data;
});
});
<!DOCTYPE html>
<html lang="en" ng-app="VinylApp">
<head>
<meta charset="utf-8">
<title>Vinyl Record Store</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script>
<script src="app.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="VinyApp">
<div ng-controller="VinylListController">
<table>
<tr ng-repeat="vinyl in vinyls">
<td>{{vinyl.Vinyl_ID}}</td>
<td>{{vinyl.VinylName}}</td>
<td>{{vinyl.Artist}}</td>
<td>{{vinyl.Price}}</td>
</tr>
</table>
</div>
</body>
</html>
<?php
$conn = new mysqli("localhost","root", "", "pinakin_northwind");
$result = $conn->query("SELECT * FROM vinyl");
$outp = array();
while( $rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $rs;
}
echo json_encode($outp);
?>

why is ajax duplicating the whole page in php

I am connected to mysql database and I want to generate table with content from mysql with php after clicking on a button by a user.
But after clicking on a button, the whole page with header, body, etc. is generated to div where are table and php script. The button also duplicate visually of course.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2">
<meta http-equiv="content-language" content="cs">
<meta name="author" content="Marek Ciz, Tomas Veskrna">
<meta name="keywords" content="galerie, iis, iis projekt 2016, informacni system">
<link rel="icon" type="image/png" href="./icons/gallery.png" />
<title>Employee</title>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#expo-but").click(function(){
$.ajax({
url: "./employee.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
</script>
</head>
<body>
<div class="page">
<div class="menu">
<button id="expo-but">Exposition</button>
</div>
<div id="table-wrapper">
<div id="table">
<table class="striped">
<thead>
<tr class="header">
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
More correct solution will be separate html and php part:-
Your html should be like this:-
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2">
<meta http-equiv="content-language" content="cs">
<meta name="author" content="Marek Ciz, Tomas Veskrna">
<meta name="keywords" content="galerie, iis, iis projekt 2016, informacni system">
<link rel="icon" type="image/png" href="./icons/gallery.png" />
<title>Employee</title>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(#expo-but).trigger("click"); // on document ready trigger click itself so that table will load initially
$("#expo-but").click(function(){
$.ajax({
url: "./employee.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
</script>
</head>
<body>
<div class="page">
<div class="menu">
<button id="expo-but">Exposition</button>
</div>
<div id="table-wrapper">
<div id="table">
</div>
</div>
</div>
</body>
</html>
And php(employee.php) will be like this:-
<?php
include './db_init.php';
//echo $_SESSION["user"];
$data = '';
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$data .= "<tr>";
$data .="<td>".$row[id_zamestnance]."</td>";
$data .="<td>".$row[jmeno]."</td>";
}
}
}
$final_data = '<table class="striped"><thead><tr class="header"><td>Id</td><td>Name</td></tr></thead><tbody>'.$data.'</tbody></table>';
echo $final_data;
?>
Note:-
Why i am saying more correct because in your php page you also have same code what you written in your current html div, so no need to do the repetition.
Just on document load call the click function of button ,that's it.
cut this code and add this code to top of the page
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
exit();
}
?>
this is a normal mistake most of us do, I suggest you to request to another php page instead requesting the same page.
table.php
<table class="striped">
<thead>
<tr class="header">
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
}
?>
</tbody>
</table>
and change the url in the scrtipt
<script>
$(document).ready(function(){
$("#expo-but").click(function(){
$.ajax({
url: "./table.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});

How to display data using AngularJS with php

I want to connect my index.php page with ngconnect.php and want to display my table record.
This is my index.php page below.................
<html>
<head>
<title>first ng app recieve data from database</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
<script>
$(function(){
var app = angular.module('myapp',[]);
app.controller('myctrl',function($scope,$http){
$http({method:'GET', url:'ngconnect.php'}).success(function(response){
$scope.names = response;
});
});
});
</script>
</body>
</html>
This is my ngconnect.php page below.............
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysql_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
} else {
$db_selected = mysql_select_db('dsc');
if (!$db_selected) {
die ('Can\'t use dsc : ' . mysql_error());
} else {
$result = mysql_query('SELECT * from user');
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
echo json_encode($data);
}
}
}
mysql_close($conn);
?>
Why my data is not being display?
ngconnect.php does display the following.....
[{"0":"1","user_id":"1","1":"Amit","first_name":"Amit","2":"","middle_name":"","3":"Kushwaha","last_name":"Kushwaha","4":"akushwaha.softvisionindia#gmail.com","email":"akushwaha.softvisionindia#gmail.com","5":"2","rate_dsc_2":"2","6":"3","rate_dsc_3":"3","7":"4","rate_token":"4","8":"e10adc3949ba59abbe56e057f20f883e","password":"e10adc3949ba59abbe56e057f20f883e","9":"Enabled","status":"Enabled","10":"8858234949","phone":"8858234949","11":"NULL","forget_link":"NULL","12":"00:00:00","forget_time":"00:00:00"},{"0":"2","user_id":"2","1":"Sandeep","first_name":"Sandeep","2":"","middle_name":"","3":"Tripathi","last_name":"Tripathi","4":"sandeep.softvisionindia#gmail.com","email":"sandeep.softvisionindia#gmail.com","5":"10","rate_dsc_2":"10","6":"20","rate_dsc_3":"20","7":"30","rate_token":"30","8":"e10adc3949ba59abbe56e057f20f883e","password":"e10adc3949ba59abbe56e057f20f883e","9":"Enabled","status":"Enabled","10":"9936882864","phone":"9936882864","11":"","forget_link":"","12":"00:00:00","forget_time":"00:00:00"}]
Try these codes..Hope it will help You..
I assume that your responce is in json format (array of object) as you posted your responce of php file..
<html>
<head>
<title>first ng app recieve data from database</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
<script>
var myapp = angular.module('myapp', []);
myapp.controller('myctrl', function ($scope, $http) {
$http.get('ngconnect.php').success(function(data) {
$scope.names = data;
});
});
</script>
</body>
</html>

Can not bind data on view using angular.js and PHP

i need to display data on the page using Angular.js. First i fetched all data from DB using PHP .Here no data is displaying on the page.I am getting the below retrieved data in my browser console.
all data [{"0":"1","id":"1","1":"","name":"","2":"","pass":"","3":"","email":""},{"0":"2","id":"2","1":"subhra","name":"subhra","2":"12345","pass":"12345","3":"subh#gmail.com","email":"subh#gmail.com"},{"0":"3","id":"3","1":"rakesh","name":"rakesh","2":"0901209474","pass":"0901209474","3":"maini","email":"maini"},{"0":"4","id":"4","1":"raj","name":"raj","2":"23457","pass":"23457","3":"rai","email":"rai"},{"0":"5","id":"5","1":"Rahul","name":"Rahul","2":"098765","pass":"098765","3":"shinha","email":"shinha"}]
I am explaining my code below.
read.js:
var app=angular.module('Read_data',[]);
app.controller('readController',function($scope){
$.ajax({
type:'GET',
url:"php/read.php",
success: function(data){
$scope.data=data;
console.log('all data',$scope.data);
}
})
});
read.php:
<?php
//database settings
$connect = mysqli_connect("localhost", "root", "*******", "AngularTest");
$result = mysqli_query($connect, "select * from users");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
print json_encode($data);
?>
index.html:
<!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" ng-app="Read_data">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo of Angular.js</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/angularjs.js" type="text/javascript"></script>
<script src="js/read.js" type="text/javascript"></script>
</head>
<body>
<center ng-controller="readController">
<div id="body">
<div id="content">
<table align="center">
<tr>
<th colspan="5">add data here.</th>
</tr>
<th> Name</th>
<th> Email</th>
<th> Password</th>
<th colspan="2">Operations</th>
</tr>
<tr ng-repeat="users in data">
<td>{{users.name}}</td>
<td>{{users.email}}</td>
<td>{{users.pass}}</td>
<td align="center"><img src="images/pencil_small.png" align="EDIT" /></td>
<td align="center"><img src="images/cross-small-icon.png" align="DELETE" /></td>
</tr>
</table>
</div>
</div>
</center>
</body>
</html>
Please help me to resolve this issue and bind all data in table successfully.
Angular is not aware of updated data. Use $scope.$apply if you are not using $http for AJAX.
var app=angular.module('Read_data',[]);
app.controller('readController',function($scope){
$.ajax({
type:'GET',
url:"php/read.php",
success: function(data){
$scope.$apply(function(){
$scope.data = angular.fromJson(data);
});
console.log('all data',$scope.data);
}
})
});
or use $http (recommended)
var app=angular.module('Read_data',[]);
app.controller('readController',function($scope, $http){
$http.get('php/read.php').
then(function(data) {
// this callback will be called asynchronously
// when the response is available
$scope.data = data.data;
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});

Categories