Reputation:
Intro I am doing an insert into the database using Ajax, PHP, and SQL.
Error: alert(data)
says undefined:first_name.....I thought I defined using $first_name = strtoupper($_POST['first_name'])
witin the add.php
file.
Index.php
<script type="text/javascript">
$(document).on('click','#update_btn',function (){
$.ajax({
type:'POST',
url:'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
updated: $("#updated").val(),
},
success: function(data){
alert(data);
if (data=='ADD_OK') {
location.reload();
} else {
alert('something wrong');
}
}
})
});
<form id="form1" class="form-inline" method="post" action="">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<select name="position" id="multiple-select-optgroup-default2" class="custom-select">
<option selected>Admin</option>
<option value="Teacher">Teacher</option required>
<option value="Staff">Staff</option>
</select>
<input type="hidden" name="updated" value='<?php echo date("Y-m-d");?>' >
<button class="btn btn-success btn-sm active" type="submit" name="save" id="update_btn"><span class="glyphicon glyphicon-plus-sign"></span> Save</button>
</form>
</script>
Add.php
<?php
$first_name = strtoupper($_POST['first_name']);
$last_name = strtoupper($_POST['last_name']);
$position = strtoupper($_POST['position']);
$updated = $_POST['updated'];
$stmt = $conn->prepare("INSERT INTO employees (first_name, last_name, position, updated) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $first_name, $last_name, $position, $updated);
$add = $stmt->execute();
if($add) {
echo "ADD_OK";
}
?>
Upvotes: 1
Views: 2225
Reputation: 674
it's undefined:first_name given an error because you don't give indexing in form but you use in jquery. show use HTML code like this and check.
<input type="text" name="first_name" id="first_name" placeholder="First Name" required>
<input type="text" name="last_name" id="last_name" placeholder="Last Name" required>
<select name="position" id="position" class="custom-select">
<option selected>Admin</option>
<option value="Teacher">Teacher</option required>
<option value="Staff">Staff</option>
</select>
<input type="hidden" name="updated" id="updated" value='<?php echo date("Y-m-d");?>' >
and debug with your jquery code.
Upvotes: 4
Reputation: 1723
Here is your piece of code of jQuery:
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
updated: $("#updated").val(),
},
In this you are trying to get value via id of textbox as you mentioned
$("#first_name").val()
Change your code to this :
data: {
first_name: $('input[name="first_name"]').val(),
last_name: $('input[name="last_name"]').val(),
position: $('input[name="position"]').val(),
updated: $('input[name="updated"]').val(),
},
Hope it will help you.
Upvotes: 2