Context-aware AJAX call in a modular site - php

Edit: I thought about a possible solution, but I made another question as it is very specific: see AJAX proxy with PHP, is it possible?
A couple of times I've encountered this problem...
I create sites that have a certain degree of modularity. So, it is possible that there are "components" (think of a rough CMS) which carry their own PHP code, CSS, and JavaScript, all dynamically included. Think about a structure like:
{siteroot}/component/datagrid/datagrid.php
{siteroot}/component/datagrid/js/datagrid.js
{siteroot}/component/datagrid/css/datagrid.css
{siteroot}/component/datagrid/ajax/getsomedata.php
Now, the question is: for JavaScript files, and expecially AJAX calls, how do I make them context-aware with the URLs?
For example, if in datagrid.js I want to call siteroot/component/datagrid/ajax/getsomedata.php with AJAX I should write (with JQuery):
$("#ajax").load("siteroot/component/datagrid/ajax/getsomedata.php");
First problem: siteroot changes on different installations. I've managed that by including a general
var codeBase = <? echo json_encode(Config::$siteRoot); ?>
with PHP on every page, from a Config file that can be easily edited for every installation, so I can do with whatever JavaScript something like:
$("#ajax").load(codeBase + "/component/Datagrid/ajax/getsomedata.php");
What do you think of this approach?
Second problem: but I have PHP functions that return to me also the components folder, or the folder of other components. It would be nice to make the whole URL dynamic. This would account also for changes in the structure of the component if I want.
The only solution I've found is to use a .js.php dynamic Javascript. This is very unelegant, and I have to include all the framework in the JavaScript file, like:
<?php
include "../../libs/framework.php"; // get my functions...
$myUrl = Config::$siteRoot . Framework::getComponentAjaxDir("datagrid") . "/getsomedata.php";
?>
$("#ajax").load(<?=json_encode($myUrl)?>);
Another side effect is that I have to know exactly the include the path for framework.php... I don't want this so hard-codedin my ".js.php" file.
Any smart solutions about that?

As nobody answered in a suitable way, I answer to myself to provide a solution I've found out that can be useful.
The key to my solution is simple:
I create an AJAX proxy at a fixed location in my site structure, so I can use codeBase to reference the proxy from JavaScript
I call this proxy with two parameters: plugin and action, which identify a) the plugin folder in which the "real" ajax is and b) the ajax file to use, along with the other params:
$("#...").load( codeBase + "/main/ajax.php?plugin=Datagrid&action=gettable&otherparams"...)
In ajax.php I sanitize the parameters, and use plugin and action to obtain the "real" ajax file:
{serverRoot}/components/{plugin}/ajax/{action}.php
Then i simply include that file in ajax.php

To be honest your problems are realistic options and aren't that bad practice in general quite frankly.
But let's explore this a little further.
What would be the best approach is for you to have 1 main config.php file which you can then specify modules, i.e. your datagrid etc.
You could store all modules in an array variable like so:
$_SITE_PATH = "/var/www/html/";
$_HTTP_PATH = "http://example.com/";
$_MODULES_PATH = $_SITE_PATH."modules/"
$_MODULES = array(
"datagrid"=>$_MODULES_PATH."datagrid/init.php",
"something_else"=>$_MODULES_PATH."something_else/init.php"
);
Each module would have it's own directory with instantiation init.php so that it would load all it required to get going.
This way you could code as you liked and when you needed something (preferably in the header state) do something like this.
global $_MODULES;
require_once($_MODULES["datagrid"]);
Everything will be easily available as and when required without any variable path issues later down the line.

Related

PHP Routing - "Clean" include

I have a PHP routing script, like this:
include_once('routing-functions.php');
// pathMatches was imported from routing-functions.php
if(pathMatches('/blog/*')){
include_once('actual-script.php');
}
The problem I have is the following: the functions and global variables from routing-functions.php could potentially conflict with the included file. Additionally, I don't want actual-script.php to have access to any of the variables of the router.
I am looking for a way to completely wipe the PHP context, so that the file is included as if it were directly requested, so doing the following is not an option because it changes the context/scope in which actual-script.php is executed:
if(pathMatches('/blog/*')){
function $sandbox(){
include_once('actual-script.php');
};
$sandbox();
}
Additionally, sending a local request to the file (e.g. with cURL) is also not an option, because it has a negative impact on performance and I want it to run as if it were under the /blog/ URL.
The problem is easy to solve with .htaccess, however, I need a dynamic solution that uses a PHP router.
If anyone has had a similar problem before or knows of a good solution it would be greatly appreciated.

Rails application that includes a PHP page

This is a 2 part question:
a. Is it possible to have a .php file as a view in Rails? Need it because at some point some data needs to be signed with a bank provided function -only in PHP-
<?php
$base64 = ".SignData("some data from rails", "private.key.pem")
?>
I tried in Rails something like:
..
render file "/home/myApp/app/view/signData.php.erb"
..
Also tried
..
render file "/home/myApp/app/view/signData.php"
..
But tells me "Template is missing". I know it is not a matter of path because if change .php to .html in path, it finds the file.
b. The other question: how to get back to rails the $base64 info obtained in PHP?
Thanks
Have you thought about having your web server reroute that one specific call to PHP instead of Rails? It might be the cleanest solution. Something like http://weblog.terrellrussell.com/2008/01/running-php-within-rails/.
You could make a separate, small PHP webservice to wrap this SignData method. You can host it on the same platform, which is handy, then call it from your main application with some straight forward Net::HTTP.

Changing dependency paths when deploying to different directory structure than developing in

What are some popular ways (and their caveats) of handling dependency path changes in scripted languages that will need to occur when deploying to a different directory structure?
Let the build tool do a textual replace? (such as an Ant replace?)
Say for example the src path in a HTML tag would need to change, maybe also a AJAX path in a javascript file and an include in a PHP file.
Update
I've pretty much sorted out what I need.
The only problem left is the URL that gets posted to via AJAX. At the moment this URL is in a JS config file amongst many other parameters. It is however the only parameter that changes between development, QA and production.
Unfortunately dynamically generated URLs as #prodigitalson suggested aren't desirable here--I have to support multiple server side technologies and it would get messy.
At the moment I'm leaning towards putting the URL parameter into its own JS file, deploying a different version of it for each of development, QA and production, additionally concatenating to the main config file when deployed.
IMO if you need to do this then youe developed in the wrong way. All of this shoul dbe managed in configuration file(s). On th ephp side you should have some kin dof helper that ouputs the path based on the config value... for example:
<?php echo image_tag('myimage.jpg', array('alt'=>'My Image')); ?>
<?php echo echo javascript_include('myscript.js'); ?>
In both these cases the function would look up the path to the javascript and image directories based on deployment.
For links you should be bale to generate a link based on the local install of the application and a set of parameters like:
<?php echo link_to('/user/profile', array('user_id' => 7)); // output a tag ?>
<?php echo url('/user/profile', array('user_id'=>7)); // jsut get the url ?>
As far as javascript goes you shouldnt have any paths hardcoded in a js file that need to be changed. You should make your ajax or things that are path dependent accept parameters and then you send these parameters from the view where you have the ability to use the same scripted configuration.. so oyu might have something like:
<script type="text/javascript">
siteNamespace.callAjax(
'<?php echo url('/user/profile/like', array('user_id' => 7)); ?>',
{'other': 'option'}
);
</script>
This way you can change all this in a central location based on any number of variables. Most MVC frameworks are going to do something like this though the code will look a bit different and the configuration options will vary.
I would take a look at Zend Framework MVC - specifcally the Config, Router, and View Helpers, or Symfony 1.4 and its Config, Routing and Asset and Url Helpers for example implementations.

php include problem with urls with options ?view=task&others file not found

I really have read the other articles that cover this subject. But I seem to be in a slightly different position. I'm not using modrewrite (other articles).
I would like to 'include' a webpage its a 'Joomla php' generated page inside a php script. I'd hoped to make additions on the 'fly' without altering the original script. So I was going to 'precomplete' elements of the page by parasing the page once it was included I hadent wanted to hack the original script. To the point I can't include the file and its not because the path is wrong -
so
include ("/home/public_html/index.php"); this would work
include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
I've tried a variety of alternates, in phrasing, I can't use the direct route "http:etc..." since its a current php version so must be a reference to the same server. I tried relative, these work without the ?option=com_k2&view=item&task=add
It may be the simple answer that 'options' or variables can be passed.
Or that the include can't be used to 'wait' for a page to be generated - i.e. it will only return the html.
I'm not the biggest of coders but I've done alot more than this and I thought this was so basic.
this would work include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
And it never will: You are mixing a filesystem path with GET parameters, which can be passed only through the web server (utilizing a http:// call... But that, in turn, won't run the PHP code the way you want.)
You could set the variables beforehand:
$option = "com_k2";
$view = "item";
$task = "add";
include the file the normal way:
include ("/home/public_html/index.php");
this is assuming that you have access to the file, and can change the script to expect variables instead of GET parameters.

custom php function creation and install

I would like to know how to create a php function that can be installed in php
just like the already built in functions like :
rename
copy
The main point I would like to achieve is a simple php function that can be called from ANY php page on the whole host without needing to have a php function within the php page / needing an include.
so simply I would like to create a function that will work like this :
location();
That without a given input string will output the current location of the file via echo etc
Well, there are a couple of options here. One of them is to actually extend the language by writing an extension. You'd have to muck around with the PHP source code, write it in C, and deal with the Zend Engine internally. You probably wouldn't be able to use this on a shared host and it would be quite time consuming and probably not worth it.
What I would do is put all of your functions into a separate PHP file, say helper_functions.php. Now, go into your php.ini and add the directive: auto_prepend_file = helper_functions.php. This file should be in one of the directories specified in your include_path (that's a php.ini directive too).
What this does is basically automatically put include 'helper_functions.php'; on every script. Each and every request will have these functions included, and you can use them globally.
Read more about auto_append_file.
As others have said, there's probably an easier, better way to do most things. But if you want to write an extension, try these links:
http://docstore.mik.ua/orelly/webprog/php/ch14_01.htm
http://www.tuxradar.com/practicalphp/2/3/0
So you want to extend PHP's core language to create a function called location(), written in C, which could be done in PHP by:
echo __FILE__;
Right. Have fun doing that.

Categories