I'm trying to send a JavaScript variable to a PHP script, use the variable in my SQL statement, and then send the results back to JavaScript.
JavaScript:
// Sending a variable to PHP script
var variableToSend = '30';
$.post('myPHPscript.php', {variable: variableToSend});
// Using the variable from earlier, run PHP script to get results
var data_from_ajax;
$.get('http://www.mywebsite.com/myPHPscript.php', function(data) {
data_from_ajax = data;
});
// Display results on the document
var displayResult = document.getElementById('displayResult');
displayResult.innerHTML = data_from_ajax;
PHP:
<?php
// Connection stuff
$conn = new mysqli($servername, $username, $password, $dbname);
// Get the sent variable
$variable = $_POST['variable'];
// Run SQL statement
$sql = "
SELECT column
FROM myDatabase
WHERE id=$variable
";
$result = $conn->query($sql);
// Send results back to JavaScript
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row["column"];
}
?>
The reason that JS is calling a PHP script is because I used an event listener in JS to determine the variable that I want to send. The variableToSend varies every time depending on what was clicked, but I have set it to some random number here.
I'm aware that the problem lies in sending variables to PHP scripts in the JavaScript, but I'm unsure how else I can do this, besides using .post and .get.
I also considered using an AJAX call, but I wasn't sure how that would work.
Thank you for any pointers.