Smart questions
Smart answers
Smart people
Join Tek-Tips Forums
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • 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!

Join Tek-Tips
*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.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Can I pass Ajax var result to PHP code?

kristo5747 (Programmer) (OP)
2 Sep 11 19:24
**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.**

Greetings.

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

CODE

     <select name="DBFilename" id="DBFilename" size="0">
     <option value="">Select Filename</option>
    <?php
    $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 } ?>
     </select>

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

CODE

    ...
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","gettable.php?q="+str,true);
    xmlhttp.send();
    }
    </script></head>
    <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>
    </select>
    </form><br /><div id="txtHint"><select name="tabList"><option></option></select> </div>
    </body></html>

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
kristo5747 (Programmer) (OP)
2 Sep 11 19:30
To clarify...

That <div> is supposed to end up being the table name that is returned by the Ajax script.  
jpadie (TechnicalUser)
3 Sep 11 4:17
remember that php web applications (and most web apps) are stateless.  you cannot interrupt output to the browser to wait for user input.
http://en.wikipedia.org/wiki/Stateless_server

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.

CODE


<?php
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'],
                            'value'=>$row['filename']);
    endwhile;
    return $options;
}
function isAjax(){
    return isset($_REQUEST['a']) && $_REQUEST['a'] == 1;
}
if(isset($_REQUEST['action'])):
    if (isAjax()):
    switch ($_REQUEST['action']):
        case 'getFileNames':
            $table = trim($_GET['q']);
            $options = getFileNames($table);
            if($options === false):
                $return = array('result'=>false);
            else:
                $return = array('result'=>true, 'options'=>$options);
            endif;
            echo json_encode($return);
            die; //should always expressly kill the process with ajax calls
        break;
        
        case 'getFileList':
            
jpadie (TechnicalUser)
3 Sep 11 6:29
oops.  slight error there.  replace the relevant bit of code with the following

CODE


//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.   
kristo5747 (Programmer) (OP)
6 Sep 11 13:25
Thanks for your help. I need to rework the whole flow of the app. Thanks for taking the time.  

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!

Back To Forum

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:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More...

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close