Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Can I pass Ajax var result to PHP code?

Can I pass Ajax var result to PHP code?

Can I pass Ajax var result to PHP code?

**Disclaimer: It's been a while since I last wrote any code. The quality of my code is likely to be sub-par. You've been warned.**


I am coding a basic form that uses a SELECT list I populate from my database.

However, my user needs the form to be dynamic and wants to be able to select either `MasterTable1` or `MasterTable2` or `MasterTable3`...

Instead of hardcoding the table name for the database query that populates the SELECT list, I attempted to implement a basic Ajax action (used example from http://www.w3schools.com/PHP/php_ajax_database.asp")...and that's when I lost my sanity...

I can output `<div id='txtHint'></div>` in my page and it shows the correct table name that was picked.

But how do I pass the correct table name to my query that will populate my SELECT list???

I tried


     <select name="DBFilename" id="DBFilename" size="0">
     <option value="">Select Filename</option>
    $sql="select distinct filename from "."<div id='txtHint'></div>";
    $result = mysql_query($sql);
     while ($row = mysql_fetch_array($result)){ ?>  
     <option value="<?php echo $row['filename']; ?>"><?php echo $row['filename']; ?></option>
     <?php } ?>

But to no avail. This is confusing  since I can do this...


    <body><form><select name="SrcTbl" id="SrcTbl" size="0" onchange="showTable(this.value)">
        <option value="">Select Data Table</option>
        <option value=""> </option>
    <option value="MasterTable1">up to 31 days old</option>
    <option value="MasterTable2">62 days old</option>
    </form><br /><div id="txtHint"><select name="tabList"><option></option></select> </div>

And the name of my table will be displayed in the SELECT list 'tablist'.

How do I pass the correct table name to my query that will populate my SELECT list? Thanks!!

Form code in pastebin.com => http://pastebin.com/raw.php?i=uQf3a30N

RE: Can I pass Ajax var result to PHP code?

To clarify...

That <div> is supposed to end up being the table name that is returned by the Ajax script.  

RE: Can I pass Ajax var result to PHP code?

remember that php web applications (and most web apps) are stateless.  you cannot interrupt output to the browser to wait for user input.

data sent to the server by ajax is accessible either in the $_POST or $_GET superglobal depending on the method employed.

i have cleaned up your code a bit and added some ajax functionality for the display of the final results.  hopefully you can see how things work and thus take it on from here.  your code is weak on security and exposed to normal attack vectors so don't deploy this anywhere vulnerable and when you're ready read up on security generally.


ini_set('error_reporting', true);
error_reporting(E_ALL ^ E_NOTICE);
define(MYDIR, $_SERVER['DOCUMENT_ROOT']."/filedepot");
$host= 'localhost';
$user = 'vatroot';
$pwd = 'ork';
$db = 'dev';

$con = mysql_connect($host, $user, $pwd);
if (!$con) {
    die('Could not connect: '.mysql_error());
mysql_select_db($db, $con) or die(mysql_error());

function check_search() {
    $errors = $results = null;
    if (isset($_POST['submit'])) {
        if (! empty($_POST['DBFilename'])) {
            $results = doFileSearch();
    } else
        $errors = "Please select an option before you hit SUBMIT.";
    return Array($results, $errors);

function doFileSearch($table=null, $DBFilename=null) {
    $result = ';
    if ( empty($DBFilename) && empty($_POST['DBFilename']))return null;
    if ( empty($table) && empty($_POST['SrcTbl'])) return null;
    $DBFilename = isAjax() ? $DBFilename : $_POST['DBFilename'];
    $table = isAjax() ? $table : $_POST['SrcTbl'];
    //add some escaping.  this is imperfect
    $table = '`' . $table . '`';
    $mydir = MYDIR;
    $dir = opendir($mydir);
    //must escape $DBFilename to prevent sql injection
    $sql = "select filename from $table where filename='".mysql_real_escape_string($DBFilename)."'";
    $getfilename = mysql_query($sql);
    if(!$getfilename) return false;
    while ($row = mysql_fetch_array($getfilename)) {
        $filename = $row['filename'];
        $result .= '<tr><td><a href="'.basename($mydir).'/'.$filename.'" target="_blank">'.$filename.'</a></td></tr>';
    if ($result) {
        $result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
    return $result;
//create a function to retrieve the files names
function getFileNames($table){
    $options = array();
    $sql="select distinct filename from $table";
    $result = mysql_query($sql);
    if(!$result) return false;
    while ($row = mysql_fetch_array($result)):
        $options[] = array( 'text'=>$row['filename'],
    return $options;
function isAjax(){
    return isset($_REQUEST['a']) && $_REQUEST['a'] == 1;
    if (isAjax()):
    switch ($_REQUEST['action']):
        case 'getFileNames':
            $table = trim($_GET['q']);
            $options = getFileNames($table);
            if($options === false):
                $return = array('result'=>false);
                $return = array('result'=>true, 'options'=>$options);
            echo json_encode($return);
            die; //should always expressly kill the process with ajax calls
        case 'getFileList':

RE: Can I pass Ajax var result to PHP code?

oops.  slight error there.  replace the relevant bit of code with the following


//remove all but the first option from the element
for (var i=elem.length-1; i >= 1; i--){
    elem.options[i] = null;

for more help on the javascript nature of your query, check out the javascript forum.   

RE: Can I pass Ajax var result to PHP code?

Thanks for your help. I need to rework the whole flow of the app. Thanks for taking the time.  

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close