I'm trying to insert select-option values into my database using Ajax, but it will keep inserting a "0" to the database rather than the actual value or it will return as "null" value. I'm able to successfully insert select-option value without the Ajax code however. But I am able to insert values using a text input field with the Ajax code. The name
values for my select and text input are the same (as they both should insert the same data to the database). When the select-option is hidden, the text input will insert its value to the database and vise versa. So my main question is, how do I get the actual value for the select-option to be inserted to the database (because all it inserts is "0" or returns with an error of "null")?
This is the html for the form, which includes the select-option and text input field which both carry the name="toctquant"
attribute:
<form method="post" action="tocarthand.php?strid=<?php echo $prodtab->strid; ?>&prodid=<?php echo $prodtab->prodid; ?>" id="toctform">
<select name="toctquant" id="quantsel" class="qinp">
<?php $q = $prodtab->quant; ?>
<?php for ($q = 1; $q <= 10; $q++): ?>
<option value="<?php echo $q; ?>"><?php echo $q; ?></option>
<?php endfor; ?>
<?php if ($q > 10): ?>
<option value="<?php echo $q; ?>"><?php echo $q; ?>+</option>
<?php endif; ?>
</select>
<input type="text" name="toctquant" class="inphid qinp">
<button type="submit" name="tocartbut" id="tocartbut">Add to Cart</button>
</form>
<div id="result"></div>
This is the Ajax code I am having problems with. It will only submit value for text input but not for the select-option value:
$("#toctform").submit(function(e) {
var data = $("#toctform").serialize();
$.ajax({
data: data,
type: "post",
url: "tocarthand.php",
success: function(data){
alert("Data Save: " + data);
}
});
});
EDIT: Included php code for file tocarthand.php
$strid = (int)$_GET['strid'];
$prodid = (int)$_GET['prodid'];
$toctprodid = (int)$_GET['prodid'];
$toctuserid = $_SESSION['userid'];
$toctquant = $_POST['toctquant'];
$stmt = $conn->prepare("INSERT INTO tocart (toctprodid, toctuserid, toctquant) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $toctprodid, $toctuserid, $toctquant);
$stmt->execute();
$stmt->close();
header('Location: itempage.php?strid='.$strid.'&prodid='.$prodid.'&insert=success');
$conn->close();