How to transfer data from sql to javascript? - javascript

I work with this example: https://www.sitepoint.com/dynamic-geo-maps-svg-jquery/ But I need get data from MySql DB.
I have 2 main files:
1) map.php (connect to db and show svg map)
2) map.js (show colorized map with static data)
In JS file I see rows:
enter code here
var regions=[
{
"region_name": "Lombardia",
"region_code": "lom",
"population": 9794525
},
{
"region_name": "Campania",
"region_code": "cam",
"population": 5769750
},
// etc ...
];
I need change value of region name to value from db. But I do not how?
In my php main variable are:
echo "Region: ".$row['region_name']."
echo "Code of region: ".$row['region_code']."
echo "Value: ".$row['value']."

First of all your PHP code should connect to the database, extract the data you are interested in and build a json string from it, just like the regions data from your example. Your PHP will return this json. You will probably want to work with json because it is the most ajax/js friendly format.
Your JS code should make a Ajax call to that PHP for retrieving the json formatted data. Assuming you are using jquery, it is something like this:
$.ajax({
url : "map.php",
dataType : "json",
done: function(data){
// the data parameter is the json returned by the php
// already converted to javascript object...
// Just like the regions array from your example.
}
});
For further information and options about the jquery ajax api, see http://api.jquery.com/jquery.ajax.

Normally you won't be modifying your js file. Instead you need to load your data from DB using i.e. an ajax call and then "give" it to the control you're using.
To do that you need i.e. a web service that returns your data and some javascript function that calls it. You can do something like this:
var jqxhr = $.get( "map.php", function() {
alert( "success" );
}).done(function(data ) {
refresh_your_map(data);
});
check https://api.jquery.com/jquery.get/ for more details
Edited - do something like this:
/* define this function in your js file*/
var getRegionsData = function()
{
var result =[];
$.ajax({ url: 'map.php',
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
//then do this
var regions=getRegionsData();
//the rest of your code from map.js

index.php
enter code here
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="map.css" rel="stylesheet" media="all">
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script src="map.js"></script>
<title>Моя карта</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "happy_user";
$password = "1234567890";
$dbname = "freesite_zzz_com_ua";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT region_name, region_code, value FROM map";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "region_name: " . $row["region_name"]. " region_code: " .
$row["region_code"]. " value: " . $row["value"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<h1>svg map</h1>
<div class="map">
<svg version="1.1" id="map_x5F_id" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="595.3px" height="841.9px" viewBox="0 0 595.3 841.9" style="enable-
background:new 0 0 595.3 841.9;" xml:space="preserve"
>
<g id="id_x5F_1">
<rect x="58" y="163" width="85" height="85"/>
</g>
<g id="id_x5F_2">
<rect x="143" y="163" width="85" height="85"/>
</g>
<g id="id_x5F_3">
<rect x="228.1" y="163" width="85" height="85"/>
</g>
</svg>
</div>
</body>
</html>
map.js:
var regions=[
{
"region_name": "region-1",
"region_code": "id_x5F_1",
"value": "10"
},
{
"region_name": "region-2",
"region_code": "id_x5F_2",
"value": "20"
},
{
"region_name": "region-3",
"region_code": "id_x5F_3",
"value": "30"
}
];
var temp_array = regions.map(function(item){
return item.value;
});
var highest_value = Math.max.apply(Math, temp_array);
$(function() {
for(i = 0; i < regions.length; i++) {
$('#'+ regions[i].region_code)
.css({'fill': 'rgba(11, 104, 170,' + regions[i].value/highest_value
+')'})
.data('region', regions[i]);
}
$('.map g').mouseover(function (e) {
var region_data=$(this).data('region');
$('<div class="info_panel">'+
region_data.region_name + '<br>' +
'value: ' + region_data.value.toLocaleString("en-UK") +
'</div>'
)
.appendTo('body');
})
.mouseleave(function () {
$('.info_panel').remove();
})
.mousemove(function(e) {
var mouseX = e.pageX, //X coordinates of mouse
mouseY = e.pageY; //Y coordinates of mouse
$('.info_panel').css({
top: mouseY-50,
left: mouseX - ($('.info_panel').width()/2)
});
});
});

Related

Data automatically change in ajax call

I am try to pass a div and elements in Ajax success response but it will automatically change and extra front slash the div .
my Ajax code is
$.ajax({
'method': 'GET',
'url': base_url +'show/elementshoe',
success: function(data) {
if(data == ""){
}else{
//alert(data);
$("#date-div-id").html(data);
}
}
});
in controller
public function elementshoe() {
$result = [];
$data = $this->elemtsModel->getRandompart($state);
if (!empty($data)) {
$i = 0;
foreach($data as $list){
$result.='<div class="data"><div class="icon"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32" viewBox="0 0 32 32"><defs>...'.$list->party .' Party';
}
}
$res = json_encode($result);
sendJsonResponse($res);
}
the alert data show the result like
" Array<div class=\"data\"><div class=\"icon\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" xmlns:xlink=\"http:\/\/www.w3.org\/1999\/xlink\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\"><defs>...Tirupathi govind Party "
so this element does show in web page
How to solve this issue, the start of the line the word Array and "" in starting and end of this data also remove that,please help me
You should return the html code directly from the controller without using the json_encode. Try using 'echo' instead of 'json_encode'.
public function elementshoe() {
$result = '';
$data = $this->elemtsModel->getRandompart($state);
if (!empty($data)) {
foreach($data as $list){
$result .= '<div class="data"><div class="icon"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32" viewBox="0 0 32 32"><defs>...'.$list->party .' Party';
}
}
echo $result;
}

Draw Line Chart (chart data is coming from mysql) based upon selected date from datepicker (Date is coming from mysql table)

What i have trying to do draw a line chart based on date and Id mentioned in the date picker like this
Below is My Code which i am currently using to populate the line chart
HTML CODE (TO show the chart )
<html>
<head>
<title>Temperature chart</title>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<script type="text/javascript" src="js/jquery-3.4.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
data.php (using this file to get the data from mysql and printing it using json)
<?php
//setting header to json
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://localhost:8080/hurry/data.php', false);
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'canvasjs_db');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT `temp`, `formatedate` FROM `datapoints` WHERE `device_id` = '50' AND `formatedate` >= '2019-04-02 09:26:00' AND `formatedate` <= '2019-04-03 13:26:00'");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
app.js (using this file to populate the data in chart)
$(document).ready(function(){
$.ajax({
url: "http://localhost:8080/Notifications/NewNotification/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push(data[i].formatedate);
score.push(data[i].temp);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Temperature ',
hoverBackgroundColor: 'rgba(30, 0, 200)',
hoverBorderColor: 'rgba(200, 200, 197)',
data: score
}
]
};
var ctx = $("#mycanvas");
var lineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});

Javascript Array to mysql database using Jquery

I'm trying to figure out how do I send a javascript array of x,y coordinates to a Mysql database? I don't have any forms or anything.
I'm very new the mysql so I basically know how to connect using this:
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
but I don't know how to connect that to the javascript. I know it has something to do with this code
jQuery.post(url, data);
Any help would be really appreciated!
I've put together this little one-page demo. Having a look at it might help you understand how it works.
To make it work, you need to put it on a server (no way!), and to have a table with x and y fields. Then, replace database credentials with your own.
References
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://api.jquery.com/jquery.ajax/
Live demo
http://shrt.tf/coordinates
Note
This one does not check for types (you can input any String), but you can add that.
test.php
<?php
// Replace these parameters to match your database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'mydatabase';
$table = 'coordinatesTable';
// Connect
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// If parameters are received
if(isset($_POST['x']) && isset($_POST['y'])){
$error_messages = array();
if ($mysqli->connect_errno) {
$error_messages[] = "Couldn't connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Prepare insert
if (!($stmt = $mysqli->prepare("INSERT INTO `$table` (x,y) VALUES (?,?)"))) {
$error_messages[] = "Couldn't prepare statement: (" . $mysqli->errno . ") " . $mysqli->error;
}
// Bind parameters x and y
if (!$stmt->bind_param("dd", $_POST['x'], $_POST['y'])) {
$error_messages[] = "Couldn't bind parameters: (" . $stmt->errno . ") " . $stmt->error;
}
// Execute the insert
if (!$stmt->execute()) {
$error_messages[] = "Couldn't execute the query: (" . $stmt->errno . ") " . $stmt->error;
}
// Prepare some data to return to the client (browser)
$result = array(
'success' => count($error_messages) == 0,
'messages' => $error_messages
);
$stmt->close();
// Send it
echo json_encode($result);
// Exit (do not execute the code below this line)
exit();
} // end if
// Fetch all the coordinates to display them in the page
$res = $mysqli->query("SELECT x,y FROM `$table`");
$rows = array();
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
$mysqli->close();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test page</title>
<style>
table{ border-collapse: collapse; }
th,td{ border: 1px solid #888; padding: .3em 2em; }
</style>
</head>
<body>
<h1>New coordinates</h1>
<p>
x: <input type="text" id="x">
y: <input type="text" id="y">
<button id="addBtn">Add</button>
</p>
<table id="coordinates">
<tr>
<th>x</th>
<th>y</th>
</tr>
<?php
if(count($rows)){
foreach($rows as $row){
?>
<tr>
<td><?=$row['x']?></td>
<td><?=$row['y']?></td>
</tr>
<?php
}
}
?>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function(){
$('#addBtn').click(postCoordinates);
function postCoordinates(){
var x = $('#x').val(),
y = $('#y').val();
if(x.length && y.length){
// Change this if it is on a different page
var url = window.location.href;
$.ajax({
'url': url,
'method': 'post',
'data': {'x': x, 'y': y},
'dataType': 'json', // The server will return json
'success': function(res){
if(res.hasOwnProperty('success') && res.success){
$('#x, #y').val(''); // Empty the inputs
$('#coordinates').append('<tr><td>'+x+'</td><td>'+y+'</td></tr>');
} else if(res.hasOwnProperty('messages')) {
alert( res.messages.join('\n') );
}
},
'error': function(x, s, e){
alert( 'Error\n' + s + '\n' + e );
}
});
} else {
alert('You need to provide x and y coordinates');
}
}
});
</script>
</body>
</html>
Search for ajax. Send the data from client side to server side:
For example:
$('selector').on('click', function(){
var coordinates = [x,y];
$.ajax({
method: 'POST',
url: 'yourURL',
data: {coordinates: coordinates},
success: function(response){
Console.log(response);
}
});
});
In PHP:
$coor = $_POST['coordinates'];
echo $coor;
//Search the manual of php for storing it in the database
NOTE: Don't use mysql because it is deprecated, use mysqli or PDO.

Filling ammap using mysql

I'm not that experienced in Javascript and I'm kind of stuck with ammap (http://www.amcharts.com/javascript-maps/).
The idea is to add some locations to the map from a mysql database. Their tutorial chapter on this is outdated and recommends using the DataLoader plugin instead (http://www.amcharts.com/tutorials/using-data-loader-plugin/). This, however, is for amcharts rather than ammap, and I can't figure it out.
Here's the code:
index.php
<script src="ammap/ammap.js" type="text/javascript"></script>
<link rel="stylesheet" href="ammap/ammap.css" type="text/css"
media="all" />
<script src="ammap/maps/js/germanyLow.js" type="text/javascript"></script>
<script
src="http://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"
type="text/javascript"></script>
<script type="text/javascript">
AmCharts.makeChart( "mapdiv", {
"type": "map",
"dataProvider": {
"map": "germanyLow"
}
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true
},
} );
</script>
<div id="mapdiv" style="width: 600px; height: 400px;"></div>
data.php
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "map";
$conn = new mysqli ( $server, $user, $pass, $db);
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT latitude, longitude FROM map";
$result = $conn->query($sql);
if($result->num_rows > 0){
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}else{
//
}
$string = json_encode($data);
echo $string;
?>
The json string of the data.php file is:
[{"latitude":"48.47","longitude":"9.11"},{"latitude":"53.33","longitude":"10"}]
The map won't load with this code. If I comment out the dataLoader part, the map itself loads just fine. Does anybody know how to use the dataLoader properly? Any help would be greatly appreciated.
Solved with help from amcharts support crew. For those of you interested in the solution:
AmCharts.makeChart("mapdiv", {
"type": "map",
"data": {
"map": "germanyLow"
},
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true,
"postProcess": function(data, config, map) {
// create a new dataProvider
var mapData = map.data;
// init images array
if (mapData.images === undefined)
mapData.images = [];
// create images out of loaded data
for(var i = 0; i < data.length; i++) {
var image = data[i];
image.type = "circle";
mapData.images.push(image);
}
return mapData;
}
}
});

PHP variable not being passed to AJAX call?

Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>

Categories