i am using ajax to load pages into a div
the page is loading fine
but i cant run the php and javascript
in that loaded page
in server i am loading the page like this
file_get_contents('../' . $PAGE_URL);
in the browser i am setting the content of the div
using
eval("var r = " + response.responseText);
and setting the innerHTML for that div
with the retrieve information
but when i get the new inner page
no php or java script is working
is that suppose to be like that ?
Well the php is not going to work I think because the way you are handling it, it is just text. I would suggest using something like include('../' . $PAGE_URL); and that should parse the php.
The javascript problem probably has to do with the fact that you are loading <html> <body> <head> tags in a div I'm not sure what happens when you do that, but it shouldn't work properly. Try using some type of <frame> tag.
In order for your javascript to be executed properly, you have to wait until the browser has finished to load the page.
This event is named onload(). Your code should be executed on this event.
<?php
$file = false;
if(isset($_GET['load'] && is_string($_GET['load'])) {
$tmp = stripclashes($_GET['load']);
$tmp = str_replace(".","",$tmp);
$file = $tmp . '.php';
}
if($file != false && file_exists($file) && is_readable($file)) {
require_once $file;
}
?>
called via file.php?load=test
That process the PHP file, and as long as you spit out HTML from the file simply
target = document.getElementById('page');
target.innerHTML = response.responseText;
Now, i'm fairly certain parts of that are insecure, you could have a whitelist of allowable requires. It should ideally be looking in a specific directory for the files also. I'm honestly not all too sure about directly dumping the responseText back into a DIV either, security wise as it's ripe for XSS. But it's the end of the day and I haven't looked up anything on that one. Be aware, without any kind of checking on this, you could have a user being directed to a third party site using file_get_contents, which would be a Very Bad Thing. You could eval in PHP a file_get_contents request, which... is well, Very Very Bad. For example try
<?php
echo file_get_contents("http://www.google.com");
?>
But I fear I must ask here, why are you doing it this way? This seems a very roundabout way to achieve a Hyperlink.
Is this AJAX for AJAXs sake?
Related
I have an automated archive of several (media) websites' frontpage, written in php. Specifically, I am copying the html in the <body> tag twice a day, I have a copy of all their css and js files, so I can recreate the frontpage from any point in the past. Now, I came to a problem with one of those websites, as they load the main slider content (most important news) with an ajax call. I would like this ajax call to be executed before I parse the data, not just a blank div. By looking around, I found out they use a wordpress plugin named lof-jslidernews2, but I can't find the specific ajax call to see the url and make curl request. Any ideas how to achieve this?
The website: http://fokus.mk/
My code (had to parse manually like this, because of some problems with DomDocument and not-valid html):
// ...
if($html = file_get_contents ($row['page_url'])) {
$content = strstr($html, '<body');
$content = str_before($content, '</body>') . '</body>';
$filename = date('YmdHis') . $row['page_name'];
if($success = file_put_contents ('app/webroot/files/' . $filename, $content)) {
// ....
** There is nothing illegal about my project, I am not stealing content, just freezing frontpages for later comparison. I have consulted a lawyer about this. :)
I don't know why, but the guy that actually solved my problem deleted his answer. So, here it is:
He suggested using an emulator, specifically Mink. It was easy to install (using composer) and did the job on the first try. Awesome library.
Mink is an open source browser controller/emulator for web applications, written in PHP 5.3.
as I already mentioned in the title, I'm looking for a JS-function for getting the same result like I get with this PHP code:
dirname(dirname(__FILE__))
Thanks in advance!
I don't think it is possible because php dirname operates on apache server on local machine. It has access to the filesystem. But javascript operates on browser layer which can't operate with filesystem. I think so you should use ajax and proccess result how you need it. I think so its best solution for you.
I needed a solution to write code like this:
$("#div").load(ROOT_URL + "my/path/to/script.php");
Solution: a PHP script generates one JS-file of all needed JS-files and adds the ROOT_URL to the top of the generated file:
$js = 'ROOT_URL = "' . ROOT_URL . '"; ' . $js;
file_put_contents("file.js", $js);
Now I'm able to use the ROOT_URL (set in a PHP config-file) in JS-code as well. I hope I could help.
You can have PHP output the script. Yes, that's right, you probably can't make php process js files (unless you are in full control of the server). But it doesn't matter. Just make sure that the MIME type is correct, both in the headers PHP returns and the script tag. That way, you can have PHP insert the any values you want in the script, including it's own path.
In script.php:
header("Content-type: text/javascript");
echo 'var myvar = '.$something;
//where $something can be $_SERVER['REQUEST_URI'], __FILE__ or whatever you need.
//You could even use information from session variables, or query the database.
//In fact, this way you can have GET parameters in your javascript.
//Make sure you are not creating a vulnerability with the exposed information.
//Then put the rest of the script as usual. You could even include it*.
*: include
In HTML:
<script type="text/javascript" src="script.php"></script>
Yes, I know I'm repeating the MIME type, do it this way to maximize browser compatibility.
There's no analogue of __FILE__ in browser Javascript; the code does not have direct access to the URL from which it was loaded. But with certain assumptions you can figure it out, as in the answer here.
Once you have the URL of the script (I assume in a variable called scriptURL below) you can set about finding the grandparent URL. This can get tricky with URLs, so it's probably safest to let the URL-savvy bits of Javascript parse the URL for you and get just the pathname component before you start with the string-munging:
var a = document.createElement('a')
a.href = scriptURL
var scriptPath = a.pathname
Then it's unfortunately down to string manipulation; here's one somewhat clunky solution:
var components = scriptPath.split(/\//)
while (components.length > 0 && !components[components.length-1])
components.length -= 1;
var twoDirsUp = components.slice(0,components.length-2).join('/')
And then you can convert the result back into a full URL using the anchor element trick in reverse:
a.pathname = twoDirsUp;
var grandParentUrl = a.href
Why not load what you want from absolute URL?
If you have inse your block of codes: /my/script/to/load.js browser will load the correct file if you are in yoursite.com or whatever like yoursite.com/a/b/c/d/e/f
A little off topic, but if you just want to get the similar of dirname($_SERVER['REQUEST_URI']) for javascript, you can do
window.location.href.substr(0, window.location.href.length - window.location.href.split('/').pop().length)
I use something like that to free from the paths in javascript
var __DIR__ = window.location.pathname.match('(.*\/).*')[1] + 'NameOfThisFolder';
first
window.location.pathname.match('(.*\/).*')[1]
return the current path without the file name or other stuff.
rootFolder/folder1/folder2/
then I add the name of this folder ('NameOfThisFolder').
In this way, I can make for instance ajax request in current page from a page that was called in turn from an ajax request without worry about the path
My first contact with Ajax is happening right now, and I'm kind a confused. I've read many of questions asked, but I'm not able to read the answer, that is most likely here somewhere.
Situation is, I'm using OOP PHP approach, and all I do go through index.php with parameters. So I do not call any other .php file in form posts, button clicks..
I've created an HTML listbox (which I'd like to remove vertical scrollbar, but that's just a bonus to resolve), which feeds my categories in it.
Now, by clicking each category I'd like to call certain function that would then generate output for the other div.
function swapContent(){
$("#myPresentDiv").html('<img src="../../imgs/ajax-loader-big.gif"/>').show();
var cat = $('#listbox').val();
$("#action").change(alert(cat));
var url = "&s=".cat;
$.post(url, {contentVar: cat} ,function(data) {
$("#myPresentDiv").html(data).show();
});
}
So, my JQuery script picks up correct Category, I alert it to alert dialog, so I'm sure that's fine, and then with code as it is at the moment, I reload my whole page so I get, page in page in page in page...
I'm trying to figure out how to write JQ ajax call, that would return only the results, not the whole page.
can I put URL "index.php&s="cat, and then somehow tell to ajax "go through index, call function displayresults ($cat); ?
Hope everything I wrote make sense to you :)
Tnx.
The url's your ajax function call, must return only the page parts and not the whole html document.
If you have
$.post('ajax.php',data,function(d){
$('#responsediv').html(d).show();
});
The file ajax.php must only return the page parts,like
<div>This is the new content</div>
so you will not have page inside page.
If you look at the frameworks or cms out there, they basically have routes that map calls to your index.php function to methods of the controller.
This is a complex argument, you could try to start out reading this article
Yeah, that makes sense. Your question is basically: when you get a result of an AJAX op and insert it into your page, it inserts the whole layout again, rather than the template.
OK, so the solution is to make a call to a PHP script that is "unstyled" i.e. has no template data. Your PHP script should therefore just output a short HTML snippet rather than a page (you might have a 'header' and 'footer' that can be removed for this page). What action you need to take depends what you're using on the server side - framework? CMS? Custom PHP app?
I did the exact thing for a internal app quite some time ago....What happened was i was passing the class name, function name and the function parameters via ajax variables and reading the same in php at the backend and then call the appropriate function in the class with those paraeters.
The PHP code:
$option = trim($_GET['v']);
switch ( $option ) {
case 1:
$sid = trim($_GET['q']);
$page = trim($_GET['p']);
$method = trim($_GET['m']);
$class = new $page( $link );
echo $class->$method( $sid );
break;
case 2:
$page = trim($_GET['p']);
$method = trim($_GET['m']);
$class = new $page( $link );
echo $class->$method();
break;
default:
echo '';
break;
}
But this was an internal app, so there was no injection attacks, xss,xsrf,session hijack issues....things might differ for you
Hope this helps.
I think you are searching for a GENERAL strategy to handle ajax requests its upto you
for example Server Side Ajax
unless you are using a specific framework (CI , yii etc)
You might want to look into some frameworks, as they can make this for you infinitely easier to implement:
http://demo.atk4.com/demo.html?t=20
I have a PHP page where the header and footer are PHP includes.
I want to know if there is any possibility of the includes loading asynchronously - or does PHP gather all the files required, compile them and send them as one file?
The reason I ask is that I've seen an interesting PHP app that seemed to keep the connection open and do things in sequence before closing the connection - I wondered if that's what happens with includes.
PHP version is 5.3.6
EDIT:
What I actually want is for the page to load all at once, to prevent my layout mashing as each bit loads. Sorry to any who misunderstood this
PHP does gather and compile them; everything goes to the browser as a single document. If you don't want this, you'll have to do something with XMLHTTPRequest on the frontend
Generally any output will be output as it is generated.
echo 'A';
sleep(1000);
echo 'B';
sleep(1000);
echo 'C';
This slowly outputs "ABC". Includes are included when they are encountered, the same way echo outputs anything at that specific point. It's all in order, never asynchronously.
A web server may buffer all output before sending any of it to the client. In the above example, you'd receive "ABC" all together after 2 seconds of nothing.
If your objective is to receive all the page at once you need to use ob_start() and ob_end_flush(). Do something like:
ob_start();
...
write all your outputs
...
ob_end_flush();
This will force the server to buffer the output until the whole page is prepared.
Good luck!
I use the following architecture when loading a page on my application:
index.php
<script src="path/to/js/lib/jslib.js" type="text/javascript"></script>
window.addEvent('load', function()
{
BuildPg(PgStatus); //PgStatus is a variable I use in a state machine to build different pages
});
<form>
<div id="DivPgTop"></div>
<div id="DivPgMiddle"></div>
<div id="DivPgBottom"></div>
</form>
This is the entire index.php
In my jslib.js I have functions like:
function BuildPg(Pg) {
BuildPgTop(Pg);
BuildPgMiddle(Pg);
BuildPgBottom(Pg);
}
function BuildPgTop(Pg) {
var Content="";
if (Pg == 1) {
Content = function_a(); // function_a builds the top of the page
else if (Pg == 2) {
Content = function_b();
etc...
}
document.getElementById("DivPgTop").innerHTML = Content; //here is where I load the top of the page
}
And I do the same for the other parts of the page Middle and Bottom.
Using this framework, if you changed my BuildPg() function to something like:
function BuildPg(Pg) {
BuildPgTop(Pg);
sleep(foo);
BuildPgMiddle(Pg);
sleep(bar);
BuildPgBottom(Pg);
}
Your user would experience the top of the page loading first, a delay, the middle of the page, another delay, and the bottom.
And if you change the order of the function calls you could even have the bottom of the page load first, then the middle and the top.
I hope this makes sense. Good luck!
PHP sends a single document. What you want to do is achieved with something called AJAX (http://en.wikipedia.org/wiki/Ajax_%28programming%29)
Basically you write some JavaScript code that uses XMLHTTPRequest object to connect to the server and download some extra info.
I need to detect where the user has just clicked from - as my AJAX content needs to be displayed differently depending on the source page it is to be inserted into.
If it's to go into about.php it needs to be data only, but if it's to go into about-main.php it needs to be the whole middle column so needs a header/footer wrapper around the data.
The html called via AJAX is held in a php page which uses this code to see who's asking, and then formats the HTML response appropriately.
$array[] = "/cf/about.php";
$array[] = "/cf/about/about-main.php";
$array[] = "/cf/about/other-page.php";
$ispage = "";
foreach ($array as $value) {
if ($_SERVER['HTTP_REFERER'] != $value) {
$ispage = "";
} else {
$ispage = "woot";
}
}
if ($ispage == "woot") {
echo $content;
} else {
include_once 'about-header.php';
echo $content;
include_once 'about-footer.php';
}
The problem is... HTTP_REFERER seems to be a bit hit and miss. It works just fine while I'm at work on the network, but I've tried it out on my computer at home and it's obviously completely failing to work - the results are horrible :o
Is there another way of achieving this? I guess session variables could be used but then I've not got much experience of that!
Any and all hints/tips are appreciated ;)
Thanks!
edit:
The page is actually a staff profile page. Its normal location is about.php and the 2nd column div displays a grid of thumbnails which when clicked, load the profile in that place via AJAX. All nice and simple - back button reloads the grid of photos.
The problem is, each staff member also needs a static page. I've created these at about/staff-name.php. The content is THE SAME though. I want the server to detect if someone has come to the about/staff-name.php directly and if so, wrap a header/footer around it.
If the request has come from the grid of photos (ie AJAX) then it doesn't need the header/footer wrapper.
Is that clear? :o
1) If AJAX request - no wrapper
2) If not AJAX request - add header/footer wrapper
Wouldn't it be easier to just pass a flag in your AJAX call to tell the script which type of content to display?
Edit:
So about/staff-name.php displays the content. Call it via AJAX as about/staff-name.php?FromAjax=1
Then in the about/staff-name.php file:
if (isset($_REQUEST['FromAjax']) ) {
echo $content;
} else {
include_once 'about-header.php';
echo $content;
include_once 'about-footer.php';
}
No matter what, the Referer is not an information you should base your whole website upon : it is sent by the client, which means (at least) :
the client does not necessarily have to send it
it can be disabled in the browser
some firewall / antivirus remove it
it can be forged / altered (an easy way with firefox is to use an extension to do that)
You definitly must find a better/saffer/more reliable way to do what you need.
One solution (which you already discarded) would be to pass an additionnal information in all your links, saying which page the request comes from. In my opinion, this would probably be the best thing to do...
Maybe a simpler way would be to add a parameter to your Ajax request, saying where it comes from ? ie, instead of relying on the Referer in the PHP script, just have a look at a parameter in the request, which would act as some "kind of referer", but put by you ?
It will not be more secure (users could still forge request, with that parameter), but, at least, it would not be disabled / modified (except if the user does it by hand)
In the end, you also say this :
1) If AJAX request - no wrapper
2) If
not AJAX request - add header/footer
wrapper
Well, if it's only a matter of determining if the PHP script was called through an Ajax request, here too, two solutions :
Add a parameter to the Request when it's done through Ajax (you only add this parameter in the JS script doing the request ; and when the parameter is here, PHP knows it's an Ajax request)
Or, in the PHP script, look for an X-Requested-With HTTP header, which is often here with the value XMLHttpRequest when a request is made through an Ajax call. (But you should check that it's set with your JS Framework / or maybe it depends on the browser -- not sure about that :-( )
Why don't you just create the static pages on the server without using ajax at all, including the header and footer and the profile bit? If the page is static you shouldn't have any need to load content using javascript.
If you do need to load it using javascript, then Vex's solution is good. You could pass some optional parameters in the ajax call which control how the page is rendered - that way, the included page doesn't need to know about the pages that use it, it just needs to understand the parameters that tell it how to render itself. You can then reuse it more easily in future.
I did notice an error in your code however - this probably won't work as expected:
$ispage = "";
foreach ($array as $value) {
if ($_SERVER['HTTP_REFERER'] != $value) {
$ispage = "";
} else {
$ispage = "woot";
}
}
If a page name is matched, but then the next one isn't, $ispage will be set back to ''. You'd probably better off doing something like:
$ispage = "";
foreach ($array as $value) {
if ($_SERVER['HTTP_REFERER'] == $value) {
$ispage = "woot";
break;
}
}
or
$ispage = '';
if (in_array($_SERVER['HTTP_REFERER'], $array)) {
$ispage = 'woot';
}
Tai kucing -
If you format your links like this:
link
Then the php just needs to be this:
if (isset($_REQUEST['setvariablehere']) ) {
do something for when variable IS set
} else {
do something for when variable IS NOT set
}