Passing PHP-Variables to Jquery - javascript

i want to load some data from an sql-table and use them with jquery to color a map.
I picked up the data with PHP:
<?php
include 'connect.php';
session_start();
$userid = $_SESSION['userid'];
$sql = "
SELECT landstatus.shortland
FROM landstatus
WHERE users_id='1'
AND status ='wanttovisit'
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["shortland"]. "<br>";
}
}
$conn->close();
?>
Now i want to use shortland for the static value 'ca' in jquery:
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#FFFFFF',
hoverOpacity: 0.7,
selectedColor: '#727272',
enableZoom: true,
colors:{
'ca' : '#4E7387',
},
series: {
regions:
[{
attribute: 'fill'
}]
},
onRegionClick: function (element, code, region) {
$(".info-box-region").append(region);
$(".info-box").show();
$("input[name=region]").val(region);
$('input[name=code]').val(code);
}
});
});
</script>
At the end colors would be filled with all shortlands from the database - each shortland has the same hex-code.
Thx for helping me.

Place all shortland values in an array and loop through it to create the ca entries
$result = $conn->query($sql);
$shortlands = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$shortlands[] = $row["shortland"];
}
}
Then loop over the values. e.g.
colors:{
<?php
foreach ($shortlands as $val) {
echo "'{$val}': '#4E7387',\n";
}
?>
},

You can "pass" anything PHP knows into JavaScript variables simply by echoing them into JavaScript code in your template:
<script>
var myJavaScriptVar = <?php echo $myPhpVar ?>
</script>

Just do this:
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#FFFFFF',
hoverOpacity: 0.7,
selectedColor: '#727272',
enableZoom: true,
colors:{
'ca' : '<?php echo $row["shortland"] ;?>',
},
series: {
regions:
[{
attribute: 'fill'
}]
},
onRegionClick: function (element, code, region) {
$(".info-box-region").append(region);
$(".info-box").show();
$("input[name=region]").val(region);
$('input[name=code]').val(code);
}
});
});
</script>

Related

Reading MySQL data into highstocks

So this is the first time i have really worked with high charts i have some data reading into high charts from my MySQL database, but the next step is to try and set up a high stocks chart. Whenever i try and use the same method as i did with high charts the chart doesn't work? This is what i want to aim for - StockChartDemo
PHP Code:
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);
if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){
echo '['.$row["time"].',' .$row["humidity"].']';
$count++;
if ($count<"20"){
echo ',';
}
}
echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>
html & jQuery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="highstock.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var options = {
chart: {
renderTo: 'tempcontainer',
alignTicks: false,
height:320,
},
rangeSelector: {
selected: 1
},
title: {
text: 'Relative humidity'
},
series: [{
type: 'column',
name: 'Humidity',
data: json,
dataGrouping: {
units: [[
'month', // unit name
[1] // allowed multiples
], [
'week',
[1, 2, 3, 4, 6]
]]
}
}]
}
$.getJSON("stockdata.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.stockChart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("stockdata.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.stockChart(options);
});
},60000);
}
});
</script>
<div id="tempcontainer"></div>
Presuming your query is returning the correct data you want. (I'm not up for mocking it out to test your query)
You should switch out the following code, and all that in-between.
if ($result->num_rows>0){
//snip
}
To use json_encode() instead.
$series = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$series[] = [
$row["time"],
$row["humidity"]
];
}
}
header('Content-Type: application/json');
exit(json_encode($series));

How to display the sum in this graph. I have the same year in my database (2012) How can i add those 2 data? And display automatically in graph?

How to display the sum in this graph. I have the same year in my database (2012) How can i add those 2 data? And display automatically in graph? This is the codes of my sample:
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM account";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result)) {
$chart_data .= "{ year:'".$row["year"]."', profit:".$row["profit"].",
purchase:".$row["purchase"].", sale:".$row["sale"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>
<script type="text/javascript">
config = {
data: [<?php echo $chart_data; ?>],
xkey: 'year',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
fillOpacity: 0.6,
hideHover: 'auto',
behaveLikeLine: true,
resize: true,
pointFillColors: ['#ffffff'],
pointStrokeColors: ['black'],
lineColors: ['gray','red']
};
</script>

Passing Decimal string from php to jquery

I am trying to pass some formatted String from PHP to jQuery. But i am getting an error as
VM2203:3 Uncaught SyntaxError: Unexpected number in the browser.
Here is my code
<?php
$OSlist = [];
$category = "";
$pieData = "";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8081",
CURLOPT_URL => "http://localhost:8081/api/devices/hoursBy/OSVersion",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$decodeStr = json_decode($response, true);
foreach ($decodeStr as $item) {
$os = $item['_id']['os'];
if ($os == $selectedOS) {
if ($item['total_hours'] != 0) {
$OSlist[$item['_id']['version']] = $item['total_hours'];
// echo 'iOS'.$item['_id']['version'] . ' : ' . $item['total_hours'] ,"<br>";
}
}
}
ksort($OSlist);
foreach ($OSlist as $key => $val) {
// echo "$key = $val" . "<br>";
$category = $category . $key . ",";
$pieData = $pieData . "[" . $key . "," . $val . "],";
}
$pieData="[".$pieData."]";
echo $pieData;
// print_r($OSlist);
} ?>
<script >
$('document').ready(function () {
var jsArray = <?php echo $pieData; ?>;
alert(jsArray);
});
</script>
The Piedata output is
[[2.3.4,97.9],[4.0.3,11.6],[4.0.4,2.4],[4.1.1,15.1],[4.1.2,398.4],[4.2.1,45.8],[4.2.2,27.3],[4.3,321],[4.4.2,694.9],[4.4.4,478.7],[5,646.3],[5.0.1,177.5],[5.0.2,1210.5],[5.1,126.2],[5.1.1,524.4],[6,201.5],]
i actually need to pass this data to highchart pie graph to the data value.The following graph is for mobile version vs its utilization hours.
function loadPieGraph() {
// Radialize the colors
var android = <?php echo $androidhrs ?>;
var ios = <?php echo $ioshrs ?>;
var obj = [{
type: 'pie',
name: 'Browser share',
data: [
['4.1', '23.0'],
{
name: '5.0',
y: '40.2',
sliced: true,
selected: true
},
]
}];
Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
},
connectorColor: 'silver'
}
}
},
series: obj
});
}
This whole part:
foreach ($OSlist as $key => $val) {
// echo "$key = $val" . "<br>";
$category = $category . $key . ",";
$pieData = $pieData . "[" . $key . "," . $val . "],";
}
$pieData="[".$pieData."]";
echo $pieData;
// print_r($OSlist);
} ?>
<script >
$('document').ready(function () {
var jsArray = <?php echo $pieData; ?>;
alert(jsArray);
});
</script>
looks really faulty in nature.
You should rather:
$pieData = json_encode($OSlist);
and in the script tag you can simply do this:
jsArray = JSON.parse("<?php echo $pieData; ?>");
And then do the HighChart's relevant array formatting in the JS.
Or you can directly do the formatting first in PHP and do json encode the final form and directly pass it to js where again you will need to JSON.parse them again.
Always do data transactions in form of JSON in these types of cases.
Hope it helps.
Hope it helps.

Jvector change country name to database name?

I have used Jvectormap it is working well. Now its work function if I click country showing country name .
i have created simple database particular country. connected database via ajax its working well.its showing alert msg database created country.
created database Canada country.But now I want display database in when click Canada show details from database not in alert box? please help me?
script:
<script>
jQuery.noConflict();
jQuery(function(){
var $ = jQuery;
$('#focus-single').click(function(){
$('#map1').vectorMap('set', 'focus', {region: 'AU', animate: true});
});
$('#focus-multiple').click(function(){
$('#map1').vectorMap('set', 'focus', {regions: ['AU', 'JP'], animate: true});
});
$('#focus-coords').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 7, lat: 35, lng: 33, animate: true});
});
$('#focus-init').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 1, x: 0.5, y: 0.5, animate: true});
});
$('#map1').vectorMap({
map: 'world_mill_en',
panOnDrag: true,
focusOn: {
x: 0.5,
y: 0.5,
scale: 1,
animate: true
},
series: {
regions: [{
scale: ['#688FA0'],
normalizeFunction: 'polynomial',
values: {
// "TD":23.4,
// "TH": 312.61,
"TL": 0.62,
// "TZ":1.56,
"TO": 0.3,
// "TT": 21.2,
//"TM":21.2,
// "TR": 729.05,
//"TJ":21.2,
// "TN":4.3,
// "YE":0.3,
// "UA": 136.56,
// "QA":0.72,
"GB": 2258.57,
// "GA":4.6,
"US": 14624.18,
//"UG":4.3,
//"UY": 40.71,
// "UZ":0.72,
"VU": 0.72,
// "VE":5.77,
// "VN": 101.99,
// "ZW":8.4,
// "ZM":2.5,
}
}]
},
onRegionClick: function (event, code) {
var map = $('#map1').vectorMap('get', 'mapObject');
var name = map.getRegionName(code);
/*
onRegionLabelShow: function(e, el, code) {
//search through data to find the selected country by it's code
var country = $.grep(data.countries, function(obj, index) {
return obj.code == code;
})[0]; //snag the first one
if (country != undefined) {
el.html(el.html() + "<br/><b>Code: </b>" +country.code + "<br/><b>Continent : </b> " + country.continent);
}
*/
// get from DB using ajax
$(document ).ready(function() {
$.ajax({
type: "GET",
url: 'database.php',
data: {country: name},
dataType: "text",
success: function(data){
// alert(data);
}
});
});
},
});
})
</script>
My PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$_country = $_GET['country'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT countryId,country,pdogcoregion,ccl,category FROM countrydetails WHERE country='".$_country."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "country: " . $row["country"];
}
} else {
echo "No database";
}
$conn->close();
?>
name display from this file i update simple part code this file
$.fn.vectorMap('addMap', 'world_mill_en',{"insets": [{"width": 900.0, "top": 0, "height": 440.7063107441331, "bbox": [{"y": -12651089.408837218, "x": -19971805.562327016}, {"y": 6919135.471157653, "x": 19994044.625421535}], "left": 0}], "paths": {"BD": {"path": "M652.71,228.85l-0.04,1.38l-0.46,-0.21l-0.42,0.3l0.05,0.65l-0.17,-1.37l-0.48,-1.26l-1.08,-1.6l-0.23,-0.13l-2.31,-0.11l-0.31,0.36l0.21,0.98l-0.6,1.11l-0.8,-0.4l-0.37,0.09l-0.23,0.3l-0.54,-0.21l-0.78,-0.19l-0.38,-2.04l-0.83,-1.89l0.4,-1.5l-0.16,-0.35l-1.24,-0.57l0.36,-0.62l1.5,-0.95l0.02,-0.49l-1.62,-1.26l0.64,-1.31l1.7,1.0l0.12,0.04l0.96,0.11l0.19,1.62l0.25,0.26l2.38,0.37l2.32,-0.04l1.06,0.33l-0.92,1.79l-0.97,0.13l-0.23,0.16l-0.77,1.51l0.05,0.35l1.37,1.37l0.5,-0.14l0.35,-1.46l0.24,-0.0l1.24,3.92Z", "name": "Bangladesh"}, "BE": {"path": "M429.28,143.95l1.76,0.25l0.13,-0.01l2.16,-0.64l1.46,1.34l1.26,0.71l-0.23,1.8l-0.44,0.08l-0.24,0.25l-0.2,1.36l-1.8,-1.22l-0.23,-0.05l-1.14,0.23l-1.62,-1.43l-1.15,-1.31l-0.21,-0.1l-0.95,-0.04l-0.21,-0.68l1.66,-0.54Z", "name": "Belgium"}
Please help me anybody. I am new in jQuery and JavaScript.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "country: " . $row["country"];
}
}
You are still returning the country.
try
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "category: " . $row["category"];
}
}

how to change customize label function?

Now I am currently using Jvector Map. Its working well. When I click the country name its shows country name for default. Now I want to customize the label and show label database value?
Script code:
<script>
jQuery.noConflict();
jQuery(function(){
var $ = jQuery;
$('#focus-single').click(function(){
$('#map1').vectorMap('set', 'focus', {region: 'AU', animate: true});
});
$('#focus-multiple').click(function(){
$('#map1').vectorMap('set', 'focus', {regions: ['AU', 'JP'], animate: true});
});
$('#focus-coords').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 7, lat: 35, lng: 33, animate: true});
});
$('#focus-init').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 1, x: 0.5, y: 0.5, animate: true});
});
$('#map1').vectorMap({
map: 'world_mill_en',
panOnDrag: true,
focusOn: {
x: 0.5,
y: 0.5,
scale: 1,
animate: true
},
series: {
regions: [{
scale: ['#688FA0'],
normalizeFunction: 'polynomial',
values: {
// "YE":0.3,
// "UA": 136.56,
// "QA":0.72,
"GB": 2258.57,
// "GA":4.6,
"US": 14624.18,
//"UG":4.3,
//"UY": 40.71,
// "UZ":0.72,
"VU": 0.72,
// "VE":5.77,
// "VN": 101.99,
// "ZW":8.4,
// "ZM":2.5,
}
}]
},
onRegionClick: function (event, code) {
var map = $('#map1').vectorMap('get', 'mapObject');
var name = map.getRegionName(code);
$(document ).ready(function() {
$.ajax({
type: "GET",
url: 'database.php',
data: {country: name},
dataType: "text",
success: function(data){
alert(data);
}
});
});
},
});
})
</script>
Its MY script code when i click country showing name country name default i want display from database . i have created database its connected via ajax code above code i had mentioned.
here attach my php code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$_country = $_GET['country'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT countryId,country,pdogcoregion,ccl,category FROM countrydetails WHERE country='".$_country."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "category: " . $row["category"];
}
}
else {
echo "No database";
}
$conn->close();
?>
I need to change the label showing country name default.
I want set database display label ?
You can customise tooltip using onRegionTipShow method. Just take a look at example available here.

Categories

Resources