我一直在尝试使用ajax将数据提交到数据库,但我一直陷入困境。
我用简单的代码来测试它,但无论我做什么,它都没有用。
HTML / ajax代码
<?php include("osb.php");?>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--we have our html form here where user information will be entered-->
<form action='osb.php' method='post' border='0' id="form1">
<div id = "container"> <br>
<label>Name: </label> <input type='text' id="name" name='name' /><br> <br>
<label>E-mail: </label> <input type='text' id="email" name='email' /><br><br><br>
<input type='hidden' name='action' value='create' />
<input type='button' value='Submit' id="submit" />
<input type="reset" value="Reset" class="reset-org">
<div>
</form>
<script type = "text/javascript">
$(function(){
$('#submit').click(function(){
$('#container').append('<img src = "img/ajax/ajax-loader.gif" alt="Currently loading" id = "loading" />');
$.ajax({
url: 'osb.php',
type: 'POST',
data: $('#form1').serialize(),
success: function(result){
$('#response').remove();
$('#container').append('<p id = "response">' + result + '</p>');
$('#loading').fadeOut(500);
}
});
});
});
</script>
PHP代码
<?php
//set connection variables
$host = "localhost";
$username = "";
$password = "";
$db_name = "";
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
$action = isset($_POST['action']) ? $_POST['action'] : "";
if($action=='create'){ //the the user submitted the form
$data=$_POST['serialize'];
$name=$data['name']; //access data like this
$email=$data['email']; //access data like this
//include database connection
//our insert query query
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "insert into 'user' VALUES ($name,$email)";
mysqli_query($mysqli, $query);
//execute the query
if( $mysqli ->query($query) ) {
//if saving success
echo "User was created.";
}else{
//if unable to create new record
echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli->close();
}
?>
每次提交表单时都会收到这些错误:
未定义的索引:在第29行的C:\ xampp \ htdocs \ php1 \ osb.php中序列化
数据库错误:无法创建记录。
答案 0 :(得分:2)
除去
$data=$_POST['serialize'];
$name=$data['name']; //access data like this
$email=$data['email']; //access data like this
添加
$name=$_POST['name'];
$email=$_POST['email'];
此致