2017-02-13 7 views
-2

SKU 그룹, Group_ID, 편집 단추 및 삭제 단추의 4 개 열이있는 HTML 표가 있습니다. 지금은 삭제 기능에 대한 작업을하고 있으므로 삭제 버튼을 누를 때마다 확인 상자가 팝업되고 "확인"을 누르면 행이 삭제되고 데이터베이스에서 삭제되는 삭제 쿼리가 전송됩니다.단추의 표 행 삭제 Ajax 사용

나는 삭제 쿼리를 위해 Ajax와 별도의 PHP 스크립트를 사용 하겠지만, 알아낼 수는 없다. 어떤 도움을 주셔서 감사합니다! 삭제 버튼에 대한

HTML :

<td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td> 

자바 스크립트는 ... 나는이 몇 가지 작업을 필요로 알고 있지만 내 질문을 위해 그것을 게시 오전 :

function deleteRow(r) { 

if (confirm('Are you sure you want to delete this entry?')) { 
    var i = r.parentNode.parentNode.rowIndex; 
    document.getElementById("skuTable").deleteRow(i); 
    } 



    request = $.ajax({ 
     type: "POST", 
     url: "delete.php", 
     data: i 
    }); 


     request.done(function (response, textStatus, jqXHR){ 
      if(JSON.parse(response) == true){ 
      console.log("row deleted"); 
      } else { 
      console.log("row failed to delete"); 
      } 
     }); 

     // Callback handler that will be called on failure 
     request.fail(function (jqXHR, textStatus, errorThrown){ 
      // Log the error to the console 
      console.error(
       "The following error occurred: "+ 
       textStatus, errorThrown 
      ); 
     }); 

     // Callback handler that will be called regardless 
     // if the request failed or succeeded 
     request.always(function() { 

     }); 


} 

delete.php :

<?php 

    $SKU_Group = $_POST['SKU Group']; 
    $Group_ID = $_POST['Group_ID']; 

    $host="xxxxxx"; 
    $dbName="xxxxxx"; 
    $dbUser="xxxxxxxxxxxxxx"; 
    $dbPass="xxxxxxxxxxx"; 

    $pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass); 

    $delete = "DELETE FROM SKU_Group_Dim WHERE Group_ID = '$Group_ID'"; 

    $stmt = $pdo->prepare($delete); 
    $result = $stmt->execute(); 
    echo json_encode($result); 
    if(!$result) { 
     echo json_encode(sqlsrv_errors()); 
    } 

?> 
+0

[Little Bobby] (http://bobby-tables.com/)에서 *** [귀하의 스크립트는 SQL 주입 공격의 위험에 있습니다.] (http://stackoverflow.com/questions/60174/how- can-i-prevent-sql-injection-in-php) ***. 심지어 [이스케이프 문자열] (http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) 안전하지 않습니다! –

+0

옳은 길을 걷고있는 것 같습니다. 작동하지 않는 것은 무엇입니까? –

+0

아약스의 데이터 변수에는 보이는 것에서 $ _POST 게터에 해당하는 매개 변수가 없습니다. –

답변

2

자바 스크립트

먼저 jQuery를 사용하고있는 것을 보았습니다. 그래서 그것을 최대한 활용 해 보시지 않겠습니까?

.delete 버튼에 대한 onclick 이벤트 처리기를 만드는 것으로 시작하십시오.

$('.delete').click(function() { 
    // do something when delete button is clicked 
}); 

는 당신은 사용자가 가 성공적으로 데이터베이스에서 삭제 된 확인 후 행을 삭제합니다.

if (confirm('Are you sure you want to delete this entry?')) { 
    // shorter call for doing simple POST request 
    $.post('delete.php', data, function (response) { 
     // do something with response 
    }, 'json'); 
    //^to indicate that the response will be of JSON format 
} 

그러나 data 우리가 삭제되는 기록을 알 수 있도록하는 $.post()로 전달되어야 하는가? 아마도 우리가 지우고 자하는 레코드의 ID 일 것입니다.

HTML

당신은 HTML의 대부분을 게시하지 않은 것처럼, 이제 당신이 아래 테이블 내장 가정하자 : 당신은 쉽게 찾을 수의 ID에 액세스 할 수 있도록

<table class="skuTable"> 
    <tr> 
     <td>123</td><!-- sku group --> 
     <td>456</td><!-- group id --> 
     <td><input type="button" class="edit" name="edit" value="Edit" ... ></td> 
     <td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td> 
    </tr> 
    <!-- more similar records --> 
</table> 

변경을 셀에 클래스를 추가하는 등의 그룹. (우리는 이미 onclick 핸들러를 만든 때문에, 당신은 더 이상 .delete 버튼에 onclick 속성을 사용할 필요가 없습니다.) (다시)

<table class="skuTable"> 
    <tr> 
     <td class="skuGroup">123</td> 
     <td class="groupId">456</td> 
     <td><input type="button" class="edit" name="edit" value="Edit" ... ></td> 
     <td><input type="button" class="delete" value="Delete"></td> 
    </tr> 
    <!-- more similar records --> 
</table> 

자바 스크립트를

당신은 쉽게 통과하여 관련 ID를 찾을 수 있습니다 jQuery 사용하기. 이제 모든 것을 함께 넣어 :

$('.delete').click(function() { 
    var button = $(this), 
     tr = button.closest('tr'); 
    // find the ID stored in the .groupId cell 
    var id = tr.find('td.groupId').text(); 
    console.log('clicked button with id', id); 

    // your PHP script expects GROUP_ID so we need to pass it one 
    var data = { GROUP_ID: id }; 

    // ask confirmation 
    if (confirm('Are you sure you want to delete this entry?')) { 
     console.log('sending request'); 
     // delete record only once user has confirmed 
     $.post('delete.php', data, function (res) { 
      console.log('received response', res); 
      // we want to delete the table row only we received a response back saying that it worked 
      if (res.status) { 
       console.log('deleting TR'); 
       tr.remove(); 
      } 
     }, 'json'); 
    } 
}); 

PHP 사람들이 준비된 문을 사용하는 이유

하나는 공격을 방지하는 것입니다. 당신이 그것을 사용하려고 시도한 것은 좋지만, 당신은 그것을 올바르게 사용하지 않고 있습니다 (Jay의 의견을 읽으십시오). 변수를 SQL의 매개 변수에 바인드하려고합니다.PDOStatement::execute() 함수의 변수 배열을 전달하여이 작업을 수행 할 수 있습니다.

레코드를 삭제할 때 PDOStatement::rowCount()을 사용하여 영향을받는 레코드 수를 확인하여 레코드가 작동하는지 확인합니다.

나는 execute()이 효과가 있는지 여부를 확인할 이유가 없습니다.

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

//$SKU_Group = $_POST['SKU Group']; 

$Group_ID = $_POST['Group_ID']; 

$host="xxxxxx"; 
$dbName="xxxxxx"; 
$dbUser="xxxxxxxxxxxxxx"; 
$dbPass="xxxxxxxxxxx"; 

$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass); 

$stmt = $pdo->prepare("DELETE FROM SKU_Group_Dim WHERE Group_ID = ?"); 
$stmt->execute(array($Group_ID)); 

// send back the number of records it affected 
$status = $stmt->rowCount() > 0; 

// send back a JSON 
echo json_encode(array('status' => $status)); 

// nothing else can be outputted after this 
?> 

물론 이것은 테스트되지 않았으므로 버그가 거의 없을 수 있습니다. 브라우저의 콘솔 로그를 열면 로그를 따라 무슨 일이 일어나고 있는지 확인할 수 있습니다.

+0

답해 주셔서 감사합니다. 스크립트에 코드가 있고 실행시 삭제 버튼을 클릭해도 아무런 변화가 없습니다. 왜 그런가? – Rataiczak24

+0

JS의 처음 2 줄을 편집하여 확인 상자가 표시됩니다. 이제 document.addEventListener ('DOMContentLoaded', function() { \t document.getElementById ("delete"). addEventListener 'click', function() {'그러나''응답 상태가 false가되었다 ''는 메시지가 나타납니다. – Rataiczak24

+0

코드를 올바르게 따라하십시오. 귀하의 HTML 버튼에는 각각'class' 속성 **이 있어야합니다 ** id 속성이 아닙니다 이 버튼은 같은 onclick 이벤트 핸들러를 공유하기 때문에이 클래스를 공유합니다 .ID는 여러 요소가 아닌 요소 하나에 대해서만 의미가 있습니다. 콘솔 로그를 따라 각 중단 점에서 올바른 값을 얻고 있는지 확인하십시오. 거짓, 당신이 AJAX에 전달하는 것을보십시오. – Mikey