Звучит так, будто вы пытаетесь устранить неисправность сразу по нескольким причинам.Прежде чем я смогу перейти к срочному вопросу, нам нужно подготовить почву, чтобы вы понимали, что должно произойти.
Во-первых, путаница с URL:
Вы все маршрутизируетечерез index.php.Следовательно, index.php должен следовать структуре, похожей на эту:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Теперь путаница с JQuery и AJAX:
Согласно https://api.jquery.com/jquery.post/ вы должны предоставить URL.
Все свойства, кроме URL, являются необязательными
Ваш JQuery AJAX отправит запрос на публикацию на вашу страницу index.php.Когда ваша страница выполняется, как показано выше, она просто напечатает {message: "Your submission was received"}
, а затем умрет.JQuery будет ожидать этого ответа и затем делать все, что вы скажете, чтобы сделать с ним (в этом примере распечатать его на консоль).
Обновить после обсуждения
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Как только у вас все заработает, вы можете взять код из receive.php
, вставить его в верхнюю часть index.php
и повторить вызов ajax на index.php
,Убедитесь, что до этого фрагмента кода невозможен вывод.