Dillinger
Dillinger

Reputation: 1903

How to call a specific php function inside a class through ajax?

I want to know how I can call the function ajax_check_login available in my User class, this class exists in user.php. This is the basic content:

class User extends {
/**
 * Class Constructor
 */
public function __construct() {
}

public function ajax_check_login() {
    try {
        if (!isset($_POST['username']) || !isset($_POST['password'])) {
            throw new Exception('Invalid credentials given!');
        }
        $this->load->model('user_model');
        $user_data = $this->user_model->check_login($_POST['username'], $_POST['password']);
        if ($user_data) {
            $this->session->set_userdata($user_data); // Save data on user's session.
            echo json_encode(AJAX_SUCCESS);
        } else {
            echo json_encode(AJAX_FAILURE);
        }
    } catch(Exception $exc) {
        echo json_encode(array(
            'exceptions' => array(exceptionToJavaScript($exc))
        ));
    }
  }
}

and this is my ajax request:

 var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
 var postData =
 {
     'username': $('#username').val(),
     'password': $('#password').val()
 };

 $.post(postUrl, postData, function(response)
 {
     // Some stuff..
 });

How you can see I want call the function ajax_check_login available in the user.php file. But I can't access directly to this function 'cause is located inside the User class, so I should create another file to bounce the request or I can do it in the same file user.php file?

Upvotes: 0

Views: 234

Answers (1)

Gavriel
Gavriel

Reputation: 19237

You have a typo:

class User extends {

Extends what?

Add this to user.php (outside of the class):

$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
  $user = new User();
  $user->$func();
}

Upvotes: 1

Related Questions