[英]jQuery submits the wrong html form
我有一个php脚本,可以从数据库中获取项目并允许用户投票给它们,我给这些获取的项目中的每一项提供一个(html表单)和一个(输入文本字段),并提供一个(提交按钮),以便在单击,然后在同一页面上有一个jQuery脚本,该脚本通过该表格将分数插入数据库而无需刷新页面,除脚本有一个脚本外,其他一切似乎都正常运行。
此脚本仅允许循环中的第一个表单(html表单)提交,而此第一个(html表单)影响不在循环中跟随它的项,如何使每个表单都归因于其项?
除此之外,我还希望脚本为提交分数的用户返回通知,以通知他们数据是成功插入还是失败,以及何时成功,我想让用户提交的分数在提交后出现在他们面前
感谢您的帮助,这是我的代码:
<body>
<div id="items-wrapper">
<?php //function where i fetch items/records from database $items=g et_items_function($page_id); if(!$items){ echo 'There are no items in this page yet!'; }else{ ?>
<div id="item">
<?php //looping the fetched items/records foreach($items as $item){ $_itemid=$ item[ 'item_id']; $_name=$ item[ 'item_name']; $item_file='path/to/items/name-' .$_name. '-id-'.$_itemid. '.jpg'; ?>
<ul id="responds">
<!--i want to append data here-->
</ul>
<img src="<?php echo $item_file; ?>" />
<form action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
<input type="text" name="content_txt" id="contentText" placeholder="Enter score" />
<button id="FormSubmit">Add Score</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</form>
<?php } ?>
</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
//Ajax request to setItemScore.php
$("#FormSubmit").click(function(e) {
e.preventDefault();
if ($("#contentText").val() === '') {
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var myData = 'score_value=' + $("#contentText").val();
jQuery.ajax({
type: "POST",
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
dataType: "text",
data: myData,
success: function(response) {
$("#responds").append(response);
$("#contentText").val('');
$("#FormSubmit").show();
$("#LoadingImage").hide();
},
error: function(xhr, ajaxOptions, thrownError) {
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});
});
</script>
</body>
第1期
出于以下两个原因,在提交表单时,应始终使用.submit()
方法,而不要使用提交按钮onclick()
。 1)使用inputs
您可以按Enter键并绕过整个方法提交表单。 2) .submit()
使用允许您获取该表单子项的表单。
考虑到这一点,我将一个类名添加到您知道通过ajax提交的表单中,例如:
<form class="ajax-form" action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
...
</form>
然后, .onclick()
使用.onclick()
还可以使用:
$('.ajax-form').submit(function(e){
...
});
第2期
在您的AJAX请求中,您使用以下行:
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
这总是将$_itemid
设置$_itemid
上述foreach()
循环的最后一次迭代,而不是表单中的action
。
如果您使用上面在问题#1中提到的方法,那么您可以简单地使用forms action属性:
url: $(this).prop('action')
$(this)
是表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.