没有值从ajax发送到我的PHP脚本

时间:2013-05-31 15:44:24

标签: php javascript html mysql ajax

好吧,所以我试图创建一个[相对]简单的联系表单,使用ajax和php在提交表单后将数据写入数据库。我的javascript或我的php没有任何错误,但问题似乎在于php没有收到ajax正在发送的数据。 的 HTML

<form action="" method="POST" id="contact">
<table>
<tbody>
<tr>
<td><h2>First Name: </h2></td>
<td><h2>Last Name: </td>
<td><h2>Email Address: </td>
</tr>
<tr>
<td><input type="text" name="first_name" placeholder="Johnny"></td>
<td><input type="text" name="last_name" placeholder="Appleseed"></td>
<td><input type="text" name="email" placeholder="johnny@email.com"></td>
</tr>
<tr>
<td><h2>Street Address:</h2></td>
<td><h2>What's Dirty?</h2></td>
</tr>
<tr>
<td><input type="text" name="address"></td>
<td>
<select name="job" form="contact">
<option value="house">House</option>
<option value="roof">Roof</option>
<option value="garage-shed">Garage/shed</option>
<option value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td><h2>Message: </h2></td>
</tr>
</tbody>
</table>
<textarea name="message" cols="80" rows="5"></textarea>
<input type="submit" id="submit" name="send" value="Send!" class="send-button">
</form> 

的Javascript

<script type="text/javascript">
$("#submit").click(function() {
var data_string = $("#contact").serialize();
$.ajax({
type: "POST",
url: "database.php",
data: data_string,
success: function(){
alert(data_string);
}
});
});
</script>

PHP / MySQL的

<?php 
$hostname = "foobase.db.9999.foobase.com";
$username = "foobase";
$dbname = "foobase";
$password = "password";
$con =mysqli_connect($hostname, $username, $password);        
//Connecting to  database
mysqli_connect($hostname, $username, $password) OR DIE ("Unable to 
connect to database! Please try again later.");
mysqli_select_db($con, $dbname);

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo "success!";
}

//adding values into the database.
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$wholename = $fname . " " . $lname;
$email = $_POST['email'];
$address = $_POST['address'];
$job = $_POST['job'];
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO client_base (Name, Email, Address, Job)VALUES                       ('$wholename', '$email', '$address', '$job')");

1 个答案:

答案 0 :(得分:3)

在您的javascript中,更改以下行:

$("#submit").click(function() {

这个:

$("#submit").click(function(e) {
   e.preventDefault();

要防止您的外部<form>被提交,就像您使用ajax一样。