Jvector change country name to database name? - javascript

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"];
}
}

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

Loading data via `dataLoader` in serial AmCharts does not renders the chart

I'm using dataLoader for retrieving data in AmChart from PHP/MySql backend.
However the simple serial bar chart is generated but don't know what is the problem with rendering graphs, graphs are not getting generated.
Then with another try using ajax call I've done re-parsing of JSON response to object via loop just like generateChartData(), it's the same data. But still chart is not getting rendered.
These options I've passed to dataLoader
"dataLoader": {
"url": 'data.php',
"format": "json"
}
In ajax call I call chart.validateData() but this is not working. What can done to solve this?
setting async option for ajax request false gives warning and doesn't work too.
Here is the js code app.js:
var chartData = [];
loadChartData();
function loadChartData() {
var time = new Date();
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var cur = new Date();
var data = JSON.parse(ajax.responseText);
data.forEach(function(d, i) {
chartData.push({
date: d.date,
visits: parseInt(d.visits, 10)
});
});
// alert('Request Completed in '+ (cur - time)+ ' mili seconds');
console.log(chartData.length);
// chart.validateData();
}
};
ajax.open('GET', 'data.php', true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send();
}
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 80,
// "dataLoader": {
// "url": "data.php",
// "format": "json"
// }, this doesn't work too!
"dataProvider": chartData,
"dataDateFormat": "YYYY-MM-DD",
"valueAxes": [{
"position": "left",
"title": "Energy Generated"
}],
"graphs": [{
"id": "g1",
"fillAlphas": 0.4,
"valueField": "visits",
"balloonText": "<div style='margin:5px; font-size:19px;'><b>[[value]]kWh</b></div>"
}],
"chartScrollbar": {
"graph": "g1",
"scrollbarHeight": 80,
"backgroundAlpha": 0,
"selectedBackgroundAlpha": 0.1,
"selectedBackgroundColor": "#888888",
"graphFillAlpha": 0,
"graphLineAlpha": 0.5,
"selectedGraphFillAlpha": 0,
"selectedGraphLineAlpha": 1,
"autoGridCount": true,
"color": "#AAAAAA"
},
"chartCursor": {
"categoryBalloonDateFormat": "JJ:NN, DD MMMM",
"cursorPosition": "mouse"
},
"categoryField": "date",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
},
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
chart.zoomToIndexes( chart.dataProvider.length - 250, chart.dataProvider.length - 100);
}
zoomChart();
And here is my php code data.php
$link = new mysqli( "localhost", "root", "", "test" );
if ( $link->connect_errno ) {
die ("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
// Fetch the data
$query = "SELECT *
FROM daily_visits
ORDER BY date ASC";
$result = $link->query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . $link->error . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
// Close the connection
mysqli_close($link);
And the returned json looks like
[{"date":"2016-09-03","visits":"16"},{"date":"2016-09-03","visits":"49"},...]
Remove "dataProvider": chartData from makeChart, when using dataloader.
You should update the instance of the chart:
let chartInstance = AmChart.makeCharts(...);
(<any>this.chartInstance).dataProvider = parsedArray; // yes, here we update the dataProvider directly
If anyone doesn't understand this, please leave a message here.

Passing PHP-Variables to Jquery

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>

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.

send data from php to javascript using jquery

I'm trying to implement a vertical timeline, but I don't know how to get the data in the correct form from the db using php.
the code to add the events is the following:
$(function() {
$("#element").timeline({
data: [
{time: new Date(),
color: '#555',
css: 'success',
content: 'jquery.timeline Demo Event 1'},
{time: new Date(),
color: '#00ff00',
css: 'success',
content: 'jquery.timeline Demo Event 2'},
{time: new Date(),
color: '#000',
css: 'success',
content: 'jquery.timeline Demo Event 3'},
{time: new Date(),
color: '#000',
css: 'success',
content: 'jquery.timeline Demo Event 4'}
]
});
I set up a get.php and I can get the data from db in this way:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT NAME, TEXT, DATE FROM TABLE";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["NAME"]. " - Name: " . $row["TEXT"]. " " . $row["DATE"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
How would I put all the retrieved contents inside the event handler?
$(function() {
$("#element").timeline({
data: [
{time: date_event_1,
color: color_event_1,
css: 'success',
content: content_event_1},
...
...
]
});
Thanks in advance.

Categories

Resources