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

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

问题描述:

I am trying to post form data to my mysql database with AJAX, javascript and php. Here is my code. My "Form Submitted successfully" message at the bottom of my php code is displayed but when I check the database through phpmyadmin the new record isn't in the table.

HTML markup:

<!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 code:

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
?>

Use either

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

or

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

Try to print out the error if any:

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