PDA

View Full Version : Help Accessing Variables Made With AJAX


aWhite89
06-09-2009, 12:11 AM
I am new with using ajax. I am trying to basically make a "Folder Tree" that I can expand and collapse folders. Also, the contents in each folder is dynamic so I am receiving these things from a database. Because I'd rather not have page refreshes, and because I'd like to learn ajax a little better, I've done it this way.

I have javascript functions in a php file that is linked as if it were a javascript-only file. See below:

index.php

...
<script type="text/javascript" src="functions.php"></script>
...


functions.php

function ajaxRequest(parent)
{
var AJAX = null;
if(window.XMLHttpRequest)
AJAX = new XMLHttpRequest();
else
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
if(AJAX == null)
{
alert("Your browser doesn't support AJAX.");
return false;
}
/*AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4 || AJAX.readyState == "complete")
{
callback(AJAX.responseText);
}
}*/
var queryString = "?parent=" + parent;
AJAX.open("GET", "index.php" + queryString, true);
AJAX.send(null);
}

function callback(serverData)
{
alert(serverData);
}

function expandFolder(parent)
{
// Expand folder
parent.src = "collapse.jpeg";
parent.onclick = function(){ collapseFolder(parent);};
ajaxRequest(parent.id); // Sends request to the server to receive $_GET
<?php
$parentID = $_GET['parent'];
$query = mysql_query("SELECT `ID`, `name` FROM `folders` WHERE `parentID` = '$parentID' ORDER BY `name` ASC") or die("Could not run query");
?>
var children = '<?php
while($child = mysql_fetch_assoc($query))
{
print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="expand.jpeg" onclick="expandFolder(this);" id="' . $child['ID'] . '" ';
print 'style="cursor: pointer;"><a href="#" onclick="openFolder(this);" id="' . $child['name'] . '">';
print ' ' . $child['name'] . '</a><br>';
}
?>';
var id = parent.id + "br";
$(id).insert({after: children});
}


I am using the ajaxRequest() function to get ajax going and to send my variables to $_GET. However, when I use $_GET['parent'] in the expandFolder() function, the result is empty - there is no value.

So, my question is: I am sending the variable to the wrong place? If not, am I accessing it incorrectly?

Thank you for any help.

A1ien51
06-09-2009, 02:40 PM
That php code will run when the page is originally generated and not in that current page.

Have you done basic tutorials on Ajax where it shows you how to call another php file to get data and display it? That is probably what you should be doing here, call anpther php file that does what you need. Do not recall th eindex page.

Eric

aWhite89
06-09-2009, 03:08 PM
I was wondering if it was something fishy like that. Where is the tutorial of which you speak?

Thanks.

A1ien51
06-09-2009, 03:21 PM
There are tons of tutorials out there, just google Ajax Tutorial php and I am sure you can find one.

Eric