2017-10-19 3 views
0

テーブル内の各行について、送信ボタン付きの次のフォームがエコーされています。同じAjaxを使用する複数のサブミット

echo '<form method="POST" name="implement" id="implement" action="submit.php?data='.$data.'" style="display: inline;"> 
<input type="submit" name="submit" value="Implement"> 
</form>'; 

各送信ボタンは、以下のjavascriptを使用できる必要があります。私は各フォームに一意のIDを割り当てる方法を理解できません。

<script> 
$(function(){ 
    $('#implement).on('submit', function(e){ 

     // prevent native form submission here 
     e.preventDefault(); 


     // now do whatever you want here 
     $.ajax({ 
      type: $(this).attr('method'), // <-- get method of form 
      url: $(this).attr('action'), // <-- get action of form 
      data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file 
      beforeSend: function(){ 
       $('#result').html(''); 
      }, 
      success: function(data){ 
       $('#result').html(data); 


     if(data === "0") { 
alert("label1"); 
     } 

    if(data === "1") { 
alert("label2"); 
     } 



      } 
     }); 
    }); 
}); 
</script> 
+0

あなたをIdではなくクラスによって、または 'form'型で行うことができます。 – Rasclatt

答えて

0

述べたように、あなただけのクラスまたはリスナーとしてformタグ自体を使用することができ、私はクラスを使用します:

// Presumably this is in your loop 
// I was start by removing the id since it's not unique 
// I would also put whatever data you are trying to submit in the $_GET into a hidden field 
?> 
<form method="POST" name="implement" class="form-submit" action="submit.php" style="display: inline;"> 
<input type="hidden" name="data" value="<?php echo $data ?>" /> 
<input type="submit" name="submit" value="Implement"> 
</form> 
<?php 

AJAXのJavaScript:

<script> 
$(function(){ 
    // Target the class name, now it will apply to all forms with this class 
    $('.form-submit').on('submit', function(e){ 
     // prevent native form submission here 
     e.preventDefault(); 
     $.ajax({ 
      type: $(this).attr('method'), 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      beforeSend: function(){ 
       $('#result').html(''); 
      }, 
      success: function(data){ 
       $('#result').html(data); 
       if(data === "0") { 
        alert("label1"); 
       } 
       else if(data === "1") { 
        alert("label2"); 
       } 
      } 
     }); 
    }); 
}); 
</script> 
関連する問題