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

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.

Related

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>

how to merge all the cells of an excel file in an array and how to make autocomplete search box works

I have two problems:
1)
I am using PHPExcel for retrieving data from cells, I have simple code two print it out.
<?php
set_include_path(implode(PATH_SEPARATOR, [
realpath(__DIR__ . '/Classes'), // assuming Classes is in the same directory as this script
get_include_path()
]));
require_once dirname(__FILE__) . '/Classes/PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$file= "./uploads/".$_GET["filename"];
//if you want to try it you can use this and comment line on the above
// $inputFileName = './sampleData/yourexcelname.xls';
$inputFileName = ($file);
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
var_dump($rowData); // Insert row data array into your database of choice here
echo "-----------------as json encode---------------";
var_dump(json_encode($rowData));
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags =<?php echo json_encode($rowData); ?>;
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
however what I want to do is....
instead of this ....
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
i tried to use this:
$total = $sheet->mergeCells('A' . $row . ':' . $highestColumn . $row, NULL,
TRUE,
FALSE);
echo "-----------------as Total---------------";
var_dump($total);
however, it just echos every detail related with document security and property cache info etc. etc. everything but what I want. how can I merge data in cells?
2) I try to turn the php array into js array so that I can put my array into autocomplete search box (autocomplete jquery )
as I used here:
$(function() {
var availableTags = $.parseJSON('<?php echo json_encode($rowData); ?>');
$( "#tags" ).autocomplete({
source: availableTags
});
});
however, my suggested options are not appearing when I put this json_encode convertion.
question: how can I make this converted array echo my data?
Useful handy helps will be appreciated.
as #MarkBaker suggested I found a solution which works pretty fine:
$kova=array();
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
echo "-----------------as rowData---------------";
var_dump($rowData); // Insert row data array into your database of choice here
echo "-----------------returning into single array---------------";
array_push($kova,$rowData);
var_dump($kova);
$myFlatArray = PHPExcel_Calculation_Functions::flattenArray($kova);
echo "<br>";
echo "----------------- converting into json encode---------------";
var_dump(json_encode($myFlatArray));
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = $.parseJSON('<?php echo json_encode($myFlatArray); ?>');
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<br>
<br>
<br>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
<br>
<br>
<br>
<br>
</div>

passing array to flot

I have been trying to make a graph plot with flot, and have ran into a problem.I Think the problem is with the way m using the php variable with flot Aside from that the graph isn't showing so I must have done something wrong. Below is the graph code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="./flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.categories.js"></script>
</head>
<body>
<?php
//CONNECTING TO THE SERVER
$servername = "XXX";
$username = "YYY";
$password = "ZZZ";
conn = new mysqli($servername, $username, $password);
$sql = "SELECT NAME, AGE FROM pro_db";
$result = $conn->query($sql);
$wt=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//storing the values in the array
$wt[]=$row;//is this the right way
}
} else {
echo "0 results";
}
?>
<div id="placeholder" style="width:600px;height:300px;"></div>
<script type="text/javascript">
$(function () {
//accessing the array
var data = <?php echo $wt; ?>;
$.plot($("#placeholder"), [data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center" }
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
});
</script>
</body>
</html>``
Here's completely working example i made. If something doesn't work - there's some error with data. Try var_dump how your $wt array looks like in the end;
$data = [
['Andrew', 31],
['Helen', 29],
['Dasha', 24],
['Denis', 23]
];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="canvas" style="width: 600px; height: 400px;"></div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/flot/jquery.flot.js"></script>
<script src="bower_components/flot/jquery.flot.categories.js"></script>
<script>
var data = <?php echo json_encode($data) ?>;
$("#canvas").plot([data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
</script>
</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;
}
?>

.append() with Database

I'm trying to retrieve information from my database, and output it to my page. I'm able to hardcore it, so to show exactly what I want to be able to do is located here:
I'm not having any console errors in the javascript, but I am unable to append data to the list once it is clicked.
HTML & JS:
<!doctype html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="../img/sd.ico" />
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="body">
<div id="header"><h1>Bookmarks</h1></div><!-- header -->
<iframe id="iFrame" name="iFrame"></iframe>
<div id="links"><ul id="accordion">
<li><div class="bookmarkTitle"><p><h4>CareerResources</h4></p></div></li><ul id="CareerResources">
</ul><li><div class="bookmarkTitle"><p><h4>CSS</h4></p></div></li><ul id="CSS">
</ul><li><div class="bookmarkTitle"><p><h4>JS</h4></p></div></li><ul id="JS">
</ul><li><div class="bookmarkTitle"><p><h4>JS: Jquery</h4></p></div></li><ul id="JS: jQuery">
</ul></div><!-- links end -->
</div><!-- body end -->
<script type="text/javascript">
$(document).ready(function(){
$("#accordion > li").click(function(e){
var catName=$(e.target).text();
$.getJSON("get.php?catName=" + catName, function(data){
if (data.data){
$.each(data.data,function(index,value){
var url = value.URL;
var title = value.title;
var desc = value.desc;
alert(catName);
$("#"+catName).append('<div class="bookmark"><p><h3>'+title+'</h3><br />'+desc+'</p></div>');
});
}
});
});
});
</script>
</body>
</html>
PHP:
// retval: 0 - login ok, 1 - login failed, 2 - internal error
$json = array("retval" => 2, "data" => NULL, "debug" => "");
$catName=mysql_real_escape_string($_REQUEST['catName']);
$sql="SELECT * FROM linktb WHERE catName='$catName'";
$json['debug'] .= "SQL query was: ".$sql."\n";
$result=mysql_query($sql);
if (!$result) {
$json['debug'] .= "SQL query failed\n";
$json['debug'] .= "Other output: ". ob_get_contents();
ob_end_clean();
die(json_encode($json));
}
$count=mysql_num_rows($result);
if($count > 0){
$json['retval'] = 0;
$json['data'] = array();
while ($row = mysql_fetch_assoc($result)){
$json['data'][] = $row;
}
} else {
$json['retval'] = 1;
}
$json['debug'] .= "Other output: ". ob_get_contents();
ob_end_clean();
echo json_encode($json);
var catID=e.target.text(); Should be var catID=$(e.target).text(); as .text() is a jQuery method.
If you want to iterate through the returned data you'll have to do it in the success function. Also from your php script you only output one row from your database.
if($count > 0){
$json['retval'] = 0;
$json['data'] = array();
while ($row = mysql_fetch_assoc($result)){
$json['data'][] = $row;
}
}
else {
$json['retval'] = 1;
}
$.getJSON("get.php?catID=" + catID, function(data){
if (data.data){
$.each(data.data,function(index,value){
var url = value.URL;
var title = value.title;
var desc = value.desc;
$("#"+catID).appendText('<div class="bookmark"><p><h3>'+title+'</h3><br />'+desc+'</p></div>');
});
}
});

Categories