Reputation: 3
I have the following Ajax call:
function loadFPFeed(catid)
{
var dataStream = 'catid=' + Number(catid);
var failMsg = 'Sorry, but there was a problem retrieving the news feed. Please try again later.';
$.ajax({
type: 'POST',
url: "ajax/load-sp-feed.php",
data: dataStream,
cache: false
}).done(function( res ) {
if(res != false)
{
$('#ppContent').html(res);
$('#ppContentCover').fadeOut(200, function() { $(this).remove(); });
}
else
{
$('#ppContentCover').html('<div id="failMsg">' + failMsg + '</div>');
}
}).fail(function( res ) {
$('#ppContentCover').html('<div id="failMsg">' + failMsg + '</div>');
});
}
This calls a PHP file that is used to pull up a newsfeed in a page:
<?php
$catid = intval($_POST['catid']);
require_once '../classes/Element.php';
$obj = new Element();
$obj->spNewsFeed($catid);
?>
What I'd like to do is put all my Ajax calls into their own folder. However, the relative URL always breaks when I do it. The problem seems to be that the relative path to the PHP class ('Element.php') will always be invalid in either the Ajax file or the page making the Ajax call, since both files are in different directories.
I've solved it for now by simply placing the Ajax calls in the same directory as the pages making the calls, but I don't like that because it's disorganized. I could simply change all of the require class calls to absolute URLs, but then I'd have to change them all when uploading to the production server.
Any ideas or best practices available? Or should I simply put the Ajax files in the same folder as the page files?
Upvotes: 0
Views: 298
Reputation: 4063
This doesn't make sense, the page making the AJAX call does not use the Element.php
file? And if it does, its a different piece of code so you could change the path only there and it's fixed.
If you are including the ajax/load-sp-feed.php
in your page because you also want to print it there when the page loads. You are doing something wrong. You should not use the ajax file in the page itself.
Upvotes: 0
Reputation: 151
I would strongly suggest looking into using a framework. (Yii is a good one.) The framework will handle stuff like this elegantly.
Also:
If you're not able to use a framework, consider using global helper functions for creating and manipulating Urls.
E.g.:
/**
* Create an absolute URL relative to the base path
*
* (You'd want to modify this to normalize the path...)
*
* @return string
**/
function createUrl($relativePath)
{
return getBasePath().normalizePath($relativePath);
}
/**
* Returns the base path in the current environment
**/
function getBasePath()
{
return 'http://localhost:8080/';
}
/**
* Normalizes the given path ('path/to/my/file') to some
* consistent form. E.g., might make sure there's a
* leading '/'.
**/
function normalizePath($path)
{
return $path;
}
Upvotes: 2