I’m new to jQuery and I keep getting undefined as data when I submit the form. I looked online and tried serialize(), the $.ajax function, $.post function, amongst other methods to no avail.
I’m trying to accomplish a form submit without a page refresh. The code works fine if I comment out the script to remain on the page after form submission.
index2.php
<script>
function newlock() {
$("#new-lock").load("new-lock.php");
}
</script>
<h3>Lock Settings</h3>
<div>
<a href="#" onclick="newlock();">New Lock</a>
</div>
//code in between
<div id="tabs-1">
<div id="new-lock"></div>
</div>
insert_new_lock.php
require "connect.php";
$name = $_POST['name'];
echo $name;
$IP = $_POST['IP'];
echo $name;
$sql="INSERT INTO door_lock (lock_IP, lock_name)
VALUES
('$name','$IP')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
mysql_close($conn);
?>
new-lock.php
<!doctype html>
<html lang="us">
<h2 align = "center"> Please enter information for the new lock </h2>
<table border="0" align= "center">
<form id="newlockform" action="insert_new_lock.php" method="post">
<tr><td>Lock Name:</td> <td><input type="text" name="name"></td></tr>
<tr><td>Lock IP:</td> <td><input type="text" name="IP"></td></tr>
<tr><td><input type="reset" value="Clear"> <input type="submit" name="submitted" value="Submit"></td></tr>
</form>
</table>
</html>
<script>
$("#newlockform").submit(function() {
var name = $("#name").val();
var IP = $("#IP").val();
var dataString = 'name=' + name + '&IP=' +IP;
$.post('insert_new_lock.php', dataString, function(data) {
$("#tabs-1").html(data).fadeIn('100');
$('#name,#IP').val('');
}, 'text');
return false;
});
</script>
Any help would be appreciated! 😀
You do not have any
idset on your form fields, sois going to return null, which you then submit as an empty string. The form fields should loo like
for your JS code to work.