I am attempting to write an application that interacts with a library and gets values from it, and I can't seem to figure out how to get a php script to execute when a button is clicked.
Index.html
Chapter: <input type="text" name="chapter"><br>
Section: <input type="text" name="section"><br>
Problem: <input type="text" name="problem"><br>
<input type="button" class="button" name="insert" value="Get Input"
onClick="doStuff()"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
function doStuff()
{
var v1 = document.getElementById('chapter').value;
var v2 = document.getElementById('section').value;
var v3 = document.getElementById('problem').value;
$.ajax({
type: "POST",
url: "get-data.php",
data: {chapter:v1,section:v2,problem:v3},
success: function(data) {
alert(data);
}
});
}
</script>
get-data.php
<?php
function doit()
{
$chapter=$_GET['chapter'];
$section=$_GET['section'];
$problem=$_GET['problem'];
$command = "python proc.py init $chapter $section $problem";
$output = exec($command);
echo $output;
}
doit()
?>
the python script is confirmed to be working, and the php script is confirmed to be working when executed by using <form action="get-data.php">
but it always redirects to a simple page where the output is echo
to.
You should receive values in php page by using $_POST not $_GET, because in ajax request that you wrote you are using type = "POST".
You are trying to get the variables as if they were passed to the PHP by GET request while using POST, change the PHP to the following. Use filter_input
to apply some safeguards:
<?php
function doit()
{
$chapter=filter_input(INPUT_POST, 'chapter');
$section=filter_input(INPUT_POST, 'section');
$problem=filter_input(INPUT_POST, 'problem');
$command = "python proc.py init $chapter $section $problem";
$output = exec($command);
echo $output;
}
doit();
?>
Note: These safeguards are probably not enough, you should make sure that no dangerous keywords can be passed to the script.
As others have answered, AJAX sends data using HTTP/POST, while you are using $_GET.
However, if for some reason (like manual testing) you want the page to handle both parameters from a POST and a GET request, you can use $_REQUEST instead of $_GET.