I am trying to apply oop concept on PHP to have a contact us form that works with ajax. The response gives me false that means whenever I submit the form alert message appears 'couldn't send your request' and I couldn't find the specific problem. I have a class for the connection to the database, and another class to send the form to the database and the form itself is a part of the home page. These are my codes after some edits:
1-the connection page and class
<?php
class db_conn {
private $servername;
private $username;
private $password;
private $dbname;
protected function connect(){
$this->servername="localhost";
$this->username="root";
$this->password="";
$this->dbname="class_on_click";
$conn=new mysqli($this->servername, $this->username, $this->password, $this->dbname);
return $conn;
}
}
?>
2-The class and page to insert data to the database:
<?php
require_once "db_conn.php";
class contact_conn extends db_conn{
public function sendForm(){
if(isset($_POST['submit'])){
$name=$_POST['name'];
$email=$_POST['email'];
$id=$_POST['id'];
$message=$_POST['message'];
$connection = $this->connect();
$send= mysqli_query($connection, "insert into contact_us_form(name, id, email, message) values('$name','$id','$email','$message')");
if($send){
$response['success'] = true;
}
else{
$response['success']= false;
}
}
$connection->close();
}
}
?>
3-The part of code on the home page where the form is there and the ajax function too:
$("#contact-form").on("submit",function(e){
e.preventDefault();
var name = document.getElementById("name").value;
if(name.length==' '){
$("#name").css("border","2px solid red");
}
var id = document.getElementById("id").value;
if(id.length !== 7 || /[a-z]/gi.test(id) || /[\W]/g.test(id)){
$("#id").css("border","2px solid red");
}
var email = document.getElementById("email").value;
if (!((email.indexOf(".") > 0) && (email.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(email)){
$("#email").css("border","2px solid red");
}
var message = document.getElementById("message").value;
var required = 30;
var left = required - message.length;
if(left > 0){
alert(left+' more characters are required to send the message.');
$("#message").css("border","2px solid red");
}
else
{
var sendData = {name:name, id:id, email:email, message:message};
$.ajax({ url: "contact_conn.php", type: "POST", data: sendData, success: function(response)
{
if(response == true){
alert('Thank you! We will contact you soon.');
}
if(response == false){
alert("couldn't send your request.");
}
}
});
}
});