i’m a beginner with databases, ajax and php. I want a user to make a choice from a list with checkboxes and when a choice is made, the choice is sent to the database. I have this code:
<form method="post" action="post" class="registry-form">
<div class="list">
<div>
<input id='label-1' type='checkbox' />
<label for='label-1'>
<h3>
<span>Studio Noos Mom Bag | Urban Woollish</span>
<span>
<br />
<a href="https://www.degeleflamingo.com/collections/juweeltjes-voor-mama/products/studio-noos-mom-bag-all-black-rib?variant=31254237020230" target="_blank">Bekijk product</a>
</span>
</h3>
</label>
</div>
...
</div>
</form>
<input type="submit" class="gift-btn" value="submit choice" />
<script>
$(document).ready(function() {
$(".list div input[type=checkbox]").change(function() {
$(this).parent().toggleClass('checked');
});
$('.registry-form').submit( function(e) {
e.preventDefault();
var geboortelijst_beschrijving = $(".list .checked h3 span:first-child").html();
console.log(geboortelijst_beschrijving);
$.ajax({
type: "POST",
url: "post.php",
dataType:'json',
data: geboortelijst_beschrijving,
success: function(data){
$(".list .checked").addClass('taken');
}
});
return false;
});
});
</script>
post.php:
<?php
header("Content-Type: application/json", true);
$conn = mysqli_connect("localhost","root","root","geboortelijst");
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$geboortelijst_beschrijving = $_POST['geboortelijst_beschrijving'];
//$geboortelijst_beschrijving = mysqli_real_escape_string($conn, $_POST['geboortelijst_beschrijving']);
if(mysqli_query($conn, "INSERT INTO geboortelijst(geboortelijst_beschrijving, geboortelijst_status)
VALUES('" . $geboortelijst_beschrijving . "', '1')")) {
echo '1';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
?>
The response i get from post.php is always 200 0K, but i have no idea why the “geboortelijst_beschrijving” is not being sent to my database. This value is empty and i always and only get “1” (which of course comes from geboortelijst_status).
Anybody have some insights?
2
Answers
$(".list .checked h3 span:first-child")
is not the correct selector. This is looking for anh3
that’s contained in the checkbox element, but checkboxes aren’t containers.You want the
h3
that’s a sibling of the checkbox, not a descendant, and then find the firstspan
in that.Something like this