我的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);
?>
答案 0 :(得分:2)
您的处理程序需要return false;
指示浏览器不要执行常规提交操作。
(另外,您应该考虑使用表单的submit
事件,而不是按钮的click
事件。)
<script type="text/javascript">
$(function(){
$("form.addItem").submit(function(){
// Start AJAX send
jQuery.ajax({
// ... your parameters ...
});
return false;
});
});
</script>