So I am trying to insert data from a form using JQuery .ajax method. In the developer tools I see that the request is send to my process.php file, but I can't add the data to the database.
Javascript
$( document ).ready(function() {
console.log( "ready!" );
$("#submit").submit(function(e) {
var url = "process.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: "process.php",
data: $("#submit").serialize(), // serializes the form's elements.
success: function(data){
alert("Data is send successifully!"); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Now I use my custom classes and methods.
This is the insert()
method from my db.class.php
public function insert($fName, $lName, $nickname){
$query = "INSERT INTO users (first_name, last_name, nickname)
VALUES ($fName, $lName, $nickname)";
return $this->_conn->query($query);
}
now I have user.class.php with add()
method
public function add($fName, $lName, $nickname){
$db = new db();
$db->insert($fName, $lName, $nickname);
}
Finally a process.php
file. I'm sending my request there.
<?php
require_once 'classes/user.php';
require_once 'classes/db.php';
$user = new user();
$user->add($_POST['fName'], $_POST['lName'], $_POST['nickname']);
?>