-2

I have the following scenario running:

graph.html --> uses ChartJS to display a line graph and imports graph.js

<html>
<head>
<title>ChartJS - LineGraph</title>
</head>
<body>
<div class="chart-container">
  <canvas id="mycanvas"></canvas>
</div>
<form name="form" action="" method="get">
<input type="text" name="input" id="subject" value="">
</form>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
</body>

graph.js --> makes a AJAX call on the graph.php file to get the data and format it.

$(document).ready(function(){
$.ajax({
url : "/graph.php",
type : "GET",
success : function(data){
console.log(data);
...
var LineGraph = new Chart(ctx, {
    type: 'line',
    data: chartdata
  });

graph.php --> Calls mysql database to get data

$var = $_GET['input'];
$query = sprintf("SELECT $var FROM wetter");

//execute query
$result = $mysqli->query($query);

I like to change the SELECT statement in the php-file by entering a new SELECT-statement in a input field of the .html file. If I put the normal $_GET[] method into the .php it will not find the input value from the .html file.

How can I parse the input value from the .html to the .php when there is a Javascript file in between? Do I need to change something in my scenario?

cuci
  • 11
  • 4

1 Answers1

0

From the code you've shown, it doesn't look like you're passing the input value along with your ajax request, you should add something like

$.ajax({
   url : "/graph.php",
   type : "GET",
   data : {input : $('#subject').val()}, <-- added this
   success : function(data){

In order to be able to see the value in $_GET['input'] on the php side.

But there is another issue I believe, your ajax request is sent as soon as your document is ready ($(document).ready(function(){), but at that time your input is most likely going to be empty. You probably want to change it to $('form[name="form"]').on('submit',function(event){event.preventDefault(); ...}), assuming your form only does that one thing (display a graph according to the input)

Pepper
  • 587
  • 4
  • 12
  • thanks a lot, but how can I access the data in the php then? $var_name =$_GET['subject']; seems not to work. – cuci Sep 14 '19 at 09:31
  • I had apostrophes around 'input' in the ajax data, my apologies... To get it in php, if you defined `data : {input : $('#subject').val()}` it should be in `$_GET['input'] `, just replace `input` by `subject` in the ajax data if you want the key to be `$_GET['subject']` – Pepper Sep 14 '19 at 14:26