Jump to content

Run a method through AJAX, not a page


mitty

Recommended Posts

Hello all,

 

Is there a way that I can simply run a PHP method through AJAX?  If I have an object $user and I want to run $user->foo() as AJAX, I want to just say in jquery

 

$('#mydiv').load(foo());

 

Or something similar.  I know that I can say

 

$('#mydiv').load(foo.php); and make foo.php contain the line of code:

$user->foo()

 

But that runs into the problem of scalability... Since I'm on a different page, I have to reopen all of the required libraries and classes for that page.  If I could simply call the method, I wouldn't have to obtain $user from the session and reload all of my objects!

 

Does this make sense?  Is there a better solution?

Link to comment
Share on other sites

One solution I've used in the past is to create a simple front controller for all your server-side ajax handling and a simple function for client-side.

 

A very simplified version might look something like:

 

ajax.php

if (isset($_POST['controller'] && isset($_POST['action'])) {
    $controller = $_POST['controller'];
    $action = $_POST['action'];

    $c = new $controller;
    $c->$action();
}

 

Then in jQuery you just use something like....

 

function ajax(controller, action, callback) {
    $.ajax({
        url: "/ajax.php",
        method: 'post',
        data: {
            controller: controller,
            action: action
        },
        success: callback
    });
}

ajax('foo','bar');

 

Of course if you need more flexability you need to be able to expose more than just a simple function.

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.