向mysql數據庫PHP和AJAX添加表單數據

[英]Adding form data to mysql database PHP and AJAX


I am wanting to have a form that will let me add names to my database without refreshing the form. I have been working on it but it does not seem to work. I am quite new at this so any help is appreciated.

我希望有一個表單,可以在不刷新表單的情況下將名稱添加到數據庫中。我一直在做這件事,但似乎沒有效果。我對這方面很陌生,所以我很感激你的幫助。

For my index.html I have:

我的指數。html我有:

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#firstname").val();
var username = $("#lastname").val();

var dataString = 'firstname='+ firstname + 'lastname=' + lastname

if(firstname=='' || lastname=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>



<body>

<form method="post" name="form">
<ul><li>
<input id="firstname" name="firstname" type="text" />
</li><li>
<input id="lastname" name="lastname" type="text" />


</li></ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div></form> 

For join.php:

join.php:

<?php
include("db.php");

if($_POST)
{
$firstname=$_POST['firstname'];
$lastname=$_POST['username'];
mysql_query("INSERT INTO persons (firstname,lastname) VALUES('$firstname','$lastname')");
}

?>

and db.php:

和db.php:

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

1 个解决方案

#1


3  

there is mistake in code, you have coded

代碼中有錯誤,你已經編碼了

  var name = $("#firstname").val();
  var username = $("#lastname").val();
  var dataString = 'firstname='+ firstname + 'lastname=' + lastname

you have to used the variables name and username in dataString but you have written the id(s) of fields for first and last name. change either the variable name or variables used in dataString

您必須在dataString中使用變量名和用戶名,但是您已經為名和姓編寫了字段的id。更改dataString中使用的變量名或變量

corrected line is :

糾正是行:

 var dataString = 'firstname='+ name + 'lastname=' + username

And

   $lastname=$_POST['username']; =>  $lastname=$_POST['lastname']; 

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/06/05/725c0f2576d8b6f218878d1bb2188a2f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com