Timothy Owen
Timothy Owen

Reputation: 466

Call PHP function with AJAX?

I know I can do this:

//Jquery
$.ajax({type: 'POST', data : {'action' : 'foo'}});

//PHP
if(isset($_POST['action']) && $_POST['action'] == 'foo')
{
    function foo()
    {
        //yeah
    }
}

But.. In a project I'm working on with a friend, he has set up the controllers to be able to have specific functions called using custom actions. For instance, say my view is using the controller of thing.php. From my Javascript I can just AJAX to a url like this:

'url' : 'thing'

So in this case, foo() would get called without a need for any ifs or switches (as far as I know)

To me, this is great and ideal but I'm not sure how it was set up. He isn't around for the holidays to ask so I'm asking you guys.

Do you know how this is achieved? We are using a pretty typical MVC architecture. Sorry I am a PHP novice. Thanks!

Upvotes: 2

Views: 266

Answers (1)

Hugo Delsing
Hugo Delsing

Reputation: 14163

It looks like your friend is using .htaccess to rewrite URLS to add .php, perhaps with

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Now if you call a URL like /thing it will actually call the file /thing.php on your server and execute it. Or in your case if your url is just thing without the starting / it will call the thing.php in the same folder your current page is in.

Or perhaps he is rewriting everything to the controller and then adding the variable as command. Something like

RewriteRule ^(.*)$ controller.php?action=$1

Anyway, check your/his .htaccess file for clues

Upvotes: 7

Related Questions