我想将数据添加到我的数据库,并从php访问数据库获取响应。
javascript代码:
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
var responseText = "onbekend";
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
因此,当一个名称无效或已经存在时,我可以将此消息添加到我的html中的span元素。
这是我的PHP代码:
<?php
if($_POST)
{
// Create connection
$con=mysqli_connect("localhost","root","root","websitedb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = getdate();
$date_time = $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . " " . $date['hours'] . ":" . $date['minutes'] . ":" . $date['seconds'];
$uitdagerArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitdager'] . "'");
$uitgedaagdeArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitgedaagde'] . "'");
$uitdager = mysqli_fetch_array($uitdagerArray);
$uitgedaagde = mysqli_fetch_array($uitgedaagdeArray);
$uitdagerId = $uitdager['id'];
$uitgedaagdeId = $uitgedaagde['id'];
$sql="INSERT INTO duels (uitdager, uitgedaagde, aanmaakdatum, gespeeld) VALUES ('" . $uitdagerId . "','" . $uitgedaagdeId . "','" . $date_time . "','" . "0" . "')";
if(!mysqli_query($con,$sql)) {
echo mysql_errno() . ": " . mysql_error() . "\n";
}
else {
echo "Duel Toegevoegd";
}
mysqli_close($con);
}
?>
那么我的php代码中的echo中的文本是否可能会从succes函数传递给'response'?
编辑:
这是我的HTML代码
<div id="nieuwDuel">
<h2>Nieuw Duel</h2>
<form name="form" method="post">
Uitdager: <input type="text" id="naamUitdager" placeholder="naam uitdager">
Uitgedaagde: <input type="text" id="naamUitgedaagde" placeholder="naam uitgedaagde">
<input type="submit" class="nieuwDuelToevoegen">
</form>
<span id="duelToegevoegd" style="display:none"></span>
<a href="index.php#home">Home</a>
</div>
答案 0 :(得分:1)
是的它应该有效。尝试将JS更改为
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
console.log(response);//This will output the response you are getting to the console so you can check it
$("#duelToegevoegd").html(response);
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
此外,我不会回应你回到客户端的任何错误
echo "Failed to connect to MySQL: " . mysqli_connect_error();
虽然这取决于用户是谁,但您不希望任何未经授权的人看到这些错误
答案 1 :(得分:1)
我认为您的PHP代码是正确的。那么你需要改变的是你的jQuery代码。
只需更改以下代码:
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
进入以下:
responseText = response;
$('#duelToegevoegd').html(responseText);
我不知道你将要做什么
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
所以,我暂时把它留下来
希望有所帮助