我正在尝试使用PHP和Ajax将表单详细信息保存在数据库中。它包括文本字段和图像。我的数据没有保存在mysql中。如果我要保存不带ajax的数据,则效果很好。 因此,请在我的代码中帮帮我。
这是我将详细信息保存在数据库中的方式:
// Create database connection
$db = mysqli_connect("localhost:8889","root","123","temp") or die("could not connect to server");
// If upload button is clicked ...
$finame=$_POST['firstname'];
$laname=$_POST['lastname'];
$image_text = $_POST['image_text'];
$template = $_POST['template'];
$address = $_POST['address'];
$email = $_POST['email'];
$experience = $_POST['experience'];
// Get image name
$image = $_FILES['image']['name'];
$directory = date("Y").'/'.date("m").'/'.date("d").'/';
//If the directory doesn't already exists.
if(!is_dir($directory)){
//Create our directory.
mkdir($directory, 755, true);
}
// image file directory
$target = $directory.basename($image);
$sql = "UPDATE person SET fname='$finame', sname='$laname', image='$image', about='$image_text', template='$template', address='$address', email='$email', experience='$experience' where id=1";
// execute query
mysqli_query($db, $sql);
?>
这是我在mysql中的表:
CREATE TABLE `person` (
`fname` varchar(30) DEFAULT NULL,
`sname` varchar(30) DEFAULT NULL,
`image` mediumblob NOT NULL,
`about` varchar(10000) NOT NULL,
`id` int(10) NOT NULL,
`template` int(10) NOT NULL,
`address` varchar(300) NOT NULL,
`email` varchar(100) NOT NULL,
`experience` varchar(1000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
这是我的表单和脚本:
<form enctype="multipart/form-data" id="frmBox" method="post">
<input type="text" name="firstname" id="fname" placeholder="First Name">
<input type="text" name="lastname" id="lname" placeholder="Last Name">
<input type="text" name="address" placeholder="Your address..." id="address">
<input type="file" name="image" id="image">
<textarea id="text" cols="30" rows="4" name="image_text" placeholder="Say something"></textarea></div>
<input type="radio" value="1" name="template" style="margin-left: 15px;"> Template 1
<input type="radio" value="2" name="template"> Template 2
<input type="text" name="email" placeholder="Your Email" id="email">
<textarea id="experience" cols="30" rows="4" name="experience" placeholder="Say something..."></textarea>
<h3 id="success"></h3>
<input type="submit" name="upload" class="sub-btn" value="submit">
</form>
<script type="text/javascript">
$('document').ready(function(){
$('#frmBox').submit(function(){
$.ajax({
type: 'POST',
url: 'insert.php',
data: $('#frmBox').serialize(),
success: function(response){
alert(response);
}
});
});
// var form = document.getElementById('frmBox').reset();
});
</script>
答案 0 :(得分:1)
您必须在脚本内使用preventDefault
来防止提交表单。
然后,您将能够将除图像之外的数据传递到您的php脚本。您可以将FormData
用于此目的。
这是脚本:
<script type="text/javascript">
$('document').ready(function(){
$('#frmBox').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'insert.php',
data: formData,
processData: false,
contentType: false,
success: function(response){
alert(response);
}
});
});
});
</script>