以下代码成功将数据提交到mysql数据库。但是,该表单在字段为空时不会显示错误,并且在成功插入数据时不会用成功消息填充div。下面的php文件显示,如果insert成功,则结果变量设置为1,这反映在ajax的if else条件中。
<body>
<div id = "container" >
<h3>jQuery AJAX Post method example with php and MySQL</h3>
<p><strong>Please fill in the form and click save.</strong></p>
<div id="message"></div>
<form name='form1'>
<table align = "">
<tr><td></td></tr>
<tr>
<td>
<label>First Name:</label>
</td>
<td>
<input type='text' placeholder='First Name' name='first_name' id= 'first_name' required ><br />
</td>
</tr>
<tr>
<td>
<label>Last Name:</label>
</td>
<td>
<input type='text' placeholder='Last Name' name='last_name' id='last_name' required ><br />
</td>
</tr>
<tr>
<td>
<label>Email:</label>
</td>
<td>
<input type='email' name='email' placeholder='Email' id='email' required ><br />
</td>
</tr>
<tr>
<td> </td>
<td>
<input class='btn' type="button" id = "saveusers" value = "Save" />
</td>
</tr>
</table>
</form>
</div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#saveusers").on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
$.ajax({
method: "POST",
url: "saverecords_ajax.php",
data: { "first_name": first_name, "last_name": last_name, "email": email},
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
var cls = '';
if(result == 1) {
str = 'User record saved successfully.';
cls = 'success';
}else if( result == 2) {
str = 'All fields are required.';
cls = 'error';
}else if( result == 3) {
str = 'Enter a valid email address.';
cls = 'error';
}else{
str = 'User data could not be saved. Please try again';
cls = 'error';
}
$("#message").show(3000).html(str).addClass('success').hide(5000);
});
});
});
</script>
</body>
saverecords_ajax.php文件
<?php
$host = "localhost";
$username = "root";
$password = "password";
$dbname = "testing";
$result = 0;
/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection */
if ($conn->connect_error) {
die("Connection to database failed: " . $conn->connect_error);
}
/* Get data from Client side using $_POST array */
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email'];
/* validate whether user has entered all values. */
if(!$fname || !$lname || !$email){
$result = 2;
}elseif (!strpos($email, "@") || !strpos($email, ".")) {
$result = 3;
}
else {
//SQL query to get results from database
$sql = "insert into users (first_name, last_name, email) values (?, ?, ?) ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $fname, $lname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close();