I have an issue with my code below. I populated my selectbox from my db which works fine. But when I select an option it wont send the value to my other php file I am relative new to jQuery so I hope that I have a small error in my code I hope that someone can help me.
$(document).ready(function() {
$("#button1").click(function(){
var dropd = $("#drop").val();
$.getJSON('data.php?id='+dropd)
So when I press button1 it should put the value from my selectbox in the variable dropd and send it to the php site data.php right?
So this is the code for my select box which should be alright.
<select id ="drop">
<option disabled selected>--Wähle Station aus--</option>
<?php
$records = mysqli_query($db, "SELECT idStation, Stationname FROM station WHERE fi_idFirma = $id");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['idStation']."'>" .$data['Stationname']."</option>";
}
?>
</select>
My problem is I think that i want several codes to start at once in jquery because when i press button1 it loads the value from dropd to data.php and than it should load an json file where i populate my graphs with.
$(document).ready(function() {
$("#button1").click(function(){
var dropd = $("#drop").val();
$.getJSON('data.php?id='+dropd)
function grab() {
return new Promise((resolve, reject) => {
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error);
}
})
})
}
grab().then((data) => {
console.log('Recieved our data', data);
let Zeit = [];
let Luft = [];
try {
data.forEach((item) => {
Zeit.push(item.Zeit)
Luft.push(item.Luftfeuchtigkeit)
});
let chartdata1 = {
labels: [...Zeit],
datasets: [{
label: 'Luftfeuchtigkeit',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: [...Luft]
}]
};
let ctx = $("#myChart1");
let barGraph = new Chart(ctx, {
type: 'line',
data: chartdata1
});
} catch (error) {
console.log('Error parsing JSON data', error)
}
}).catch((error) => {
console.log(error);
})
I know it looks a bit messy but i hope that you can help me in this case.
This is the data.php file where the select value should arrive.
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","usera01");
$id = isset($_GET['dropd']) ? $_GET['dropd'] : false;
if ($id) {
echo ($_GET['dropd']);
} else {
$id = 1;
}
$sqlQuery = "SELECT idDatenNr, Luftfeuchtigkeit, Lichtverhältnis, Bodenfeuchtigkeit,Temperatur, Zeit, fi_idStation FROM daten WHERE fi_idStation = '$id'";
$result = mysqli_query($conn,$sqlQuery);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
Maybe i made here an mistake.
Related
(I am new to Javascript and jQuery..) I have a dashboard and I want to display a map that shows the countries where participants of a particular event are coming from. With this, I opted with Jvector Map. I am having a hard time displaying the countries in the map, coming from my database.
dashboard.js
var mapData = {};
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 0.9,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 0
}
},
series: {
regions: [{
values: function() {
$.ajax({
url:"includes/sql/fetchcountries.php",
method:"GET",
data:mapData,
dataType:"json",
success: function(data){
mapData = data;
console.log(mapData);
}
})
},
scale: ["#1ab394", "#22d6b1"],
normalizeFunction: 'polynomial'
}]
},
});
fetch.php
<?php
require '../auth/dbh.inc.auth.php';
$id = $_SESSION['ntc_id'];
$stmt = $conn->prepare("SELECT DISTINCT(participants.p_country) FROM ntc_participants
INNER JOIN participants ON participants.p_id=ntc_participants.p_id_fk
WHERE ntc_participants.ntc_id_fk=?");
$data = array();
mysqli_stmt_bind_param($stmt, "i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0);
if($row = $result->fetch_assoc()) {
$data[] = [
$row['p_country'] => 0 ]; //the value 0 is just a placeholder.. The jvector map feeds on this format: "US":298, "SA": 200
}
echo json_encode($data);
?>
Could anyone be gracious enough to walk me through all the wrong things I'm doing in my code? Appreciate all the help! :)
Ajax is asynchronous, so You are creating the map before the data has been downloaded.
Initialize the map with empty values for Your region:
$('#world-map').vectorMap({
...
values: {}
...
});
Then, whenever You need to show the data, set it dynamically:
$.get("includes/sql/fetchcountries.php", function(data) {
var mapObj = $("#world-map").vectorMap("get", "mapObject");
mapObj.series.regions[0].setValues(data);
});
During the ajax invocation and data download maybe You can show a spinner (please look at beforeSend inside the jQuery full ajax documentation: https://api.jquery.com/jquery.ajax/).
Here is the reference for setValues:
http://jvectormap.com/documentation/javascript-api/jvm-dataseries/
http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018
This link will give you up-to-date stats for most common indicators via json - and then you can pluck whatever data that you like. I don't have all the code yet, as I am working on this today too.
This answers the question above whenever your database can also present JSON
document.addEventListener('DOMContentLoaded', () => {
console.log("loaded")
fetchCountryData()
})
function fetchCountryData () {
fetch('http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018')
//
.then(resp => resp.json())
.then(data => {
let country.id = data[1]
let indicator.id = data[1]
create-GDP-Data(country.id,indicator.id)
})
}
function create-GDP-Data(country.id,indicator.id){
let gdpData = ?
}
$('#world-map-gdp').vectorMap({
map: 'world_mill',
series: {
regions: [{
values: gdpData,
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
},
onRegionTipShow: function(e, el, code){
el.html(el.html()+' (GDP - '+gdpData[code]+')');
}
});
I'm creating page in PHP but when I use AJAX to send data, echo function start to printing data in console instead in DOM elements.
I want to add Quagga barcode reader to my page. Quagga is write in JS but my page is in php. So I have to use Ajax to send barcode result to my php code. And there is a problem. After sending data (POST) and using echo to display that on the screen, every data that echo should display are showing up in console. Not only data I send but whole page html code too. Even header('Location: ') doesn't work correctly. Because I'm sending readed code to barcodereaded.php where I put POST data inside SESSION var, and I try to echo that on the screen in different file barcoderesult.php but everytime data is printed in console log in barcode.php (which code is below). On every other subpage php echo and header functions works fine, only this one case causing troubles.
<div id="scanner-container"></div>
<input type="button" id="btn" value="Start/Stop" />
<script src="js/quagga.min.js"></script>
<script>
var _scannerIsRunning = false;
function startScanner() {
var barcode = {};
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
numOfWorkers: navigator.hardwareConcurrency,
target: document.querySelector('#scanner-container'),
constraints: {
size: 1920,
width: 200,
height: 480,
facingMode: "environment"
},
},
config: {
frequency: 5,
},
locator: {
patchSize: "x-large",
},
decoder: {
readers: [
"code_128_reader",
"ean_reader",
"ean_8_reader",
"code_39_reader",
"code_39_vin_reader",
"codabar_reader",
"upc_reader",
"upc_e_reader",
"i2of5_reader"
],
debug: {
showCanvas: true,
showPatches: true,
showFoundPatches: true,
showSkeleton: true,
showLabels: true,
showPatchLabels: true,
showRemainingPatchLabels: true,
boxFromPatches: {
showTransformed: true,
showTransformedBox: true,
showBB: true
}
}
},
}, function (err) {
if (err) {
console.log(err);
return
}
console.log("Initialization finished. Ready to start");
Quagga.start();
// Set flag to is running
_scannerIsRunning = true;
});
Quagga.onProcessed(function (result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: "green", lineWidth: 2 });
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "#00F", lineWidth: 2 });
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: 'red', lineWidth: 3 });
}
}
});
Quagga.onDetected(function (result) {
Quagga.stop();
barcode.code = result.codeResult.code;
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
});
}
// Start/stop scanner
document.getElementById("btn").addEventListener("click", function () {
if (_scannerIsRunning) {
Quagga.stop();
_scannerIsRunning = false;
} else {
startScanner();
}
}, false);
</script>
I just want to send readed barcode to other file to convert it into data I want to add to database (quantity of elements on the pallet, production date, etc.)
Look at this part of your code :
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
The success method tells what to do with the result of your ajax code.
And here you specifically tell to log the response (res) to the console.
Instead you can use the content of res to append it to your dom via your preferred Javascript solution (vanilla, jQuery,...).
With jQuery you could (if the result from your php code is some text):
$('#my-return-container').text(res)
I am trying to output data onto a chart using the chart.js lib. I have successfully pulled the data out I need and created the datasets but for some reason it just will not render onto the chart.
I have three files:
teamData.js
$(document).ready(function(){
$.ajax({
url : "http://localhost/acredashAdv/teamData.php",
type : "GET",
success :function(data){
console.log(data);
var score_1 = [];
var score_2 = [];
for (var i in data) {
score_1.push(data[i].score_1);
score_2.push(data[i].score_2);
}
var chartata = {
labels: [
"Strategic Development and Ownership",
"Driving change through others",
"Exec Disposition",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
],
datasets : [
{
label: "user 1",
backgroundColor: "rgba(0,0,0,0)",
borderColor: "#B71C1C",
data: score_1,
},
{
label: "user 2",
backgroundColor: "rgba(0,0,0,0)",
borderColor: "#B71C1C",
data: score_2
},
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'radar',
data: chartata,
animationEasing: 'linear'
});
},
error :function(data){
},
});
});
teamData.php
<?php
include 'config.php';
$query = sprintf("SELECT member_id, firstName, lastName, score_1, score_2, score_3, score_4, score_5, score_6, score_7, score_8 FROM members");
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
print json_encode($data);
?>
teams.php
<div style="max-width: 500px;">
<canvas id="mycanvas" class="container"></canvas>
</div>
On my console.log I can see the data is coming through correctly:
[{"member_id":"144","firstName":"Dan","lastName":"Barrett","score_1":"4","score_2":"2","score_3":"3","score_4":"5","score_5":"1","score_6":"3","score_7":"5","score_8":"4"},{"member_id":"145","firstName":"Jon","lastName":"Smith","score_1":"3","score_2":"4","score_3":"1","score_4":"2","score_5":"1","score_6":"2","score_7":"3","score_8":"4"},{"member_id":"146","firstName":"Dan","lastName":"Barrett","score_1":"1","score_2":"2","score_3":"1","score_4":"1","score_5":"4","score_6":"1","score_7":"4","score_8":"3"}]
But unless I am getting mixed up it will not draw out the data... I end up with an empty chart.
Maybe could be the version of your Chart.js, here is your code running:
https://jsfiddle.net/6xdvj5u3/
Using this version of Chart.js
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js
try to take the PabloMartinez's recommendation adding a header to your PHP file, before your print line:
header('Content-type: application/json');
print json_encode($data);
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I'm a newbie php/js/mysql programmer.
I'm trying to create a pie chart in highcharts using jquery, where the data is discovered dynamically via ajax from echo json_encode in php (includes a select query from mysql).
Two problems:
1) The pie chart has these trailing "Slice: 0 %" flares everywhere. Don't know where these are coming from, what it means, nor how to fix it.
2) Json is new to me. The json data feed appears to be getting through (firebug sees it), but the format looks like this. I'm trying to boil it down to name and percent number only. Like this ['Pages', 45.0] but not sure how. Is this done in the json/php or should it be done in the sql query itself?
[{"contenttype":"BLOGPOST","count(*)":"2076"},{"contenttype":"COMMENT","count(*)":"2054"},{"contenttype":"MAIL","count(*)":"29448"},{"contenttype":"PAGE","count(*)":"33819"}]
Any help much appreciated
The highcharts js file is here:
//Define the chart variable globally,
var chart;
//Request data from the server, add it to the graph and set a timeout to request again
function requestData() {
$.ajax({
url: 'hc1.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function(){
//Create the test chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'mycontainer2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
events: {load: requestData}
},
title: {text: 'Content Types in Wiki'},
tooltip: {formatter: function() {return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
//color: Highcharts.theme.textColor || '#000000',
//connectorColor: Highcharts.theme.textColor || '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Content',
data: []
}]
});
The php file is here:
<?php
// Set the JSON header
header("Content-type: text/json");
// Connect to db
include('dbconnect.php');
// Count version 1 of content types of interest
$query = ("select contenttype, count(*)
from CONTENT
where version='1' and contenttype='page' or contenttype='comment' or contenttype='blogpost' or contenttype='mail' or contenttype='drafts'
group by CONTENT.contenttype;");
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// create a php array and echo it as json
//$row = mysql_fetch_assoc($result);
//echo json_encode($row);
$results = array(); while ( $row = mysql_fetch_assoc( $result )) { $results[] = $row; }
echo json_encode($results);
?>
First problem, how do you get your data into a format that highcharts is going to accept (namely arrays of arrays, [[name,percent],[nextname,percent],etc])? I would handle this in your PHP:
<snip>
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$total = 0;
$results = array();
while ( $row = mysql_fetch_assoc( $result )) {
$results[$row["contenttype"] = $row["count()"];
$total += $row["count()"];
}
$forHigh = array();
foreach ($results as $k => $v) {
$forHigh[]=array($k,($v/$total) * 100); // get percent and push onto array
}
echo json_encode($forHigh); // this should be an array of array
Now that our JSON returned structure is ready for HighCharts, we just need to call the plot creation once after our JSON call to create the plot. I would do it in the success callback of the $.ajax call.
$.ajax({
url: 'hc1.php',
success: function(jsonData) {
chart = new Highcharts.Chart({
<snip>
series: [{
type: 'pie',
name: 'Content',
data: jsonData
}]
<snip>
},
cache: false
});