我正在尝试将 ajax 表单提交用于由 php foreach 循环生成的表单列表。我的问题是我显然需要将每个生成的表单标记为唯一并且似乎无法弄清楚。我想使用 HTML data- 属性,但似乎无法使其工作。
这是代码
<?php
if (isset($_SESSION['team_mem_id'])) {
$query_team_matches = $conn->prepare($sql_team_matches);
$query_team_matches->bindParam(':tid', $tid, PDO::PARAM_INT);
$query_team_matches->execute();
$matches = $query_team_matches->fetchAll(PDO::FETCH_ASSOC);
if (!empty($matches)) {
foreach($matches as $Matches) {
$tmid = $Matches['tmid'];
$opponent = $Matches['opponent'];
$location = $Matches['location'];
$tm_datetime = $Matches['tm_datetime'];
$match_date = date("F j",strtotime($tm_datetime));
$match_time = date("g:i A",strtotime($tm_datetime));
$match_when = $match_date. " @ ".$match_time;
?>
<div class='match_container'>
<div class='match_basic_info'>
<h3><?php echo $match_when.' - <span style="font-size: 16px">'.$location.' vs '.$opponent; ?></span></h3>
<a class='match_details_link' href='http://localhost:1234/tennisexcel/teams/match.php?r=team&tid=<?php echo $tid; ?>&tmid=<?php echo $tmid; ?>'>More info...</a>
</div>
<div id='match_avail_container' class='match_avail_container'>
<h3>My availability:</h3>
<form id='avail_submit_form' data-tmid='<?php echo $tmid; ?>' class="" action='http://localhost:1234/tennisexcel/test_ajax.php' method='POST'>
<input type='hidden' name='uid' value='<?php echo $_SESSION['uid']; ?>'/>
<input type='hidden' name='tid' value='<?php echo $_SESSION['tid']; ?>'/>
<input type='hidden' name='tmid' value='<?php echo $tmid; ?>'/>
<button class='match_avail_yes' type='submit' name='availability' value='1'>✔</button>
<button class='match_avail_no' type='submit' name='availability' value='2'>✖</button>
</form>
<div id="signup" data-tmid='<?php echo $tmid; ?>' class='match_avail_success success_display'>
<p>success!</p>
</div>
</div>
</div>
<?php
}
}
}
?>
我在表单和需要标记为唯一的 div 中添加了一个 data-tmid='$tmid' 。jquery如下:
$(document).ready(function() {
$('#avail_submit_form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var fromData = $(this).serialize();
$.post(url, fromData, function(response) {
$('#avail_submit_form').hide();
$('#signup').removeclass('success_display');
}); //end post
}); //end submit
}); //end ready
我尝试将 [data-tmid='+$(this).attr('data-tmid')+'] 添加到每个 id 但不确定如何使其正常工作,或者它是否是正确的方法.
感谢任何可以引导我朝着正确方向前进的人!