В настоящее время я получаю сообщение об ошибке «Неопределенный индекс» после попытки отправить данные из файла JavaScript в PHP через запрос AJAX POST - $ _ POST выходит пустым . Учитывая, что я изучил все остальные вопросы переполнения стека по этому вопросу безрезультатно, вот что происходит:
У меня есть вопросник - ответы на этот вопросник сохраняются в массиве "all_answers". Когда я нажимаю кнопку «Готово» в своей анкете, я вызываю функцию с именем «saveAnswersInDatabase ()», которая в основном выполняет AJAX-запрос типа POST. Наряду с этим запросом POST я отправляю некоторые данные, которые являются ответами на мою анкету, которую я храню в ранее упомянутом массиве "all_answers".
Этот запрос POST выполняется в файл PHP с именем «questionnaire_php», в котором я обращаюсь к суперглобальному $_POST
, чтобы сначала определить, какое действие было запрошено, а затем я делаю SQL-запрос, чтобы INSERT
ответил на моя анкета в таблице ответов моей базы данных.
В настоящее время я получаю сообщение об ошибке Undefined index: requested_action
error.
Я безуспешно пытался:
- Добавить
dataType
из json
и text
в мой запрос AJAX POST;
- Пусть все пары
key : value
поля data
моего запроса AJAX POST будут заключены в одинарные и двойные кавычки;
Вот код.
HTML:
<!-- Questionnaire's conclusion -->
<div class="row" id="conclusion" style="display: none;">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<h6><small class="text-muted">Thank you for successfully completing this questionnaire. You may review your answers by going to the EmoJar page and selecting this content's corresponding circle.</small></h6>
<!-- 'Finish' button -->
<div class="text-center">
<button type="button" class="btn btn-info btn-sm" id="questionnaire-conclusion-finish-button" onclick="saveAnswersInDatabase()"><i class="fa fa-check icons-style"></i> Finish</button>
</div>
</div>
</div>
JS:
function saveAnswersInDatabase() {
// We prepare an AJAX request to save the answers to our questionnaire in the 'answer' table of our 'm4wb' database
$.ajax({
// 'type' determines our request's type ('GET' or 'POST')
type: "POST",
// 'url' determines where our request will go to (e.g., a server), or through (e.g., a file)
url: "php/questionnaire_php.php",
// 'data' determines what data is to be sent along with our request
data: {
"requested_action": "save_answers",
"question_1": all_answers[0],
"question_1_1": all_answers[1],
"question_2": all_answers[2],
"question_2_1": all_answers[3],
"question_3": all_answers[4],
"question_3_1": all_answers[5],
"bar_chart_colors": all_answers[6],
"question_4": all_answers[7],
"question_5": all_answers[8],
"question_6": all_answers[9],
"question_6_1": all_answers[10]
},
// 'success' determines what happens if our request is successfully fulfilled
success: function() {
console.log("The request was successfully fulfilled.");
},
// 'error' determines what happens if our request is not successfully fulfilled
error: function() {
console.log("The request could not be fulfilled.");
}
});
}
PHP:
<?php
/* Connection data */
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "m4wb";
/* Connection attempt */
$database_connection = mysqli_connect($servername, $username, $password, $databasename);
/* Connection verification */
if ($database_connection) {
echo "Connected to database.";
} else {
echo "Not connected to database.";
}
/* Requested action */
$requested_action = $_POST["requested_action"]; // '$_POST' is an array that stores all information sent in a 'POST' request
echo $requested_action;
/* Requested action verification */
// If a request to save the answers to our questionnaire was made, (...)
if ($requested_action == "save_answers") {
// (...) we get the data that was sent along with the request, (...)
$question_1 = $_POST["question_1"];
$question_1_1 = $_POST["question_1_1"];
$question_2 = $_POST["question_2"];
$question_2_1 = $_POST["question_2_1"];
$question_3 = json_encode($_POST["question_3"]); // We can't directly store arrays in a database, so we use 'json_encode()' to turn the array into a string
$question_3_1 = $_POST["question_3_1"];
$bar_chart_colors = json_encode($_POST["bar_chart_colors"]); // We can't directly store arrays in a database, so we use 'json_encode()' to turn the array into a string
$question_4 = json_encode($_POST["question_4"]); // We can't directly store arrays in a database, so we use 'json_encode()' to turn the array into a string
$question_5 = $_POST["question_5"];
$question_6 = $_POST["question_6"];
$question_6_1 = $_POST["question_6_1"];
echo $question_1, $question_1_1, $question_2, $question_2_1, $question_3, $question_3_1, $bar_chart_colors, $question_4, $question_5, $question_6, $question_6_1;
// (...) we prepare our query, (...)
$query = "INSERT INTO answer ('ID', 'USER_ID', 'CONTENT_ID', 'Q_ONE', 'Q_ONE_ONE', 'Q_TWO', 'Q_TWO_ONE', 'Q_THREE', 'Q_THREE_ONE', 'BAR_CHART_COLORS', 'Q_FOUR', 'Q_FIVE', 'Q_SIX', 'Q_SIX_ONE') VALUES ('1', '1', '1', '$question_1', '$question_1_1', '$question_2', '$question_2_1', '$question_3', '$question_3_1', '$bar_chart_colors', '$question_4', '$question_5', '$question_6', '$question_6_1')";
// (...) we execute the query, we save its result ('TRUE' or 'FALSE'), (...)
$query_result = mysqli_query($database_connection, $query);
echo $query_result;
// (...) we commit the current transaction, (...)
mysqli_commit($database_connection);
// (...) we close our database connection, (...)
mysqli_close($database_connection);
// (...) and we exit this PHP script
exit("Exited!");
}
var_dump($_POST);
exit("Exited!");
?>
Я только что получил вышеупомянутую ошибку и понятия не имею, почему. Любая помощь приветствуется! Заранее спасибо.
PS: я знаю, что могу стать жертвой инъекции, но об этом мы поговорим позже.
РЕДАКТИРОВАТЬ: Я столкнулся с этой проблемой после реализации запроса INSERT INTO, который я делаю в файле PHP, фактически не привел к добавлению данных в таблицу, в которую я хочу вставить новые данные INTO. Я быстро обнаружил, что $ _POST пуст!