2012-07-20 99 views
-3

到mysql我想用克隆的div包含表單使用此代碼插入記錄使用jquery

$(document).ready(function() { 

    $("#button").click(function() { 
     $("<div class='newclone' id='xxx'><article><form method='post' id='aj'><input type='checkbox'><label>Firstname</label><input type='text' value='' name='firstname'><label>Secondname</label><input type='text' value='' name='secondname'><label>City</label><input type='text' value='' name='city'><input type='hidden' value='4'></article><input type='submit' value='insert' class='one'><button class='two'>Delete</button><button class='three'>Cancel</button></form></div>").appendTo('.clone-container'); 
    }); 

    $('.one').click(function() { 
     $.ajax({ 
      type: "POST", 
      url: "insert.php", 
      data: $("#aj").serialize(), 
      success: function() { 
       alert('Inserted!'); 
      } 
     }); 
    }); 
}); 

這是php文件

$con = mysql_connect("localhost","root",""); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 
mysql_select_db("clone", $con); 

$firstname=$_POST['firstname']; 
$secondname=$_POST['secondname']; 
$city=$_POST['city']; 
mysql_query("INSERT INTO clone(firstname,secondname,city) VALUES ('$firstname','$secondname','$city')"); 

插入一條記錄到數據庫編輯

問題是,似乎沒有發佈

+0

什麼是錯誤? – 2012-07-20 14:46:58

+2

http://bobby-tables.com/這是主要問題;) – haynar 2012-07-20 14:47:14

+3

StackOverflow不是「這是我的代碼,修復它」。你的代碼在做什麼?你得到什麼錯誤?你有沒有嘗試過自己調試? – 2012-07-20 14:48:09

回答

3

分別測試每個部分。 Ajax請求是否發送正確的數據? PHP腳本是否獲得了數據? (嘗試echo <pre>;print_r($_POST);exit;。)您的INSERT查詢是否正確配製?它成功了嗎?

你還不知道你的問題到底是什麼。首先找出問題所在。那麼可能很容易找出如何解決它。

+1

另外,作爲一個單獨的問題,您應該瞭解數據庫輸入衛生。這一點很重要。 – 2012-07-20 14:52:03

+0

Zsanks賈森zes kind words。我有$('。'')。live(「click」,function()註釋掉,所以我恐慌了一下,但現在正在工作。 – Gandalf 2012-07-20 15:12:19

1

只有在點擊了$("#button")之後,纔會將$('.one')添加到DOM。所以,當$('.one').click(運行時,$('.one')尚不存在,所以事件沒有綁定。

您需要使用委託(或「實時」)事件。

$(document).on('click', '.one', function(){ 
    // Click handler here 
});