i am looking for a way to directy access the variables of the page that loaded another page inside a div in it using ajax. i know i can do it using some kind of a get string pass it to the Javascript and open the son page with it and retrieve the variables using get normal GET function, i am looking for a better solution. i have this parent page:
<body onLoad="control_post_data(<?php
echo true;
//echo isset($_COOKIE['username']); // allow after login is done
?>)">
<div id="publish_page">
</div>
and this is the script:
function control_post_data(bool){
var div = document.getElementById("publish_page");
var xmlhttp = createXmlHttpRequestObject();
if(bool){
//user is registered presend post page
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
div.innerHTML = responseText;
//Use the response text to add the extra row
}
}
xmlhttp.open("GET","sub_published.php",true);
xmlhttp.send();
} else {
//present log in/register page
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
div.innerHTML = responseText;
//Use the response text to add the extra row
}
}
xmlhttp.open("GET","login.php",true);
xmlhttp.send();
}
}
i am trying to acces the parent page variables in the sub_published.php page.
You could store all the parent page variables in the $_SESSION variable, like:
session_start();
$_SESSION['someid']['varname']=$var;
and then access it in the child page:
session_start();
$var=$_SESSION['someid']['varname'];
if you wish to allow users to have open multiple instances of your page with different values in variables, you should set the someid to something unique and send that with the ajax request, otherwise it can be static.
The simple answer is that you cannot. When the browser deals with the parent page, it has no knowledge of what/how generated it - all it sees is an HTML page, hence there are no variables of any kind that it knows about.
When you're invoking another PHP script using AJAX, the browser simply makes another call to the server. A new process is started on the server to run that script - and it has no knowledge of the parent page generation (which most likely has finished loading by now, anyway, and the script exited).
The only way to avoid using GET or POST values in the ajax request is to use cookies. You can set a cookie value (using setcookie()
function) from the parent page and then read is in the ajax page (using $_COOKIE
superglobal).
EDIT: Just realised the obvious: you can also use $_SESSION
to store values between pages. See @Ratzor's answer for more info.
If you are talking about HTML then you can access the DOM-tree of a parent page via window.parent.document. If you are talking about PHP then it is not possible - I advise reading a bit more about client-server nature of PHP-HTML.