doutouhe5343 2013-12-02 16:38
浏览 53
已采纳

使用带有数据库信息的下拉菜单填充文本框

hello people i am currently pulling my hair out trying to figure out how to populate text boxes with the information in a database after the user has selected "date" for example from a dropdown menu.

my dropdown menu is currently being populated by the departure_date of a tour and i would like all of the other information connected to that date to be displayed into the text boxes on the page.

this is for a project i am working on and our current server does not support pdo unfortunately.

this is making my head spin and i cannot think about how i am supposed to accomplish this. searching on the internet did not give me any useful information.

here is my html code for the select box and text boxes.

<div>

  <label><strong>Search Tours</strong></label>
<form>
  <p>
    <select name="lst_tour">
      <option value="">Select a Tour:</option>
      <?php 

foreach ( $results as $option ) : ?>
      <option value="<?php

          echo $option->departure_date; ?>"><?php echo $option->departure_date; ?>    </option>
      <?php endforeach; ?>
    </select>
  </p>
  <p><strong>List of Tour Details</strong></p>


        <input name="txt_tourname" type="text" id="txt_tourname" readonly="readonly"     value = <?php echo $ltour_name ?> />
      </label></td>

        <input name="txt_departuredate" type="text" id="txt_departuredate"  readonly="readonly" />
      </label>


        <input name="txt_tourdetails" type="text" id="txt_tourdetails"     readonly="readonly" />
      </label>

and here is my php connection code

     <?php
session_start();

        $server = "server";
        $schema = "schema";
        $uid = "name";
        $pwd = "pass";

    $tour_name =$_POST["txt_tourname"];
    $departure_date =$_POST["txt_departuredate"];
    $tour_details =$_POST["txt_tourdetails"];
    $no_of_volunteers =$_POST["txt_noofvolunteers"];


mysql_connect($server , $uid , $pwd) or die ("server not found");
mysql_select_db($schema) or die ("Database not found");

     $sql = "SELECT * FROM tour";
     $query = mysql_query($sql);
     while ( $results[] = mysql_fetch_object ( $query ) );
     array_pop ( $results );
?>

any help would be great

  • 写回答

1条回答 默认 最新

  • dr6673999 2013-12-02 16:58
    关注

    Ok, this question is asked and answered a lot and most of those who ask have a concept problem. I'll explain this in parts, and afterwards I'll post a clean rewrite of your code, including a javascript file for you to dive in and learn

    • The idea behind what you are trying to do involves some sort of behaviour on the part of what looks most likely to be a static html page
    • Javascript adds behaviour to your otherwise dead html, allowing you to trigger events and generate responses
    • Ajax was born out of a collective necessity to be able to talk to the server while the user did not leave the page. It allows us to make requests behind the scene (asynchronously) and bring back info
    • the power to combine behaviour with asynchronous requests is the base of today's rich internet applications (RIA for short?)

    Ok, don't take that at face value, do some research on it and and you'll find out the potential. In the meantime I'll create a mockup of what it looks like you want and I'll be back with it as soon as I can. Be on the lookout for other answers, there is a lot of knowledgeable people around ^^

    edits

    html form

    <form method="somemethod" action="somescript.php">
      <select name="lst_tour" id="lst_tour">
        <option value="">Select a Tour:</option>
        <?php foreach ( $results as $option ) {
          ?><option value="<?php echo $option->departure_date; ?>"><?php echo $option->departure_date; ?></option><?php
        } ?></select>
      <!-- these will be "magically" populated, they conveniently have ids ^^ -->
      <input name="txt_tourname" type="text" id="txt_tourname" readonly="readonly" />
      <input name="txt_departuredate" type="text" id="txt_departuredate" readonly="readonly" />
      <input name="txt_tourdetails" type="text" id="txt_tourdetails" readonly="readonly" />
    </form>
    

    javascript

    lot's of edits and rewrites. This is a noisy script with lots of alerts so please be patient and sequentially start removing alerts as you no longer need them. Attention: the select tag has an id that I use to find it and attach the event handler

    (function(){
      var
        // the php script that's taking care of business
        url = 'http://path/to/handling/ajaxscript.php',
        select,
        // assume these are the ids of the fields to populate
        //  AND assume they are the keys of the array thats comming from the server
        inputs = ['txt_tourname','txt_departuredate','txt_tourdetails'],
        // the XMLHttpRequest, I'm not recycling it but, oh well
        xhr,
        // the onReadyStateChange handler function, it needs access to xhr
        xhrRSC,
        // event handler, called for <select>."onChange"
        onChooseDate,
        // response handler that will be executed once the xhrRSC deems it ready
        populateData,
        // convenient event handlers
        onLoad, onUnload;
      xhrRSC = function () {
        if (xhr && xhr.readyState !== 4) {return;}
        alert('the server response has completed. Now continue with the population');
        populateData(JSON.parse(xhr.responseText));
        xhr = null;
      };
      onChooseDate = function () {
        var date = select.options[select.selectedIndex].value;
        alert('I have been changed. Did I select the right date: '+date
          +'. Now we send some info to the server');
        // AJAX: make xhr
        xhr = new XMLHttpRequest();
        // AJAX: setup handler
        xhr.onreadystatechange = xhrRSC;
        // AJAX: open channel
        xhr.open('get',url+'?ajax=1&date='+date,true);
        // AJAX: send data (if method post)
        xhr.send(null);
        // if we had jQuery, we could condense all this into one line
        // $.post(url,{ajax:1,date:date},populateData,'json');
      };
      populateData = function (json) {
        // we have the content from the server. Now json decode it
        alert('json data => '+json.toSource());
        // foreach input id execute function
        inputs.forEach(function(v){
          // set the value of each input to the data sent by the server
          alert('setting input "'+v+'" to "'+json[v]+'"');
          document.getElementById(v).value = json[v];
        });
      };
      onLoad = function () {
        alert('page has loaded');
        // assume the <select> tag has an id of "lst_tour", just as it's name
        select = document.getElementById('lst_tour');
        // the "change" event is fired when the user changes the selected <option>
        select.addEventListener('change',onChooseDate,false);
      };
      onUnload = function () {
        select.removeEventListener('change',onChooseDate,false);
        select = null;
      };
      window.addEventListener('load',onLoad,false);
      window.addEventListener('unload',onUnload,false);
    }());
    

    ajax script, the php handler

    <?php
    // this file has $_GET populated with 'ajax' => '1' and 'date' => 'what the user chose'
    if (!isset($_GET['ajax'])) die('this is not how its supposed to work');
    // we must protect the output
    ob_start();
    // your initializers
    // your logic: it should make the selection, then populate the array to be JSON encoded
    
    $response = array(
      'txt_tourname' => $txt_tourname,
      'txt_departuredate' => $txt_departuredate,
      'txt_tourdetails' => $txt_tourdetails
    );
    // you may want to log this for debugging
    // server output has been protected
    ob_end_clean();
    header('Content-Type: text/json');
    echo json_encode($response);
    // the client has what he wanted
    exit;
    

    There it is, it's not tested and it's a handfull but with careful review you will learn a LOT. Also read Crockford and take into consideration the benefits of using jQuery, that javascript could have been much less complicated, and more efficient with jQuery

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探