I am trying to post an AJAX request to a PHP class function, following the advice posted in this topic: jQuery Ajax POST example with PHP
I don't know if its possible to post AJAX query directly to a class function, so I wrote a small 'controller' type file to process the data and then call the class function.
product_controller.php:
switch ($_GET['action'])
{
case "create":
$product_name = isset($_POST['bar']) ? $_POST['bar'] : null;
$product = new Product($DB_con);
$product->new_product($product_name);
break;
case "update":
//Stuff
break;
case "delete":
//Stuff
break;
}
And this is the actual class file:
class.product.php
<?php
class Product
{
private $db;
private $error;
function __construct($DB_con)
{
$this->db = $DB_con;
}
//New product function
private function new_product($product_name)
{
try
{
//Try to insert the data into the database
$stmt = $this->db->prepare("INSERT INTO products(product_name) VALUES(:product_name)");
$stmt->bindParam(":product_name", $product_name);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
And this is the actual form/jquery:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
</div>
<script>
var request;
$("#foo").submit(function(event){
event.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "product_controller.php?action=create",
type: "post",
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
console.log("Success!");
console.log(serializedData);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occurred: "+ textStatus, errorThrown);
});
request.always(function () {
$('#spinner_test').show();
$inputs.prop("disabled", false);
});
});
</script>
As far as I'm aware, the AJAX request is fine, when the form is submitted the "success" message is shown, but the data is not being inserted into the database, so my guess is the problem is in the class/controller files, but I can't see what it is?
I have also tried following the advice posted in a couple of other topics but to no avail, so any help with this is greatly appreciated.
EDIT: dbconfig.php
<?php
session_start();
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "fcrn";
try
{
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
include_once 'class.product.php';