Привет, люди, которых я сейчас вытаскиваю, пытаясь понять, как заполнять текстовые поля информацией в базе данных после того, как пользователь выбрал "дату", например, из выпадающего меню.
мое выпадающее меню в настоящее время заполняется tour_date тура, и я хотел бы, чтобы вся другая информация, связанная с этой датой, отображалась в текстовых полях на странице.
это для проекта, над которым я работаю, и наш текущий сервер не поддерживает pdo, к сожалению.
это заставляет мою голову вращаться, и я не могу думать о том, как я должен это делать. поиск в Интернете не дал мне никакой полезной информации.
вот мой html-код для окна выбора и текстовых полей.
<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>
и вот мой код подключения php
<?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 );
?>
любая помощь будет большой
Хорошо, этот вопрос задают и много отвечают, и большинство тех, кто спрашивает, имеют проблему с концепцией. Я объясню это по частям, а потом опубликую чистую переписку с вашим кодом, включая файл javascript для вас, чтобы погрузиться и узнать
Хорошо, не принимайте это по номиналу, делайте некоторые исследования по этому вопросу, и вы узнаете о потенциале. Тем временем я создам макет того, что он похож на вас, и я вернусь с ним, как только смогу. Будьте в поиске других ответов, есть много знающих людей вокруг ^^
<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>
много изменений и переписываний. Это шумный сценарий с множеством alerts
поэтому, пожалуйста, будьте терпеливы и последовательно начинайте удаление предупреждений, поскольку они вам больше не нужны. Внимание: тег select имеет идентификатор, который я использую, чтобы найти его и присоединить обработчик событий
(function(){
var
// the php script that 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 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);
}());
<?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;
Там он, он не проверен, и это ручная работа, но с тщательным обзором вы узнаете много. Также прочитайте Crockford и учтите преимущества использования jQuery, что javascript мог быть намного менее сложным и более эффективным с помощью jQuery