Я пытаюсь использовать jquery с ajax-запросом для отправки значения выбора из выпадающего списка, чтобы различные флажки могли отображаться в зависимости от выбора.
Я использовал это, и это работало, но отправлял запрос GET дважды и думал, что должен быть более эффективный способ:
success: function(html) {
window.location.href= "search.php?industry=" + industry + "";
}
Запрос GET для приведенного ниже кода работает, и флажки отображаются, но форма повторяется, и я не понимаю, почему. (изображение — https://ibb.co/j7Ag7m)
В файле search.php находится весь код. Я попытался сохранить часть формы для флажков в другом файле, например url: «searchData.php», но произошло то же самое.
Может кто-нибудь сказать мне, пожалуйста, где я иду не так?
<?php
if(isset($_GET['industry'])) {
$request = $_GET[‘industry’];
// insert to database here works
}
?>
<form id="skillsSelectForm" role="form" method="get">
<select id="industry" name="industry">
<option value="Administration">Administration</option>
<option value="Business">Business</option>
<option value="Charity">Charity</option>
<option value="Healthcare">Healthcare</option>
</select>
<script>
$('#industry').change(function() {
var industry = $(this).val();
$.ajax({
type: "GET",
url: "search.php",
data: { industry: industry },
success: function(data) {
$("#results").html(data);
}
});
});
</script>
<div id="results"></div>
<?php
// change checkboxes displayed based on $request
if(isset($request)) {
foreach ($allskills as $skill):
if($request == $skill['industry']) {
echo '<label for="'.$skill['skill'].'">
<input type="checkbox" name="'.$skill['skill'].'" value="'.$skill['skill'].'"> '.$skill['skill'].'</label>';
}
endforeach;
}
?>
<input type="submit" name="search" value="Search">
</form>
Я вижу, что ваша проблема в вашем коде состоит в том, что вы перезагружаете всю страницу до самого себя внутри $("#result")
элемент. Вот почему, похоже, он выполняется дважды.
Когда запускается событие $ (). Change, оно получает всю HTML-страницу и публикует ее внутри #result
элемент div.
Вы можете упростить использование метода GET, попробовав это,
<form id="skillsSelectForm" role="form" method="get">
<select id="industry" name="industry">
<option value="">Select Industry</option>
<option value="Administration">Administration</option>
<option value="Business">Business</option>
<option value="Charity">Charity</option>
<option value="Healthcare">Healthcare</option>
</select>
<div id="ChkList"></div>
<input type="submit" name="search" value="Search">
</form><script>
$('#industry').change(function() {
var industry = $(this).val();
$.ajax({
type: "GET",
url: "getSkillList.php",
data: { industry: industry },
dataType: 'json'
success: function(data) {
if(data.length <> 0){
var $elem = $("#ChkList");
var output = '';
$elem.empty(); /* empty before appending the skills list */
$.each(data, function(a,b){
output += "<label>"+b.skill+"</label><input type='checkbox' id='"+b.id+"' name=''><br>";
})
$elem.append(output);
}
}
});
});
</script>getSkillList.php
<?php
$industry_id = $_POST['industry'];
/* You connection string here */
$query = "Select * from skill_list where industry_id = $industry_id";
$sth = mysqli_query($query);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
/* return the result of the query $skilllist in json format */
?>
Я, конечно, не могу сказать, почему ваш код не удался, потому что ваши объяснения мне не так понятны, а также потому, что вы предоставили неполные коды или просто фрагменты кода. Извини… 🙂
Тем не мение, window.location.href
наверняка не нужно.
Так вот, как бы я это сделал.
Есть только страница search.php, с формой и без запроса ajax. Если флажок изменен, просто отправьте форму. Таким образом, будет два способа отправки формы:
В PHP-коде вверху страницы две ситуации различаются с помощью:
$industry = 'Administration'; // Default combobox value.
if (isset($_POST['searchButton'])) { // Form was submitted by clicking on the "searchButton".
$industry = $_POST['industry']; // Assign the chosen combobox value.
// ...
} elseif (isset($_POST['industry'])) { // Form was submitted by changing the "industry" combobox value.
$industry = $_POST['industry']; // Assign the chosen combobox value.
// ...
}
Я использовал «POST» для атрибута метода формы (рекомендуется). Остальное подробно прокомментировано в моем коде.
<?php
/*
* Set the default industry. The value will be overwritten
* by the combobox value posted upon the form submission.
*/
$industry = 'Administration';
if (isset($_POST['searchButton'])) { // Form was submitted by clicking on the "searchButton".
$industry = $_POST['industry']; // Assign the chosen combobox value.
/*
* Read the values of the posted skills checkboxes here. In the $_POST they are
* saved in an array like this:
*
* [skills] => Array (
* [0] => 1
* [1] => 3
* )
*/
/*
* Search in db and fetch the searching results into an array.
* How you search is up to you. I'll use here just an array example.
*/
$searchResults = [
[
'myarraykey1' => 13,
'myarraykey2' => 'a value',
//...
],
[
'myarraykey1' => 25,
'myarraykey2' => 'other value',
//...
],
[
'myarraykey1' => 37,
'myarraykey2' => 'some other value',
//...
],
];
} elseif (isset($_POST['industry'])) { // Form was submitted by changing the "industry" combobox value.
$industry = $_POST['industry']; // Assign the chosen combobox value.
}
/*
* If the form was not submitted yet, then $industry has the default value "Administration".
* Otherwise, if the form was submitted (by clicking on the "searchButton" or by changing
* the "industry" combobox value), $industry has the value of the submitted combobox value.
*
* Fetch the skills list from the db for the selected industry with an sql statement like:
* "SELECT id, name FROM skills WHERE industry = $industry".
* Note: use prepared statements!
*
* Let's say, if the form was submitted in one of the two ways, the industry chosen in the
* combobox was "Administration" or "Environment".
*
* The if-elseif case bellow is just a simulation of getting skills array based on a non-existent db.
* In your case, fetch the skills from db and define the $skills array, without any if-elseif statement.
*/
if ($industry === "Administration") {
$skills = [
[// 1st record
'id' => 1,
'name' => 'Management',
],
[// 2nd record
'id' => 2,
'name' => 'Insurance',
],
[// 3rd record
'id' => 3,
'name' => 'Financial and control',
],
];
} elseif ($industry === "Environment") {
$skills = [
[// 1st record
'id' => 1,
'name' => 'Agronomy',
],
[// 2nd record
'id' => 2,
'name' => 'Ansible',
],
[// 3rd record
'id' => 3,
'name' => 'Business Case Development',
],
];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#industry').on('change', function () {
$('#skillsSelectForm').submit();
});
});
</script>
<style type="text/css">
body { padding: 30px; }
button { padding: 5px 10px; font-size: 14px; background-color: #8daf15; color: #fff; border: none; }
</style>
</head>
<body>
<h3>Skills Search</h3>
<form id="skillsSelectForm" action="" method="post">
<select id="industry" name="industry">
<option value="Administration" <?php echo $industry === 'Administration' ? 'selected' : ''; ?>>
Administration
</option>
<option value="Environment" <?php echo $industry === 'Environment' ? 'selected' : ''; ?>>
Environment & Agriculture
</option>
</select>
<br/><br/>
<div id="skillsList">
<?php
foreach ($skills as $skill) {
$id = $skill['id'];
$name = $skill['name'];
?>
<label for="skill_<?php echo $id; ?>">
<?php echo $name; ?>
</label>
<input type="checkbox" name="skills[]" id="skill_<?php echo $id; ?>" value="<?php echo $id; ?>" />
<br/>
<?php
}
?>
</div>
<br/>
<button type="submit" name="searchButton">
Search
</button>
</form>
<?php
if (isset($searchResults)) { // The form was not yet submitted by clicking on the "searchButton", so the array doesn't exist yet.
?>
<br/><hr/><br/>
<div id="searchResults">
<?php
if ($searchResults) { // Array is not empty, e.g. search results were found.
foreach ($searchResults as $searchResult) {
$myArrayValue1 = $searchResult['myarraykey1'];
$myArrayValue2 = $searchResult['myarraykey2'];
//...
?>
<div class="search-result-record">
<?php echo $myArrayValue1; ?> » <?php echo $myArrayValue2; ?>
</div>
<?php
}
} else { // Array is empty, e.g. no search results found.
?>
<span class="no-search-results">
No search results found
</span>
<?php
}
?>
</div>
<?php
}
?>
</body>
</html>
Это на самом деле элегантный. Есть две страницы:
Первый ajax извлекает список навыков в готовом документе. Второй ajax извлекает список навыков на событии обмена combobox’а.
Форма отправляется как обычно, нажав на кнопку «searchButton».
<?php
if (isset($_POST['searchButton'])) { // Form was submitted by clicking on the "searchButton".
$industry = $_POST['industry'];
/*
* Read the values of the posted skills checkboxes here. In the $_POST they are
* saved in an array like this:
*
* [skills] => Array (
* [0] => 1
* [1] => 3
* )
*/
/*
* Search in db and fetch the searching results into an array.
* How you search is up to you. I'll use here just an array example.
*/
$searchResults = [
[
'myarraykey1' => 13,
'myarraykey2' => 'a value',
//...
],
[
'myarraykey1' => 25,
'myarraykey2' => 'other value',
//...
],
[
'myarraykey1' => 37,
'myarraykey2' => 'some other value',
//...
],
];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
function getSkillsList() {
var industry = $('#industry').val();
$.ajax({
method: 'post',
dataType: 'html',
url: 'getSkillsList.php',
data: {
industry: industry
},
success: function (response, textStatus, jqXHR) {
$('#skillsList').html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + '<br />' + errorThrown);
}
});
}
$(document).ready(function () {
getSkillsList();
$('#industry').on('change', function () {
getSkillsList()
});
});
</script>
<style type="text/css">
body { padding: 30px; }
button { padding: 5px 10px; font-size: 14px; background-color: #8daf15; color: #fff; border: none; }
</style>
</head>
<body>
<h3>Skills Search</h3>
<form id="skillsSelectForm" action="" method="post">
<select id="industry" name="industry">
<option value="Administration" <?php echo isset($industry) && $industry === 'Administration' ? 'selected' : ''; ?>>
Administration
</option>
<option value="Environment" <?php echo isset($industry) && $industry === 'Environment' ? 'selected' : ''; ?>>
Environment & Agriculture
</option>
</select>
<br/><br/>
<div id="skillsList"></div>
<br/>
<button type="submit" name="searchButton">
Search
</button>
</form>
<?php
if (isset($searchResults)) { // The form was not yet submitted, so the array doesn't exist yet.
?>
<br/><hr/><br/>
<div id="searchResults">
<?php
if ($searchResults) { // Array is not empty, e.g. search results were found.
foreach ($searchResults as $searchResult) {
$myArrayValue1 = $searchResult['myarraykey1'];
$myArrayValue2 = $searchResult['myarraykey2'];
//...
?>
<div class="search-result-record">
<?php echo $myArrayValue1; ?> » <?php echo $myArrayValue2; ?>
</div>
<?php
}
} else { // Array is empty, e.g. no search results found.
?>
<span class="no-search-results">
No search results found
</span>
<?php
}
?>
</div>
<?php
}
?>
</body>
</html>
<?php
/*
* Get the industry - the value posted through the ajax
* request when the onchange event of the combobox or the window's onload event is raised.
*/
if (isset($_POST['industry'])) {
$industry = $_POST['industry'];
/*
* Fetch the skills list from the db for the selected industry with an sql statement like:
* "SELECT id, name FROM skills WHERE industry = $industry".
* Note: use prepared statements!
*
* The if-elseif case bellow is just a simulation of getting skills array based on a non-existent db.
* In your case, fetch the skills from db and define the $skills array, without any if-elseif statement.
*/
if ($industry === "Administration") {
$skills = [
[// 1st record
'id' => 1,
'name' => 'Management',
],
[// 2nd record
'id' => 2,
'name' => 'Insurance',
],
[// 3rd record
'id' => 3,
'name' => 'Financial and control',
],
];
} elseif ($industry === "Environment") {
$skills = [
[// 1st record
'id' => 1,
'name' => 'Agronomy',
],
[// 2nd record
'id' => 2,
'name' => 'Ansible',
],
[// 3rd record
'id' => 3,
'name' => 'Business Case Development',
],
];
}
foreach ($skills as $skill) {
$id = $skill['id'];
$name = $skill['name'];
?>
<label for="skill_<?php echo $id; ?>">
<?php echo $name; ?>
</label>
<input type="checkbox" name="skills[]" id="skill_<?php echo $id; ?>" value="<?php echo $id; ?>" />
<br/>
<?php
}
}