使用ajax,Javascript / jQuery和php发布到数据库无法正常工作

时间:2014-12-09 00:37:58

标签: javascript php jquery mysql ajax

我正在尝试使用AJAX,javascript和php将表单数据发布到我的mysql数据库。这是我的代码。显示我的PHP代码底部的“表单已成功提交”消息,但是当我通过phpmyadmin检查数据库时,新记录不在表中。

HTML标记:

<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX PHP and javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="css/style.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h2>Submit Form Using AJAX,PHP and javascript</h2>
<!-- Required Div Starts Here -->
<form id="form" name="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<label>Contact No :</label>
<input id="contact" type="text">
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>
<div id="clear"></div>
</div>
<div id="clear"></div>
</div>
</body>
</html>

Javascript代码:

function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var contact = document.getElementById("contact").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if (name == '' || email == '' || password == '' || contact == '') {
alert("Please Fill All Fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "ajaxjs.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}

PHP:

<?php
// Fetching Values From URL
$name2 = $_POST['name1'];
$email2 = $_POST['email1'];
$password2 = $_POST['password1'];
$contact2 = $_POST['contact1'];

$connection = mysqli_connect("localhost", "username","password","mydba"); // Establishing Connection with Server..
if (!$connection) {
  die('Could not connect: ' . mysqli_error($connection));
}

$db = mysqli_select_db($connection,"myTable"); // Selecting Database

if (isset($_POST['name1'])) {
$query = mysql_query("INSERT INTO form_element(name, email, password, contact) VALUES ('$name2', '$email2', '$password2','$contact2')"); //Insert Query
echo "Form Submitted succesfully";
}
mysql_close($connection); // Connection Closed
?>

1 个答案:

答案 0 :(得分:0)

使用

$query = mysqli_query($connection, "INSERT ...");

$query = $connection->query("INSERT ...");

尝试打印错误,如果有的话:

if (!$query) {
    echo "Error message: " . $connection->error;
}