Trying to generate a piechart using dropdown menu and api but there is a json error for table showing invalid string.
Pie file
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
// Create connection and select db
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart,table package.
google.load('visualization', '1', {'packages':['corechart','table']});
function drawItems(num) {
var jsonPieChartData = $.ajax({
url: "getpiechartdata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
var jsonTableData = $.ajax({
url: "gettabledata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var piechartdata = new google.visualization.DataTable(jsonPieChartData);
var tabledata = new google.visualization.DataTable(jsonTableData);
// Instantiate and draw our pie chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(piechartdata, {
width: 700,
height: 500,
chartArea: { left:"5%",top:"5%",width:"90%",height:"90%" }
});
// Instantiate and draw our table, passing in some options.
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(tabledata, {showRowNumber: true, alternatingRowStyle: true});
}
</script>
</head>
<body>
<form>
<select name="pt" onchange="drawItems(this.value)">
<option value="">Select a server:</option>
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
// Make a MySQL Connection
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName) or die(mysql_error());
mysqli_select_db($con,"techyari_demos") or die(mysqli_error());
// Create a Query
$sql_query = "SELECT id, servername FROM server ORDER BY servername ASC";
// Execute query
$result = mysqli_query($con,$sql_query) or die(mysqli_error());
while ($row = mysqli_fetch_array($result)){
echo '<option value='. $row['id'] . '>'. $row['servername'] . '</option>';
}
mysqli_close($con);
?>
</select>
</form>
<div id="chart_div"></div>
<div id="table_div"></div>
</body>
</html>
getpiechartdata
<?php
$q=$_GET["q"];
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
$sql_query="SELECT * from entry";
// $sql_query = "SELECT nickname, name, j2.label, j2.pointsum FROM user JOIN ( SELECT j1.user_id, j1.label, name, hover, j1.pointsum FROM activityfield JOIN ( SELECT user_id, activity_id, label, field_id , SUM( points.points ) AS PointSum FROM points JOIN activity ON points.activity_id = activity.id WHERE points.user_id=" . $q . " GROUP BY points.user_id, points.activity_id, activity.label, activity.field_id ORDER BY points.activity_id ASC ) AS j1 ON activityfield.id = j1.field_id ) AS j2 ON j2.user_id = user.id WHERE pointsum > 0 ORDER BY j2.pointsum DESC;";
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName)or die(mysql_error());;
if (!$con){ die('Could not connect: ' .mysqli_error());}
mysqli_select_db($con,"techyari_demos");
$result = mysqli_query($con,$sql_query);
echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Name-Label\",\"pattern\":\"\",\"type\":\"string\"}, {\"id\":\"\",\"label\":\"PointSum\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ ";
$total_rows = mysqli_num_rows($result)or die(mysqli_error());;
$row_num = 0;
while($row = mysqli_fetch_array($result)){
$row_num++;
if ($row_num == $total_rows){
echo "{\"c\":[{\"v\":\"" . $row['date'] . "-" . $row['sname'] . "\",\"f\":null},{\"v\":" . $row['status'] . ",\"f\":null}]}";
} else {
echo "{\"c\":[{\"v\":\"" . $row['date'] . "-" . $row['sname'] . "\",\"f\":null},{\"v\":" . $row['status'] . ",\"f\":null}]}, ";
}
}
echo " ] }";
mysqli_close($con);
?>
gettabledata
<?php
$q=$_GET["q"];
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'techyari_demos';
$sql_query="SELECT date,sname,dbs,status,updatedby from entry";
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysqli_select_db($con,"techyari_demos");
$result = mysqli_query($con,$sql_query);
echo "{\"c\":[{\"v\":\"" .'date'. "\",\"f\":null},{\"v\":\"" .'sname' . "\",\"f\":null},{\"v\":\"" .'dbs' . "\",\"f\":null},{\"v\":\"" .'status'. "\",\"f\":null},{\"v\":\"".'updatedby'."\",\"f\":null}]}, ";
$total_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
echo "{\"c\":[{\"v\":\"" . $row['date'] . "\",\"f\":null},{\"v\":\"" . $row['sname'] . "\",\"f\":null},{\"v\":\"" . $row['dbs'] . "\",\"f\":null},{\"v\":\"" .$row['status']."\",\"f\":null},{\"v\":\"" . $row['updatedby']. "\",\"f\":null}]}, ";
}
/* $result = mysqli_query($sql_query2);
while($row = mysqli_fetch_array($result)){
echo "{\"c\":[{\"v\":\"" . $row['servername'] . "\",\"f\":null},{\"v\":\"" . "\",\"f\":null},{\"v\":\"" . "\",\"f\":null},{\"v\":\" Total \",\"f\":null},{\"v\":\"" . $row['dbs'] . "\",\"f\":null}]}";
}
echo " ] }";*/
mysqli_close($con);
?>
Further to my comments (and others comments), create some classes for re-use and readability, create a config for storage of re-usables, and then finally use json_encode() on arrays to create json strings for your ajax. I don't know if they are correctly formed, but they will be valid json strings:
/config.php
<?php
# Used for universal directory separator compatibility
define('DS',DIRECTORY_SEPARATOR);
# Store absolute paths for easy referencing
define('ROOT_DIR',__DIR__);
define('VENDOR_DIR',ROOT_DIR.DS.'core'.DS.'vendors');
# Store database connection credentials this one spot only
define('DB_HOST','localhost');
define('DB_NAME','techyari_demos');
define('DB_USER','root');
define('DB_PASS','');
# Start user session
session_start();
# Create class autoloader so you don't have to worry about including manually
spl_autoload_register(function($class) {
$path = str_replace(DS.DS,DS,VENDOR_DIR.DS.str_replace('\\',DS,$class).'.php');
if(is_file($path))
include_once($path);
});
/core/vendors/Database.php
<?php
class Database
{
private static $con;
private $query;
# Assign database
public static function init()
{
$db = new Database();
return $db->getConnection();
}
# Creates database connection
public function getConnection()
{
if(self::$con instanceof \PDO)
return $this;
try {
self::$con = new \PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_NAME);
}
catch(\PDOException $e) {
}
return $this;
}
# Used to query database
public function query($sql,$bind=false)
{
if(!empty($bind)) {
foreach($bind as $key => $value) {
$skey = ":$key";
$setBind[$skey] = $value;
$this->query = self::$con->prepare($sql);
$this->query->execute($setBind);
}
}
else {
$this->query = self::$con->query($sql);
}
return $this;
}
# Used to fetch results from database
public function getResults($single=false)
{
$row = array();
while($result = $this->query->fetch(\PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(empty($row))
return $row;
return ($single)? $row[0] : $row;
}
}
/core/vendors/App.php
<?php
class App
{
# Easily return post values even if they don't exist without drawing errors
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Easily return get values even if they don't exist without drawing errors
public function getGet($key=false)
{
if(!empty($key))
return (isset($_GET[$key]))? $_GET[$key] : false;
return $_GET;
}
# Easily return session values even if they don't exist without drawing errors
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Used to render pages
public function render($file)
{
ob_start();
# Create instance of database
$db = Database::init();
# Include page to render
include($file);
# Assign view
$data = ob_get_contents();
ob_end_clean();
# Return for echo
return $data;
}
}
/index.php
<?php
if(!isset($this)) {
include_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
echo (new App())->render(__FILE__);
exit;
}
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart,table package.
google.load('visualization', '1', {'packages':['corechart','table']});
function drawItems(num) {
var jsonPieChartData = $.ajax({
url: "getpiechartdata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
var jsonTableData = $.ajax({
url: "gettabledata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var piechartdata = new google.visualization.DataTable(jsonPieChartData);
var tabledata = new google.visualization.DataTable(jsonTableData);
// Instantiate and draw our pie chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(piechartdata, {
width: 700,
height: 500,
chartArea: { left:"5%",top:"5%",width:"90%",height:"90%" }
});
// Instantiate and draw our table, passing in some options.
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(tabledata, {showRowNumber: true, alternatingRowStyle: true});
}
</script>
</head>
<body>
<form>
<select name="pt" onchange="drawItems(this.value)">
<option value="">Select a server:</option>
<?php
$servers = $db->query("SELECT id, servername FROM server ORDER BY servername ASC")->getResults();
foreach($servers as $row) { ?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['servername'] ?></option>
<?php
}
?>
</select>
</form>
<div id="chart_div"></div>
<div id="table_div"></div>
</body>
</html>
/getpiechartdata.php
<?php
if(!isset($this)) {
include_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
echo (new App())->render(__FILE__);
exit;
}
# Internally retrieve the get value
$q = $this->getGet("q");
# Run your general query
$results = $db->query("SELECT * from entry",array($q))->getResults(true);
# Set base array/object
$base = array(
'cols'=>array(
array(
'id'=>'',
'label'=>'Name-Label',
'pattern' => '',
'type'=>'string'
),
array(
'id'=>'',
'label'=>'PointSum',
'pattern' => '',
'type'=>'number'
)
)
);
# Create default array
$base['rows'] = array();
# Loop results, building on base array/object
foreach($results as $row) {
$base['rows'][] = array(
'c'=>array(
array(
'v'=>$row['date'].' - '.$row['sname'],
'f'=>NULL
),
array(
'v'=>$row['status'],
'f'=>NULL
)
)
);
}
# Return results
echo json_encode($base);
I am trying to select multiple columns with concat an put the returned data into one textbox.
I think there is something wrong with my definition for the variables. But I could not figured out what is wrong. Here are the variables:
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
When I define just one variable for $name the script works. But that is not what I want.
Does someone know what is wrong?
Here is the other part of my script.
First I have a textbox. The data needs to be send to this textbox:
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
The button calls sends '5' as the ID and runs the script getName():
<button type="button" rel="5" onclick="getName();"
<script type="text/javascript">
$('body').on('click', '.selectClass', function () {
var id = $(this).attr('rel');
$("#id").val(id);
modal.style.display = "none";
});
</script>
After clicking on the button the id is deployed here:
<input type="text" class="form-control" id="id" name="id">
The onClick event runs the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getName(value) { // Do an Ajax request to retrieve the product price
console.log("getName before ajax", jQuery('#id').val());
jQuery.ajax({
url: './get/getname5.php',
method: 'POST',
data: {'id' : jQuery('#id').val()},
success: function(response){
console.log("getName after ajax", jQuery('#id').val());
jQuery('#name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The jquery script calls the PHP, which is not working with the multiple variables for $name
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$conn = new mysqli($servername, $username, $password, $dbname) ;
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
$query = 'SELECT concat(firstname, ' ', insertion, ' ', lastname) as name FROM users WHERE id="' . mysqli_real_escape_string($conn, $id) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}
}
?>
Hi All,
i'm getting all the data from database for array format i need to pass that data to second drop down list like (group option value),please any one help me.
This is my php code:
<?php
//error_reporting(0);
$servername = "localhost";
$username = "root";
$password = "";
$db = "essae";
$data = "";
$subcategory_id = "";
$subcategory_name = array();
$conn = mysqli_connect($servername, $username, $password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category= $_GET["category_id"];
$sql = "SELECT es_category.category_id,es_category_description.name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$result = $conn->query($sql);
if ($result->num_rows > 1){
$sql_getrec ="SELECT es_category.category_id AS sub_cat_id,es_category_description.name AS sub_cat_name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$sub_category= $conn->query($sql_getrec);
if ($sub_category->num_rows > 1){
while ($row=mysqli_fetch_array($sub_category)){
$subcategory_id = $row['sub_cat_id'];
//$subcategory_name['sub_category_name'][] = $row['sub_cat_name'];
$sql_getrec = "SELECT es_product_description.name AS prod_name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id = $subcategory_id AND es_product.status=1";
$sub_product=$conn->query($sql_getrec);
while ($prow=mysqli_fetch_array($sub_product)){
$subcategory_name['sub_category_name'][$row['sub_cat_name']]['products_name'][] = $prow['prod_name'];
}
}
echo "<pre>";print_r($subcategory_name);
}
}
else {
$sql_getrec = "SELECT es_product_description.name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id='$category' AND es_product.status=1";
$result_getrec=$conn->query($sql_getrec);
while ($row=mysqli_fetch_array($result_getrec)){
$data .= $row['name'].",";
}
$data = rtrim($data,",");
}
print_r($data);
?>
This is my Html code:
<php?
$decocedData1 = json_decode($str_json_format, TRUE);
//print_r($decocedData1);die;
$decode = $decocedData1;
?>
<div>
<select name="category" id="category" />
<option selected ="selected">Select category</option>
<?php foreach($decode as $key => $value) { ?>
<option value="<?php echo $value['category_id']; ?>"><?php echo $value['name']; ?></option>
<?php } ?>
</select>
</div>
<div><select name="category12" id="category12" />
</select>
</div>
this is my j query and ajax method code:
<script type="text/javascript">
$(document).ready(function(){
$('#category').change(function(){
var category_id=$('#category').val();
$.ajax({
type: "get",
url: 'data_product.php?category_id='+category_id,
success: function(data) {
var products = data.split(",");
state_html = '';
state_html = '<option>Please Select product</option>'
$.each(products, function (index, productName) {
state_html += "<option value='"+productName+"'>"+productName+"</option>";
});
$('#category12').html(state_html);
},
});
})
});
</script>
You may use Type Casting in php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
<?php
$array = array("name", "age", "mobile", "email");
var_dump($array);
(string)$array;
var_dump($array);
?>
This is not your final answer but you can try below code and figure out your variable names
$('#category12').empty();
$.each(data, function (index) {
var optgroup = $('<optgroup>');
optgroup.attr('label',data[index].name);
$.each(data[index].children, function (i) {
var option = $("<option></option>");
option.val(i);
option.text(data[index].children[i]);
optgroup.append(option);
});
$("#category12").append(optgroup);
});
$("#category12").multiselect('refresh');
you can do a jquery each in the result of your ajax
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
$(function(){
//sample result, this will be your ajax result....
var products = ["Candy", "Cotton Candy", "Iced Candy"];
//clear again the select element.
$('#category12').empty();
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="category12"></select>
I am trying to show data from the database in my textbox. But when I start the script I am getting no results. I tested the script in different ways and i figured out that the variable: $product1 is empty. Does anybody know how I can fix this?
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
}
?>
Change
var selectedItem = jQuery('.product1 option:selected').val();
To
var selectedItem = jQuery('#product1 option:selected').val();
You are selecting a class with name product1, but you set only an ID with this name. Id's are specified with # and classes with .
Update on your script, because you used getPrice(this.value);
<script>
function getPrice(selectedItem) {
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
TIP:
Did you know that you can use jQuery.ajax and jQuery('selector') also like this: $.ajax and $('selector') :-)
You have not a form tag in your HTML. The default form Method is GET.
In Your get.php you try to get a POST Variable with filter_input
The function filter_input returns null if the Variable is not set.
Two possible solutions:
1. Add a form to your html with method="post"
2. Change your php code to search for a GET variable
Im trying to do this: When someone selects any option from the drop down called subject, the sections drop down should show all sections of that subject. The subject drop down works well, fetches all names of subjects but the sections one won't work. Im unable to find the issue. It should fetch the sections from the database WHERE/WHEN name(database column) is equal to the subject chosen. Thanks in advance. My code is below:
my js code
<script type="text/javascript">
function getSection(strURL)
{
alert(strURL);
var req = getXMLHTTP(); // fuction to get xmlhttp object
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('sectiondiv').innerHTML=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
req.open("GET", strURL, true); //open url using get method
req.send(null);
}
}
</script>
php code:
<div>
Subject:
<?php
$conn = new mysqli('localhost', '', '', '')
or die ('Cannot connect to db');
$result = $conn->query("select name from class");
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$name = $row['name'];
echo '<option value="subject">'.$name.'</option>';
}
echo "</select>";
?>
</div>
<br>
<div id="sectiondiv">
Section:
<select name="select">
</select>
</div>
my findsection.php
<? $subject=intval($_GET[‘subject’]);;
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$mysqli = new Mysqli($servername, $username, $password, $dbname) or mysqli_error($mysqli);
$section = $mysqli->query("SELECT section FROM class WHERE name = '$subject'")->fetch_object()->section;
$result=mysql_query($section);?>
<select name="section">
<? while ($row = $result->fetch_assoc()) { ?>
<option value><?=$row['section']?></option>
<? } ?>
</select>
You have incomplete/invalid html
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
Change it to this
echo '<select name="subject" onchange="getSection(\'findsection.php?subject=\' + this.value)">';