How to display data using AngularJS with php - 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>

Related

Calling php page with ajax is not working

I'm having problem with calling php page with ajax. When I click the button, the chart.php is not displayed. Both of the buttons don't work. The target php files are the same with different data only, so I included only one of the chart.php pages. How can I fix this? please. Thanks for your help!
Index.php code:
<!DOCTYPE html>
<html>
<head>
<title>Charts</title>
<link rel="stylesheet" type="text/css" href="etc/main.css" />
<script type="text/javascript" src="etc/jquery-2.1.4.js"></script>
</head>
<body>
<div id="wrapper">
<div id="header">
<button id='actbutton1'> Chart1</button>
<button id='actbutton2'> Chart2</button>
</div>
<div id="contentliquid">
<div id="content">
<div id="querydiv">
</div>
</div>
</div>
<div id="leftcolumn">
</div>
</div>
<script>
document.getElementById('actbutton1').onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "chart1.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("querydiv").innerHTML = xhr.responseText;
}
}
xhr.send();
}
document.getElementById('actbutton2').onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "chart2.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("querydiv").innerHTML = xhr.responseText;
}
}
xhr.send();
}
</script>
</body>
</html>
The page I call with ajax, chart1.php, is this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
}
$query = "SELECT Week, Omean FROM charts";
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Chart1</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Week','Omean'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Week"]."', ".$row["Omean"]."],";
}
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var options = {
title: 'Chart1',
'width':1700,
'height':600,
hAxis : {textStyle : {fontSize: 8}},
'tooltip' : { trigger: 'none'},
enableInteractivity: false,
legend: { position: 'bottom' }
};
var chart = new
google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
chart.draw(view, options); // <-- use data view
}
</script>
</head>
<body>
<div id="curvechart" style="width: 900px; height: 400px"></div>
</body>
</html>

JSON data with AngularJS from PHP connecting to SQL

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.

Changing the content of jquery mobile

I am developing mobile app using jquery mobile framework and I would like to change page content using javascript and ajax but I don't get the expected result.Could you help me please.
Here is the code :
connection.php
<?php
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$db="mobileapp";
$conn=mysql_connect($dbhost,$dbuser,$dbpass) or die("Could not connect");
mysql_select_db($db);
?>
index1.php
<?php
include 'connection.php';
$fetch="SELECT * from users";
/**
$result=mysql_query($query) or die(mysql_error());
//while($person=mysql_fetch_array($result)){
$person=mysql_fetch_array($result)
echo json_encode($person);**/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['username'] = $row['username'];
$row_array['city'] = $row['city'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
//}
?>
index.html
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"> </script>
<script type="text/javascript" src="global.js">
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Railway Station</h1>
</div><!-- /header -->
<div data-role="content">
<input type="button" value="Refresh" id="submit" data-icon="refresh" /></br>
<ul data-role="listview" id="list"> </ul>
<script id="source" language="javascript" type="text/javascript">
$(document).live('pageinit',function (event) {
$.ajax({
url: 'index1.php',
data:"",
dataType: 'json',
success: function(rows)
{
for(var i=0;i<rows.length;i++)
{
var row = rows[i];
var id = row[0];
var name= row[1];
var city= row[2];
$('#list').append("<li>id:"+id+"Name:"+name+"City:"+city+"</li>");
}
};
});
});
</script>
</div>
</div>
<div data-role="footer">
<h1>©AmeyPat.All Rights Reserved.</h1>
</div><!-- /footer -->
</body>
</html>

try to send ajax post request to php to db but got an error

I better show everything because I've no idea where it went wrong.. I'm very sure my database / tables are correctly connected.. but it still return error..
html
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="UTF-8">
<title>Ajax Example</title>
</head>
<body>
<ul>
<li class='item'>item 1</li>
</ul>
<a href="#" id='btn'>Add</a>
<br /><input type='text' id='input'>
</body>
</html>
js
$(document).ready(function(){
$('#input').hide();
$('#btn').click(function () {
$(this).hide();
$('#input').show().focus().val('');
});
$('#input').blur(function () {
var userInput = $('#input').val().trim();
if (userInput !== "") {
var text = $(this).val().charAt(0).toUpperCase() + $(this).val().substring(1); // to uppercase first letter
$('#btn').show();
$('#input').hide();
$.ajax({
type: "POST",
url: "send.php",
data: { item : text }
})
.done(function( data ) {
if(data == 1)
alert('data inserted');
else
alert('error');
});
appendTab = "<li class='item'>" + text + "</li>"
$('ul').append(appendTab);
}
else {
$('#btn').show();
$('#input').hide();
}
});
});
php
<?php
$data = mysqli_real_escape_string($_POST['item']);
$conn = mysqli_connect("localhost","root","");
mysqli_select_db($conn, "ajaxExample");
$q = "INSERT INTO user (userList) VALUES ('$data')";
if(mysqli_query($conn, $q)){
echo 1;
}
?>
I use wamp and hv a mysql database, I think I can still use mysqli?
In your php you cannot use mysqli_real_escape_string function before a valid mysql connection
What you need to do just put mysqli_real_escape_string after mysqli_connect function
and this is probably your error
<?php
$conn = mysqli_connect("localhost","root","");
$data = mysqli_real_escape_string($_POST['item']);
mysqli_select_db($conn, "ajaxExample");
$q = "INSERT INTO user (userList) VALUES ('$data')";
if(mysqli_query($conn, $q)){
echo 1;
}
?>

Empty value when going from PHP => JSON => JS

I have created a PHP connection to my database and made the following query:
$taxRates = array();
while($row = mysql_fetch_assoc($result)) {
$taxRates[] = $row['mar_tax_rate'];
}
I then encoded the result as follows:
$jsonobj = json_encode($taxRates, JSON_NUMERIC_CHECK);
echo "This is jsonobj:<br>" . $jsonobj . "<br>";
Which returns:
This is jsonobj:
[0,0.35,0.35,0.35,0.35,0.35,0.35,0.35,0.35]
The problem that I am having is this. When I try to echo these results into JS, my result is coming back empty (as far as I can see) -- not an empty array, just nothing. This is how I am trying to feed the result into JS:
data:[<?php echo $jsonobj; ?>]
Which returns:
data:
I have tried to alert the PHP variable using
alert("<?php echo $jsonobj; ?>");
which produces an alert, but is also empty.
Any thoughts?
Here is the full code:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="includes/js/highcharts.2.3.2.js"></script>
<script type="text/javascript" src="includes/js/highstock.src.js"></script>
<script type="text/javascript">
$(document).ready(function() {
drawChart();
});
function drawChart() {
alert("<?php echo join($jsonobj); ?>");
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
type: 'column',
},
credits: {
enabled: false
},
series: [{
data:[<?php echo $jsonobj; ?>]
}]
});
};
</script>
</head>
<body>
<button style="height:100px; width:300px;" onclick="drawChart();">Redraw the Chart</button><br />
<div id="chart"></div>
<?php
$link = mysql_connect('url', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//mysql_close($link);
$db_selected = mysql_select_db('bloch',$link);
if (!$db_selected) {
die ('Can\'t use Bloch Database : ' . mysql_error());
}
$result = mysql_query('SELECT mar_tax_rate from bloch.bloch_deficit');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$taxRates = array();
while($row = mysql_fetch_assoc($result)) {
$taxRates[] = $row['mar_tax_rate'];
}
$jsonobj = json_encode($taxRates, JSON_NUMERIC_CHECK);
echo "This is jsonobj:<br>" . $jsonobj . "<br>";
?>
</body>
</html>
Your variable isn't being defined before you try and put it in to your HTML. Create the variable with what you need before your HTML in order to get it to the page correctly.

Categories