Jump to content

Ajax call php class function?


gmc1103
Go to solution Solved by Ch0cu3r,

Recommended Posts

Hi

 

I would like to use my php class to be called from ajax but i don't get it to work propery

 

This is my main class (part)

class USER {
    private $db;
    function __construct($DB_con) {
        $this->db = $DB_con;
    }
 public function delItem($id_itens){
        try {
            $sql = 'DELETE FROM `esmaior_biblioteca`.`item` WHERE `id_itens` = :me';
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':me', $id_itens, PDO::PARAM_INT);
            if (!$stmt->execute()) {
                print_r($stmt->errorInfo());
                return array('status' => 'error', 'message' => 'Problema ao remover este item...');
            } else {
                return array('status' => 'success', 'message' => 'O registo foi removido com sucesso...');
            }
        }
        catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

And in my main file

<?php
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
include_once 'dbconfig.php';
$user_role = $_SESSION['user_role'];
if (!$user->is_loggedin()) {
    $user->redirect('index.php');
}
//include 'menu_admin.php';
$user_id = $_SESSION['user_session'];
?>

<script>
            $(function () {
                $('#myFormSubmit').click(function (e) {
                    e.preventDefault();
                    var item = $('#id_itens').val();
                    var delItem = "delItem";
                    $.ajax({
                        url: '<?php echo $user->delitem($delItem); ?>',
                        type: 'POST',
                        data: {'delItem': delItem, 'item': item},
                        success: function (response) {
                            if (response.status === 'success') {
                                console.log("success");
                                $("#myModal").modal('hide');
                                $('#respostas .modal-title').html('Sucesso');
                                $('#respostas .modal-body').html('Informação: ' + response.message);
                                $('#respostas').modal('show');
                                $('#respostas').on('hidden.bs.modal', function () {
                                    window.location.reload(true);
                                });
                            }
                        }
                    });
                });
            });
        </script>

And i can't get this working properly, do i miss something?

 

Thanks

Link to comment
Share on other sites

I'm not sure if you actually understand Ajax, because the code you've posted doesn't really make sense.

 

The idea is this:

  • After the client has received a page of your website, they use JavaScript to make an additional HTTP request to a PHP script.
  • The target script receives the request, processes the data and takes action. For example, it might instantiate your User class and call the delItem() method. It's also possible to send data back.
  • Upon receiving the HTTP response, the JavaScript code checks for errors and processes the data (if present).

So, no, you can't just send an Ajax HTTP request to an arbitrary URL. Your server needs to provide a PHP script which understands your Ajax requests and processes them.

 

You can either implement this all by yourself. Or you can use an established protocol like JSON-RPC so that you don't have to mess with low-level HTTP stuff.

Link to comment
Share on other sites

I doubt that your code works with anything. If I understand it correctly, then you don't use Ajax at all, you just call $user->delitem($delItem) in your main script and somehow insert the return value into the JavaScript code. This has nothing whatsoever to do with Ajax.

 

Again: You need a separate(!) PHP script which processes the Ajax request. There's no other way. That's simply how Ajax works.

Link to comment
Share on other sites

No, it works when i put instead of

$user->delitem($delItem)

i put a name file who gonna call that function, example updates.php who includes db_config where is the class

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-type: application/json');
include_once 'dbconfig.php';
$id_itens = filter_input(INPUT_POST, 'item');
$delItem = filter_input(INPUT_POST, 'delItem');
if ($delItem != null) {
    $ret = $user->delItem($id_itens);
    echo json_encode($ret);
}
Link to comment
Share on other sites

That looks a lot more like Ajax. So, problem solved?

 

If you still have trouble with multiple methods, open the link I gave you. Your problem has already been solved.

 

Of course you could also try to implement your own Ajax interface. But in my experience, most homegrown APIs are very bad. For example, why does your delItem() method return this weird status array? All it should do is update the database (and maybe throw an exception if that fails). Sending status codes around is the job of a separate class which takes care of the client/server communication.

Link to comment
Share on other sites

You are over-thinking this whole thing. You can call whatever class/function you want in the PHP file that will be accessed by your Ajax call.

in the data you pass to your PHP page, you can tell it what class should be called, what function etc.

 

In this following example we have 'action' which tells your PHP page to call the "delItem" method on a known class and pass the method the "item" argument.

$.ajax({
url: 'http://www.yourwebsite.com/file_name.php',
type: 'POST',
data: {action: 'delItem',item: item},
success: function (response) {
    if (response.status === 'success') {
        console.log("success");
        $("#myModal").modal('hide');
        $('#respostas .modal-title').html('Sucesso');
        $('#respostas .modal-body').html('Informação: ' + response.message);
        $('#respostas').modal('show');
        $('#respostas').on('hidden.bs.modal', function () {
            window.location.reload(true);
        });
    }
}
});
Link to comment
Share on other sites

Hi hansford

 

Thank you for your apport.

I have tested your code but nothing happen

 

This is my ajax

<script>
            $(function () {
                $('#myFormSubmit').click(function (e) {
                    e.preventDefault();
                    var item = $('#id_itens').val();
                    $.ajax({
                    url: 'class.user.php',
                    type: 'POST',
                    data: {action: 'delItem',item: item},
                    success: function (response) {
                        if (response.status === 'success') {
                            console.log("success");
                            $("#myModal").modal('hide');
                            $('#respostas .modal-title').html('Sucesso');
                            $('#respostas .modal-body').html('Informação: ' + response.message);
                            $('#respostas').modal('show');
                            $('#respostas').on('hidden.bs.modal', function () {
                                window.location.reload(true);
                            });
                        }
                    }
                    });
                });
            });
        </script>

and this is my class.user.php function

public function delItem(){
        $id_itens = filter_input(INPUT_POST, 'item');
        try {
            $sql = 'DELETE FROM `esmaior_biblioteca`.`item` WHERE `id_itens` = :me';
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':me', $id_itens, PDO::PARAM_INT);
            if (!$stmt->execute()) {
                print_r($stmt->errorInfo());
                return array('status' => 'error', 'message' => 'Problema ao remover este item...');
            } else {
                return array('status' => 'success', 'message' => 'O registo foi removido com sucesso...');
            }
        }
        catch (PDOException $e) {
            echo $e->getMessage();
        } 
    }

and i don't have any response....

Link to comment
Share on other sites

  • Solution

No, that is not what hansford meant

 

You still need to to have the code you used in post #7 for handing the ajax request, except rather than doing this

$id_itens = filter_input(INPUT_POST, 'item');
$delItem = filter_input(INPUT_POST, 'delItem');
if ($delItem != null) {
    $ret = $user->delItem($id_itens);
    echo json_encode($ret);
}

it'll now be

$id_itens = filter_input(INPUT_POST, 'item');

// get the action passed for ajax request
$action = filter_input(INPUT_POST, 'action');

// do this if action is set to delItem
if ($action == 'delItem') {
    $ret = $user->delItem($id_itens);
    echo json_encode($ret);
}
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.