mitty Posted August 1, 2011 Share Posted August 1, 2011 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 https://forums.phpfreaks.com/topic/243443-run-a-method-through-ajax-not-a-page/ Share on other sites More sharing options...
trq Posted August 1, 2011 Share Posted August 1, 2011 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 https://forums.phpfreaks.com/topic/243443-run-a-method-through-ajax-not-a-page/#findComment-1250095 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.