0

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';
Community
  • 1
  • 1
Aaranihlus
  • 143
  • 2
  • 13
  • You echo out an error message from your method (bad practice) Instead, return a status and in your switch check for an error message. When you are AJAXing, echo's tend to get lost if you are not careful – RiggsFolly May 14 '17 at 17:25
  • Or instead of this `console.log("Success!"); console.log(serializedData);` echo the returned data `console.log("Success!"); console.log(response);` – RiggsFolly May 14 '17 at 17:26
  • Also change your private function to public – Rotimi May 14 '17 at 17:39
  • @RiggsFolly Thanks for the info, I have updated my class based on your advice! – Aaranihlus May 14 '17 at 17:47
  • @Akintunde Thanks, I have changed the function from private to public, however the issue still remains – Aaranihlus May 14 '17 at 17:48
  • Where does the variable dbconn come from in your switch case?? – Rotimi May 14 '17 at 18:06
  • Oops, my bad, it is included just above the form like so: require_once 'dbconfig.php';. I have also included the dbconfig file in the OP – Aaranihlus May 14 '17 at 18:14

1 Answers1

0

Firstly you can't post to a class function and secondly you are not posting to a class function but you a posting to a file though it's linked to another with class function which is okay. If you using class autoload, I'd expect this to work just fine once you require the class.product.php file in your product_controller.php file cos that won't be loaded automatically.

DAVID AJAYI
  • 1,912
  • 20
  • 13