having a bit of a mystery issue here...
I've built a button on a page which submits a form. The form is embedded with a DIV, which updates to show the amended data.
(it's within a smarty template)
form:
<form id='itempost_{$item.itemid}_{$item2.itemid}' method='post' class='itempost'>
<input type='hidden' name='item' value='{$item.itemid}'>
<input class='btn_text' type="submit" value="Send Item">
</form>
JS
$('.itempost').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url : 'item.php',
data: $(this).serialize(),
success : function (response) {
$("#update").eq(0).load("update.php?&t={$parentid}");
},
error: function (jXHR, textStatus, errorThrown) {
alert('not ok');
alert(errorThrown);
}
});
return false;
});
update.php
all update.php contains is the necessary minimums to rebuild the page, then it rebuilds the section of template that sits within div #update.
$smarty->display('items.tpl');
The first time the button is clicked, it works brilliantly, and the HTML content changes without any noticeable impact on the page.
The second click, however, doesn't seem to go anywhere near the JS, and simply reloads the page. The following click then works as it should, leading me to believe the the actions are:
1st Click: Submits form with AJAX as designed 2nd Click: Refreshes the page, does nothing more 3rd Click: Submits form with AJAX as designed 4th Click: Refreshes the page, does nothing more
etc.
Any ideas on what I'm doing wrong here? I've made sure that the JS is present on all occasions, checked over everything, and googled my digits off - I just can't see where I've made an error?
$("#update").eq(0)
?$('#update')
should only be one element. – putvande<form>
then the event listener isn't assigned to the new one. Read up about event delegation in jQuery, something along$(document).on('submit','.itempost',function(){...})'
should do the job. – yuriy636