AJAX proxy with PHP, is this possible?

In connection with my other question: Context-sensitive AJAX call on a modular site , is it possible to configure AJAX proxies in a convenient way?

I would like to make AJAX requests with a dynamic url without messing up the JavaScript code using server side PHP instructions, calculating the correct path for the ajax php file on the Apache / PHP / MySQL modular site, a crude CMS written by me. In other words, the site has plugins and components with their own folder structures containing their CSS, JS and PHP, and I have functions for dynamically restoring their folders. I would like:

$("#mydiv").load(siteRoot + "/ajax.php?plugin=datagrid&
action=myaction&... other params...");

will call instead (with a server-side url using PHP):

{siteRoot}/components/datagrid/ajax/myaction.php?... other params ...

(obviously with all possible checks against injections, CSRF and other hacks).

+2
source share
2 answers
File

/ajax/get.php should look something like this:

$plugin = $_GET['plugin'];
$action = $_GET['action'];
$get = array();
foreach ($_GET as $k=>$v) {
    if($k!='plugin' && $k!='action') {
        $get[] = "{$k}={$v}";
    }
}
$url = 'siteRoot/components/'.$plugin.'/ajax/'.$action.'.php?'.implode('&', $get);

header("Location: {$url}");

Of course you need to add some security checks to the code above

EDIT: The downside is that it will not work for sending POST requests.

+1
source

Instead, you can also declare your javascript variable in your request to the first page, and then use it say, SITE_URL contains your php-computed URL

 var siteRoot = '<?php echo SITE_ROOT?>' // or some thing else 

therefore, for any .js script included after this line, the siteRoot var parameter will be specified.

0
source

All Articles