Reputation: 9
I have an HTML form that contains a number of checkboxes. When the user clicks the submit button the checked array is posted and a query runs based on that result. I have a button allowing the user to save their result, when they insert their saved result into another table. But this means I need to post the form result again which it doesn't allow me to do. How would I fix this?
Upvotes: 1
Views: 109
Reputation: 2625
PHP Code
<?php
if (isset($_POST['submit']) && isset($_POST['sport'])) {
$class = $_POST["sport"];
foreach ($class As $key => $value) {
$query = "SELECT *
FROM sport b
join sport a
on a.Tag = b.Name
where a.SportID<> b.SportID and a.Tag = '$value'";
$result = mysqli_query($con, $query) or die("Invalid Query");
while ($row = mysqli_fetch_assoc($result)) {
echo "* $row[Name]\n";
}
}
} else if (isset($_POST['saved'])) {
$arr_class = $_POST["sport"];
foreach ($arr_class As $key => $newvalue) {
$query2 = "INSERT INTO save (Username, Name)
SELECT '$username', b.Name
FROM sport b
JOIN sport a
on a.Tag = b.Name
where a.SportID <> b.SportID
and a.Name = '$newvalue'";
$result2 = mysqli_query($con, $query2) or die('Result could not be saved!');
}
echo 'Result saved!';
}
JS Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.submit-button').click(function (ev) {
var $item = $(this);
var formData = $('form').serialize();
$.ajax({
data: formData+'&submit=submit',
url:'test1.php',
type: "POST",
dataType: "html",
success:function (data) {
console.log(data);
if(confirm('You want to save \n'+data+ ' as your sport')){
$.ajax({
data: formData+'&saved=saved',
url:'test1.php',
type: "POST",
dataType: "html",
success:function (data) {
console.log(data);
}
});
}
}
});
});
});
</script>
HTML Code
<form id="form" action="" method="post">
<input type="checkbox" name="sport[]" value="Football">Football<br>
<input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
<input type="checkbox" name="sport[]" value="Golf">Golf<br>
<input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
<br> <input type="button" class="submit-button btn btn-info" name="submit" value="submit">
<input type="submit" style="display:none;">
</form>
Upvotes: 1