I'm using chart.js to generate charts on my page.
However I want these charts to be populated by my SQL database.
I'm able to get my data out of my database, but I won't draw the chart
I got a canvas on my main page called "OmzetChart" , this is where the chart should come.
<script>
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = data;
//alert(JSON.stringify(data));
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
</script>
The page of GetData.php results in the following (This is what I need, just want it into my chart):
[{"dag":"23","0":"23","uur":"13","1":"13","SomOmzet":"23.00","2":"23.00"},{"dag":"23","0":"23","uur":"18","1":"18","SomOmzet":"2.50","2":"2.50"}]
Getdata.php:
<?php
include ("../PDO.php");
$conn = DatabasePDO::getInstance();
$sql = "SELECT DATEPART(DD, receiptdatetime) as dag ,DATEPART(hh, receiptdatetime) as uur, ISNULL(abs(cast(sum(NetAmount) as decimal (10,2))),0) as SomOmzet FROM ReceiptLine a , Receipt b, ReceiptLineDetail c
where a.LineType = 200 and a.receiptID = b.receiptid and a.receiptlineID = c.receiptlineID
group by DATEPART(DD, receiptdatetime), DATEPART(hh, receiptdatetime)";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$list[] = $row;
}
$conn = null;
echo json_encode( $list );
?>
json_encode() produces a JSON string. You need to parse this with JSON.parse() before you can use it.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = JSON.parse(data); //parse the data into JSON
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
Also, using $.ajax() method's dataType parameter, you can leave this parsing to jQuery.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
dataType: 'json', //tell jQuery to parse received data as JSON before passing it onto successCallback
success: function (data) {
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: data //jQuery will parse this since dataType is set to json
});
}
});
Related
I am trying to pass some basic data using JavaScript and PHP.
The PHP is not receiving any data.
I have the following JavaScript code:
var formData = new FormData();
formData.append("action", "save-game");
formData.append("title", title);
formData.append("players", players);
formData.append("noTables", noTables);
formData.append("maxPPT", maxPPT);
formData.append("rounds", roundChart);
$.ajax({
url: "/static/apps/games.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
if (response.success) {
alert("Saved Game Setup");
} else {
alert("Failed to save game setup, "+response.reason);
console.log(response.reason);
}
}
})
And I have stripped the PHP down to the bare minimum but it is still not receiving the data
header("Content-Type: application/json");
$action = $_POST["action"];
echo json_encode(array(
'success' => false,
'reason' => $action,
));
The $action variable in PHP is returning null
try to build data like here
var buildData = function( _action, _title, _players, _noTables, _maxPPT, _rounds){
var data = {};
data.action = _action;
data.title = _title;
data.players = _players;
data.noTables = _noTables;
data.maxPPT = _maxPPT;
data.rounds = _rounds;
return JSON.stringify(data);
}
var _json = buildData("save-game", title, players, noTables, maxPPT, roundChart);
I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)
I want to send data through an array
This transmitter code:
<script type="text/javascript">
$(function() {
$(".cat_button").click(function() {
var element = $(this);
var test = $("#cou").val();
var test2 = $("#category2").val();
var data = [
{data:test},
{data:test2}
];
if(test=='' || test2=='.....')
{
alert("fill data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading...</span>');
$.ajax({
type: "POST",
url: "insert2.php",
data: {data: data},
cache: false,
success: function(response){
console.log(response);
}
});
}
return false;
});
});
</script>
This code reception:
print_r($_POST['data']); // dumps an array
$course = $_POST['data'][0]['data'];
$category = $_POST['data'][1]['data'];
$insert_new_cou = mysql_query("insert into course (name,cat_id) values ('$course','$category')") or die($insert_new_cou."<br/><br/>".mysql_error());
But show me the following error:
Cannot use string offset as an array
I think the solution using Jtgson but I do not know how to use it
It can be done by JSON encoding your array of objects. In the $.ajax call:
...
url: "insert2.php",
data: {data: JSON.stringify(data)},
...
On the PHP side use json_decode() to get an array of objects from the JSON string:
$data = json_decode($_POST['data']);
$course = $data[0]->data;
$category = $data[1]->data;
index.html:
Function drawChart() {
var jsonData = $.ajax({
url: "server.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
}
server.php:
$SQLString = "SELECT (...)'".$_POST['value']."' (...)
$result = mysql_query($SQLString);
(...)
$data[$i] = array(...)
echo json_encode($data);
So, index.html get data from server.php right?
Can I send some values to server.php which are important to do the query before index.html do the jsonData...etc? How?
Thanks :)
Example of a query parameter:
var jsonData = $.ajax({
url: "server.php?someQuery=" + query,
dataType: "json",
async: false
}).responseText;
You can send using post method via ajax. Here is a JQuery example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
http://api.jquery.com/jQuery.ajax/
you can use a library that will do it automatically for you, using phery http://phery-php-ajax.net, in your case it would be:
the event phery:json will deal with the JSON sent from the server
var remote = phery.remote('data', {'argument': 'you want to send'}, {'target':'server.php'}, false);
remote.bind('phery:json', function(event, obj){
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
});
remote.phery('remote'); // call the remote AJAX function
in your server.php
function data($data){
$r = new PheryResponse;
// $data['argument'] will have 'you want to send'
$SQLString = "SELECT (...)'".$_POST['value']."' (...)"
$result = mysql_query($SQLString);
(...);
$data[$i] = array(...);
return $r->json($data);
}
Phery::instance()->set(array(
'data' => 'data'
))->process();
I need to get the distance between two points from JavaScript to PHP using Google Maps. Below is my function to get the distance and post no problems. Now, how can I send the arrays (i.e. volunteerDist and tvid) to another php file (i.e. distanceToDb.php) and what should be the code of my distanceToDb.php to get these data? Thanks! Actual codes is highly appreciated.
<?php
function getFDistance(lat, lng, vlat, vlng, vid) {
var eventlocation = new GLatLng(lat, lng);
var volunteerDist = new Array();
var tvid = new Array();
var volunteerlocation;
for(i=0;i<lat.length;i++) {
tvid[i] = vid[i];
volunteerlocation = new GLatLng(vlat[i], vlng[i]);
volunteerDist[i] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
}
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: function(data){
alert("Successful");
},
dataType: "json"
});
}
?>
I've passed arrays and objects using JSON in javascript, let's say through a jquery.post call:
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: successfunction,
dataType: "json"
});
Then, in the php file you just do this:
$js_data_arr = json_decode($_POST['data']);