我有JavaScript代码(jQuery和Ajax)、一个数据库和一个PHP页面,我的Ajax正在引用这些代码。
我在这里的主要目的是:
- 我正在努力为孩子们建立一个网站(学校/专业项目)来帮助他们学习数学
- 他们必须回答一个问题,例如23+10,有不同程度的困难等等……但这并不是最重要的
- 这些值是用PHP编写到
<div>
中的。我的目标是提取它们并将它们插入到我的数据库中 - 我不会在这里写无用的细节,但他们基本上必须写一个数学答案。然后答案被发送到我的数据库,用于统计(好答案的百分比等)。所以我使用AJAX和jQuery,代码如下:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(function(){
$("#button").on("click", function(){
$.ajax({
url: "myWebsiteName.com/receiveQuestion.php",
type: "post",
data: {
id_question: $("#id_question").html(), resultat_operation: $("#reponse").html()
},
success: function() {
alert('success')
},
error : function() {
alert('error')
},
})
var num1 = parseInt(document.getElementById("num1").innerHTML, 10);
var num2 = parseInt(document.getElementById("num2").innerHTML, 10);
var reponse = parseInt(document.getElementById("reponse").value, 10);
var signe = document.getElementById("signe").textContent;
...
(and there's a function verifying the results, etc...)
引用的PHP页面代码在这里:
<?php
require('connexion.php');
require('fonctions.php');
if(isEnfant()) {
if(isset($_POST['id_question']) && isset($_POST['result_operation'])) {
try {
$id_questionInt = (int) $_POST['id_question'];
$result_operationInt = (int) $_POST['result_operation'];
$req = $bdd->prepare('INSERT INTO details (player, id_question_details, result_operation) VALUES (:id_player, :id_question, :resultOpe)');
$req -> bindValue(':id_player', $_SESSION['login_c']); // login of the children once he is online.
$req -> bindValue(':id_question', $id_questionInt);
$req -> bindValue(':resultOpe', $result_operationInt);
$req -> execute();
}
catch(PDOException $e) {
die('Error : ' . $e->getMessage());
}
}
}
?>
我尝试过的:
- 对值进行强制转换,因为显然通过post方法将这些值视为字符串
- 正在显示值,但没有结果
我通过消息知道请求是成功的,但的数据不会插入我的数据库。
您可能需要将值与PDO的一个类型常量绑定。
$id_questionInt = intval($_POST['id_question']);
$result_operationInt = intval($_POST['result_operation']);
$login_c = $_SESSION['login_c'];
$req = $bdd->prepare('INSERT INTO details (player, id_question_details, result_operation) VALUES (:id_player, :id_question, :resultOpe)');
$req -> bindValue(':id_player', $login_c); // login of the children once he is online.
$req -> bindValue(':id_question', $id_questionInt, PDO::PARAM_INT);
$req -> bindValue(':resultOpe', $result_operationInt, PDO::PARAM_INT);
$req -> execute();