I'm trying to use Ajax and PHP to send my input data database without refreshing the page. But I am getting this error and it's been couple of hours of me solving this issue but I still can't. Please help me. Thanks!
This is my index.php file where I placed my ajax script and html codes.
$(document).ready(function() {
$('#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'insert.php',
method: 'post',
data: $('form').serialize(),
dataType: 'text',
success: function(strMessage) {
$('#result').text(strMessage);
$('#myForm')[0].reset();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5 class="alert-heading">
ADD INFORMATION
</h5>
<hr>
<form id="myForm" method="post" action="">
<div class="form-group">
<label>Full name</label>
<input type="text" autofocus="on" class="form-control" name="fullname" placeholder="Enter your name here" required>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" name="address" placeholder="Address" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="alert alert-success" role="alert" id="result"></div>
And here's my insert.php file
<?php
try {
include_once 'classes/Db.php';
$fullname = addslashes($_POST['fullname']);
$address = addslashes($_POST['address']);
$sql = "INSERT INTO users (null, fullname, address) VALUES ('$fullname', '$address')";
$stmt = $conn->prepare($sql);
$stmt->execute();
} catch (PDOException $e) {
echo "ERROR IN INSERTING DATA! : " . $e->getMessage();
}
?>
And my classes/Db.php file
<?php
$localhost = 'localhost';
$dbname = 'test_icon';
$username = 'root';
$password = '';
try {
$sql = 'mysql:localhost=' .$localhost. '; dbname=' .$dbname;
$stmt = new PDO($sql, $username, $password);
$conn = $stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "CONNECTION FAILED: " .$e->getMessage(). '<br/>';
die();
}
?>