我的ajax调用有问题。我正在通过 php 向 mySQL 提交一些信息,提交部分运行良好,它正在将数据添加到数据库中,但是 ajax 函数没有在后台加载该 php,而是在窗口中加载它并显示 php 文件结果。
这是HTML代码。
<form action="upload.php" class="addItem" method="post">
Firstname:<br><input type="text" class="firstname" name="firstname" /><br>
Lastname:<br><input type="text" class="lastname" name="lastname" /><br>
Age:<br><input type="text" class="age" name="age" /><br>
Photo:<br><input type="file" name="image" accept="image/jpeg" /><br><br>
<input type="submit" class="submitItem" value="Add Row" />
</form>
<a href="logout.php">Logout</a>
</div>
<script>
$(document).ready(function(){
$(".submitItem").click(function(){
// Start AJAX send
jQuery.ajax({
// Enter below the full path to your "send" php file
url: "upload.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
// If form submission is successful
if ( html == 1 ) {
$('.successMessage').show(200);
$('.successMessage').delay(2000).hide();
}
// Double check if maths question is correct
else {
$('.errorMessage').show(200);
$('.errorMessage').delay(2000).hide();
}
}
});
});
});
</script>
这是PHP代码
<?php
$name = $_POST['firstname'];
$surname = $_POST['lastname'];
$age = $_POST['age'];
if(($name === "") || ($surname === "") || ($age === "")){
echo "please fill in all fields";
} else {
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
if ($sql) { echo "1"; }
else{echo "error";}
}
mysql_close($con);
?>