2013-02-13 58 views
-3

提交複選框,所以我有這種形式的表在一個PHP頁面:使用jQuery和Ajax

$page .='<form method="POST" action="delete.php" ID="orgForm">'; 
$page .= "<table> \n"; 
$page .= "<tr>\n"; 
//Decides what to display based on logged in. Only if logged in can you see all the contact's info 
$page .= "<th>ID</th> \n <th>First Name</th> \n <th>Last Name</th> \n <th>Phone Number</th> \n <th>Email</th> \n"; 
//Loops through each contact, displaying information in a table according to login status 
$sql2="SELECT cID, firstName, lastName, phoneNum, email FROM Contact WHERE oID=".$_GET['orgID']; 
$result2=mysql_query($sql2, $connection) or die($sql1); 
while($row2 = mysql_fetch_object($result2)) 
{ 
    $page .= "<tr>\n"; 
    $page .= "<td>".$row2->cID."</td>\n"; 
    $page .= "<td>".$row2->firstName."</td>\n"; 
    $page .= "<td>".$row2->lastName."</td>\n"; 
    $page .= "<td>".$row2->phoneNum."</td>\n"; 
    $page .= "<td>".$row2->email."</td>\n"; 
    $page .= '<td><input type="checkbox" name="checkedItem[]" value="'.$row2->cID.'"></input></td>'."\n"; 
    $page .="</tr>"; 
} 
$page .= '<input name="deleteContacts" type="submit" value="Delete Selected Contacts" />'."\n"; 
$page .= "</form>\n"; 

$page .='<script src="assets/js/orgDetails.js" type="text/javascript"></script>'."\n"; 

我需要以某種方式寫內部orgDetails.js的jQuery腳本,它能夠刪除選中時行我按下刪除按鈕。更改必須在屏幕上顯示而不刷新,而且我還需要能夠從sql db中刪除實際的行。有人能幫我一下嗎?謝謝。

回答

1

在操作URL delete.php,提交此信息後:

if ($_POST != array()) { 
    foreach ($_POST['checkedItem'] as $id) { 
     mysql_query('delete from Contact where cID='.$id); 
    } 

    echo 'Records deleted.'; 
} 

如果你不想刷新頁面時,刪除記錄:

添加到HTML:

<button class="delete_button">Delete selected records</button> 

加入您的js文件:

$('.delete_button').click(function() { 
    $form = $('#orgForm'); 

    delete_ids = []; 

    $form.find('input[name=checkedItem]').each(function() { 
     $checkbox = $(this); 

     if ($checkbox.is(':checked')) { 
      delete_ids.push($checkbox.val()); 
     } 
    ); 

    $.ajax({ 
     url: 'delete.php', 
     type: 'post', 
     data: {delete_ids: delete_ids}, 
     success: function (result_html) { alert(result_html); }, 
    }); 
}); 

而在delete.php中:

if ($_POST != array()) { 
    foreach ($_POST['delete_ids'] as $id) { 
     mysql_query('delete from Contact where cID='.$id); 
    } 

    echo 'Records deleted.'; 
}