I have the following html code: (that gets loaded via ajax into a div)
(Cut out the irrelevant parts)
<form id='addContactForm' method='post' action='/contact/create/'>
<div>
<input type="image" name="submit" id="addContactSubmit" src="/images/add-small.png" style="width: auto; vertical-align: bottom;">
</div>
</form>
<script>
$('#addContactSubmit').click(function () {
alert('got here');
$.ajax({
type: 'POST',
url: '/contact/create/',
data: $("#addContactForm").serialize(),
success: function (data, status, xhttp) {
if (data) {
alert('Got Data');
} else {
alert('No Data');
}
},
dataType: html
});
return false;
});
</script>
So now when I click on the <image>, it actually posts the form and refreshes the page. I read another post that stated that the problem was that jquery wasn’t loaded, and once loaded that fixed the problem. However, in this case, I am getting the alert, which tells me that jquery is loading (as the click event is triggering fine), however it seems the $.ajax portion is not being executed (or there is a problem with it). If I remove the $.ajax portion, I get the alert, and the page does not submit and reload.
Originally I stated that this form html gets loaded via an ajax call on the main page, and I am wondering if that has something to do with the failing ajax post. Note I also never get the alert (‘Got Data’) or (‘No Data’), only the alert ‘got here’
any insite would be great. Thanks
Another note, I am getting no errors in firebug.
It’s a submit input which will automatically post back the form as well as run your ajax script.
Try this…
All I’ve done is pass the click event to your jQuery function then calling e.preventDefault() stops the execution of the default DOM click event which in this case for a submit button is a post back.
Hope this makes sense, you had it pretty much right!