I have a table with 20 buttons. I want to assign a php variable the same value as the button I press, something I figured would be easy but it's been two hours now without success.
foreach ($soccerseason->getTeams() as $team) {
if (($i % $number_per_row) == 0) {
echo '<tr>';
}
?>
<td style="background-image:url(<?php echo $team->crestUrl ?>);background-position: 50% 50%;background-repeat:no-repeat;background-size:100px 100px; width: 110px; height: 110px;">
<form action="JavaScript: showQuiz()" method="post" value="<?php echo $team->name ?>">
<button class="tableButton" value="<?php echo $team->name ?>"style="width:110px; height:110px"></button>
</form>
</td>
<?php
if (($i % $number_per_row) == $number_per_row - 1) {
echo '</tr>';
}
$i = $i + 1;
}
Say I want to echo the value of the button I press - how would you proceed? The function of the javascript is currently to hide/show different divs, nothing else. Thanks
One solution is to make the button call a Javascript function, that uses JQuery's ajax request to do whatever you want to do in PHP, and have the PHP output the name, which the Javascript will receive back, and change the div, or span to. I think the code would look something like this(in the Javascript):
function ajaxRequest(buttonName){
var data = "name=" + buttonName;
$.ajax({
url: "showPHP.php",
type: "post",
data: data
}).done(function(data){
document.getElementById("currentButtonSelectedDiv").innerHtml = data;
});
}
I am pretty sure you might need some other flags, but that is the basics of the javascript. The PHP would look something like this:
<?php
// Your php stuff
echo $_POST['name'];
?>
You generally keep the name attribute on the buttons the same as you have done, but vary the value.
Without seeing the rest of the table, you could potentially wrap the whole table in the form tag also.
<form method="post" action="readValue.php">
...
<button type="submit" name="teamName" value="team1">team1</button>
<button type="submit" name="teamName" value="team2">team2</button>
<button type="submit" name="teamName" value="team3">team3</button>
...
</form>
When the data is posted back, read the teamName value from the $POST variable.
<?php
$teamName = $POST["teamName"];
It's not entirely clear what you are doing with the javascript, but you can attach event handlers when the buttons are clicked also.