Can not bind data on view using angular.js and PHP - 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.
});
});

Related

Table not sorting through PHP but sorting inside HTML

I have html table create by a php, I want to sort this table, but no success.
If I create the table inside the html the sort work.
<!DOCTYPE html>
<html>
<head>
<title>Teste</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<div class="container mb-3 mt-3" id="inicio">
</div>
<script>
$(document).ready(function(){
load_list();
$('.mydatatable').DataTable();
function load_list()
{
var action = "data";
$.ajax({
url: "teste.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#inicio').html(data);
}
})
}
});
</script>
</body>
</html>
Example of table from php:
<?php
if(isset($_POST["action"]))
{
if($_POST["action"]=="data")
{
$output = '
<table class="table table-striped table-bordered mydatatable" style="width: 100%">
<thead>
<tr>
<th>Tittle</th>
</tr>
</thead>
<tbody>
<tr>
<td>data</td>
</tr>
<tr>
<td>date2</td>
</tr>
</tbody>
</table>
';
echo $output;
}
?>
I think the $('.mydatatable').DataTable(); is in the wrong place, I tried my options but only work if the table is inside the html page. Anyone can help me?
As first A in ajax means asynchronous, then your call to $('.mydatatable').DataTable(); happens before real data is loaded via ajax. You should move call to DataTable to success callback:
success:function(data)
{
// note the order - first you load `html`
$('#inicio').html(data);
// after that you have a `.mydatatable` selector available
$('.mydatatable').DataTable();
}
Table html is not there when you initialize your Datatable.
$(document).ready(function(){
load_list();
function load_list()
{
var action = "data";
$.ajax({
url: "teste.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#inicio').html(data);
//move this to here
$('.mydatatable').DataTable();
}
})
}

AngularJS HTTP Request with another function

I have a simple app that reads data from a JSON file and displays it in a webpage. That part works fine (the displaying). I now want to be able to sort through the table by toggling on the table headers using the orderBy filter in AngularJS ... however, that's where I have issues.
What may I be overlooking? I feel like it has to do with the HTTP Function ... could that be messing with it? I don't know why that may be an issue though?
Please find my code attached.
leads.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app = "myApp" ng-controller = "myCtrl">
<textarea name="name" ng-model = "test"></textarea>
<h1>{{ count }}</h1>
<table class="table">
<thead>
<tr>
<th ng-click = "sortBy('first_name')">First Name</th>
<th ng-click = "sortBy('last_name')">Last Name</th>
<th ng-click = "sortBy('email')">Email Address</th>
<th ng-click = "sortBy('accountCreation')">Account Creation</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "user in myData | orderBy : orderByThis">
<td> {{user.first_name}} </td>
<td> {{user.last_name}} </td>
<td> {{user.email}} </td>
<td> {{user.accountCreation}}</td>
</tr>
</tbody>
</table>
</div>
<script src="./leadsController.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
</body>
</html>
leadsController.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("leadsData.php").then(function (response) {
$scope.myData = response.data.records;
});
$scope.sortBy = function(x){
$scope.orderByThis = x;
};
});
You can do this inside the controller itself
$scope.sortBy = function(x){
$scope.myData = $filter('orderBy')($scope.myData, x);
}
and make sure to inject $filter

How to read content from td with simple html dom

This is my code:
<tr>
<td class="text">
<div>Something</div>
</td>
<td>Something2</td>
<td>Something3</td>
</tr>
I want to get content from td and return in single line like this
Something - Something2
For HTML DOM manipulation there is a library called jQuery you can easily Travers the HTML dome with that.
and Bellow is the solution of your problem.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table id="tblNewAttendees">
<tr>
<td class="text"><div>Something</div</td>
<td>Something2</td>
<td>Something3</td>
</tr>
</table>
<div class="table-content"></div>
<script>
$(document).ready(function(){
var content ='';
$('#tblNewAttendees tr').each(function() {
$.each(this.cells, function(){
//alert($(this).text());
content+=$(this).text()+" - ";
});
});
$(".table-content").html(content);
});
</script>
</body>
</html>

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

Initialize dataTable from separate .php table

I am trying to initialize a dataTable from a separate .php file that builds a table. It builds the table okay, but the dataTable properties do not seem to be in effect.
Here is my code:
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#live_table').load("table.php");
var refreshId = setInterval(function() {
$('#live_table').load("table.php");
}, 2000);
$.ajaxSetup({ cache: false });
$('#data').dataTable();
});
</script>
<title></title>
</head>
<body>
<div id="live_table">
</div>
</body>
</html>
table.php
<table id="data">
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
index.php is meant to refresh the table every 2000ms and table.php is actually more complex in my real situation and requires conditional cell backgrounds and links which is why I didn't choose to use the server side processing (JSON) for table data.
Any idea why the $('#data').dataTable(); command isn't working?
I think it is not loading because you are using a selector that does not exist yet.
Try:
$(document).ready(function() {
$('#live_table').load("table.php");
var refreshId = setInterval(function() {
$('#live_table').load("table.php");
}, 2000);
$.ajaxSetup({ cache: false });
$('#data').dataTable(); //This line should be in table.php
Technically there is no element #data in the DOM. You should put the table initialization in the table.php file.
It looks like the problem is the call to .dataTable() is occurring before the table is actually loaded, since .load call happens asynchronously and the rest of the code keeps running. You need to call .dataTable() after the request has finished by using the third parameter to .load:
$('#live_table').load(
"table.php",
{},
function() { $('#data').dataTable(); }
);
Demo: http://jsfiddle.net/sAnUL/1/
you can use callback function of load() method:
$('#live_table').load("table.php", function(){
$('#data').dataTable();
});
or use ajaxSuccess():
Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.
$('#data').ajaxSuccess(function(){
$(this).dataTable()
})

Categories