I am posting some variables to a php file. The variables are coming from a form. So, when I put the variables in the form, they are posted to the php file. However, when I want to actually use the variables, they come as an undefined index. I have to use json_encode and retrieve the variables using the post call back function. But I want the variables to work when using the get function/method. I am a beginner so please go easy on me.
I have tried to put the post function before the get get function. I have tried to use json_decode I have tried to using $_REQUEST instead of $_POST If json_encode is JUST used to echo the $_POST variable, then it will show in the call back 'success' function. But I want the $_POST variables to be used generously through out the code and show when the get function is used. Looking through other peoples answers, I see that apparently the index for the $_POST is undefined/null. But my code sends the form to the PHP, so it shouldn't be null.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<h1>Combining HTML, JS & PHP</h1>
<form id="IPLAnalyisForm" method="post">
<div>
<select name="opponent">
<option name = "Sunrisers Hyderabad" value="Sunrisers Hyderabad">Sunrisers Hyderabad</option>
<option name = "Royal Challengers Bangalore" value="Royal Challengers Bangalore">Royal Challengers Bangalore</option>
<option name = "Kolkata Knight Riders" value="Kolkata Knight Riders">Kolkata Knight Riders</option>
<option name = "Delhi Daredevils" value="Delhi Daredevils">Delhi Daredevils</option>
<option name = "Kings XI Punjab" value="Kings XI Punjab">Kings XI Punjab</option>
<option name = "Rajasthan Royals" value="Rajasthan Royals">Rajasthan Royals</option>
</select>
<input onclick="getData()" type="submit" name="submit" id="submit" value="submit parameters"/>
</div>
</form>
<button onclick="getData()">Submit query</button>
<div id = "result"></div>
<script type="text/javascript">
</script>
</body>
<script src="IPL.js"></script>
</html>
JavaScript (with some Jquery) var obj, dbParam, xmlhttp;
$(document).ready(function() {
$('#IPLAnalyisForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'IPL.php',
data: $(this).serialize(),
success: function()
{
// var jsonData = JSON.parse(response);
// alert(jsonData);
}
});
});
});
function getData() {
obj = {"table": "batting", "limit": 5};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "IPL.php?x=" + dbParam, true);
xmlhttp.send();
}
PHP CODE
$opponent = $_POST['opponent'];
echo $opponent;