user3557428
user3557428

Reputation: 1

$.post into a php class function

I want to make a live username check and I want to use a PHP function.

-->
<?php
    require '../../core/init.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>K&ouml;ppCMS - Registrieren</title>
    <link rel="stylesheet" href="../../../css/style.css">
    <script type="text/javascript" src="../../../js/jquery.js"></script>
    <script type="text/javascript" src="../../../js/footer.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#username").keyup(function (e) {

                //removes spaces from username
                $(this).val($(this).val().replace(/\s/g, ''));

                var username = $(this).val(); //get the string typed by user

                $.post('users.php', {'username':username}, function(data) { //make ajax call to users.php
                    $("#user-result").html(data); //dump the data received from PHP page
                });

            });
        });
</script>
</head>

Init.php:

<?php
session_start();
require 'database/connect.php';
require 'classes/users.php';
require 'classes/general.php';

$users         = new Users($db);
$general     = new General();

$errors     = array();
?>

So how can I call the check_username function and send the values to it? Hope you understand my question, because my English isn't that good.

i'd tried this in the users.php:

<?php
$users = new Users($db);
echo $users->check_username($_POST['username']);
class Users{
    private $db;

    public function __construct($database) {
        $this->db = $database;
    }

    public function check_username($data) {
        return $data+1;
    }
    function func1($data){
        return $data+1;
    }

}

Get this Error:

Notice: Undefined variable: db in C:\xampp\htdocs\kcms\system\cms\user\users.php on line 2

enter image description here

Upvotes: 0

Views: 63

Answers (1)

Barmar
Barmar

Reputation: 781350

Your PHP script should do something like:

<?php
require('init.php'); // This contains $users = new Users($db);
echo $users->check_username($_POST['username']);

For using the return value in your Javascript, see

How do I return the response from an asynchronous call?

Upvotes: 3

Related Questions