简体   繁体   English

AJAX表单刷新页面

[英]AJAX form refreshes page

Have been searching around for a while and can't find a proper answer to this problem. 已经搜索了一段时间,找不到适合该问题的正确答案。 I have a "finance" tracker that has several hidden divs which using jQuery appear when the button to show that div is clicked. 我有一个“财务”跟踪器,该跟踪器具有几个隐藏的div,当单击该按钮以显示div时,将使用jQuery出现。 I have a Asset Tracker which queries a database and upon being checked updates the database with new values in adjacent input rows where the checkbox is located. 我有一个资产跟踪器,该查询器查询数据库,并在选中该复选框时,使用相邻输入行中的新值更新数据库。 I am trying to get the checkbox to submit the data without causing the page to reload and the div to "toggle" off again. 我正在尝试使复选框提交数据,而不会导致页面重新加载,并且div再次“切换”。

On the form section I attempted to remove the method='post' but instead when checking the box it reloaded the page and added all the post variables to the URL string. 在表单部分,我尝试删除method='post'但是当选中此框时,它重新加载了页面并将所有post变量添加到URL字符串中。 I removed the action='FBook.php' in an attempt to prevent the reloading, but that did not resolve the problem. 为了防止重新加载,我删除了action='FBook.php' ,但这并不能解决问题。

Here is the related code from the PHP file: 这是PHP文件中的相关代码:

if(isset($_POST['AssetSetUpdate'])) { $AssetLastUpdate = $dtNowDate->format('Y-m-d');
foreach($_POST['AssetID'] as $key => $id) { if(isset($_POST['AssetSetUpdate'][$key])) {
$stmt_ATrackUp -> bindParam(':UpDate', $AssetLastUpdate, PDO::PARAM_STR, 10);
$stmt_ATrackUp -> bindParam(':UpNotes', $_POST['AssetNotes'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpThis', $_POST['AssetDescription'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpVal', $_POST['AssetValue'][$key], PDO::PARAM_INT, 3);
$stmt_ATrackUp -> execute(); } else continue; }
echo "<div class='Notice'>" . $PageTitle . " / Assets updated!</div>"; }

(other code) (其他代码)

$(document).ready(function() {

$("#AssetUpdateForm").submit(function(e) {
e.preventDefault();
$.ajax({
    type: 'POST',
     url: 'FBook.php',
    data: $(this).serialize(),
     success: function() { alert('form submitted'); },
    });
return false;
});


$('#ShFBAsset').click(function() { $('#FBAsset').toggle('slow'); });

(other code) (其他代码)

});

(other code) (其他代码)

$AssetCounter = 1;

$stmt_ATrack -> execute(); while ($row_ATrack = $stmt_ATrack -> fetch(PDO::FETCH_ASSOC))

{   

$ChAge = $row_ATrack['Checked']; $cChAge = ''; switch(true)
{
case (strtotime($ChAge) >= strtotime('-7 days')): $cChAge = 'FBCAN'; break;
case (strtotime($ChAge) >= strtotime('-30 days')): $cChAge = 'FBCA1'; break;
case (strtotime($ChAge) >= strtotime('-90 days')): $cChAge = 'FBCA3'; break;
default: $cChAge = 'FBCA6'; break;
}

if(isset($row_ATrack['Serial'])) { $IfDSerial = "<strong>Serial: </strong>" . $row_ATrack['Serial'] . "<br/>"; } else { $IfDSerial = ''; }
if(isset($row_ATrack['UPC'])) { $IfDUPC = "<strong>UPC: </strong>" . $row_ATrack['UPC'] . "<br/>"; } else { $IfDUPC = ''; }
if(isset($row_ATrack['Related'])) { $IfDRelated = "<strong>Related: </strong>" . $row_ATrack['Related'] . "<br/>"; } else { $IfDRelated = ''; }
if(isset($row_ATrack['Location'])) { $IfDLocation = "<strong>Location: </strong>" . $row_ATrack['Location'] . "<br/>"; } else { $IfDLocation = ''; }
if(isset($row_ATrack['TagPhoto'])) { $IfDTagPhoto = "<strong>Tag photo: </strong><a href='Images/INV/" . $row_ATrack['TagPhoto'] . ".JPG'>" . $row_ATrack['TagPhoto'] . "</a><br/>"; } else { $IfDTagPhoto = ''; }

$IfDetails = "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'>" . ($IfDSerial) . ($IfDUPC) . ($IfDRelated) . ($IfDLocation) . ($IfDTagPhoto) . "</div></div>";
if($IfDetails == "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'></div></div>") { $IfDetails = ''; }

echo "<form id='AssetUpdateForm[" . $AssetCounter . "]' method='post'>";
echo "<tr><input type='hidden' name='AssetID[" . $AssetCounter . "]' value='" . $AssetCounter . "' />";
echo "<td><input type='hidden' name='AssetDescription[" . $AssetCounter . "]' value='" . $row_ATrack['Description'] . "' /><a href='https://www.google.com/#q=eBay+" . $row_ATrack['Description'] . "' target='_new_AssetSearch'>" . $row_ATrack['Description'] . "</a></td>";
echo "<td>" . $row_ATrack['Type'] . " - " . $row_ATrack['Category'] . "</td>";
echo "<td><input type='checkbox' name='AssetSetUpdate[" . $AssetCounter . "]' value='Now' onchange='this.form.submit();' /></td>";
echo "<td><input type='number' name='AssetValue[" . $AssetCounter . "]' value = '" . $row_ATrack['Value'] . "' style='width: 75px;' /></td>";
echo "<td class='" . $cChAge . "'>" . $ChAge . "</td>";
echo "<td><input type='text' name='AssetNotes[" . $AssetCounter . "]' value = '" . $row_ATrack['Notes'] . "' style='width: 140px;' /></td>";
echo "<td>" . $IfDetails . "</td>";
echo "</tr>";
echo "</form>";

$AssetCounter++;

}

Your JavaScript: 您的JavaScript:

$("#AssetUpdateForm")

… is working on a form with id="AssetUpdateForm" . …正在使用id="AssetUpdateForm"的表单。

Your PHP says: 您的PHP说:

id='AssetUpdateForm[" . $AssetCounter . "]'

which in HTML terms becomes: 用HTML术语表示为:

id='AssetUpdateForm[something]'

Even if the variable is empty, you still have the square brackets, so the ID is not going to match and the JavaScript event handler will never be bound to that element. 即使变量为空,您仍然可以使用方括号,因此ID将不匹配,并且JavaScript事件处理程序将永远不会绑定到该元素。

You need to either use the real ID or, since it appears that it can change, add a class to the form and use a .class-selector in the JavaScript. 您需要使用真实ID,或者因为它似乎可以更改,所以需要在表单中添加一个class并在JavaScript中使用.class-selector


NB: Your HTML is invalid. 注意:您的HTML无效。 The particular problem you have has the potential to cause the same symptoms are you describe so just fixing the problem above might not be enough. 您所描述的特定问题有可能导致相同的症状,因此解决上述问题可能还不够。 Use a validator and write valid HTML too. 使用验证器并编写有效的HTML。

Had nothing to do with the HTML or PHP. 与HTML或PHP无关。 Turns out that jQuery AJAX was conflicting with the onclick='this.form.submit();' 事实证明jQuery AJAX与onclick='this.form.submit();'冲突onclick='this.form.submit();' property. 属性。 I removed that and changed the ajax request to the following - and while it still has bugs as it won't work on the 2nd ajax request, it validates everything else is fine. 我删除了它,并将ajax请求更改为以下内容-尽管它仍然存在错误,因为它无法在第二个ajax请求上正常工作,但它可以验证其他一切都很好。

$(".Check2Update").on('change', function(e) {
e.preventDefault();
$.ajax({
    type: 'post',
    url: 'FBook.php',
    data: $(this.form).serialize(),
    success: function(html) { 
        console.log('Successfully submitted AJAX!');
        $("#TableAssets").replaceWith($('#TableAssets', $(html)));
    }
    });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM