Reputation: 303
I am trying to insert data into a database with ajax. The problem is that everything works excepting the insertion of data in the database. When I click the submit button I get the proper message "You have been subscribed" just that it doesn't insert the data in the database. And don't understand exactly why.
I have dbconn.php
<?php
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
?>
common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($name)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
subscribe.php
HTML
<form name="subscribe" class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
AJAX
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
Upvotes: 1
Views: 929
Reputation: 68476
Remove the quotes and substitute with backticks here
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed')
^ ^
Upvotes: 4