I have a small form and a link which submits this form using jQuery and POST. I wish to display the HTML output from the process page on the form page without refreshing using AJAX. However, my code doesn't seem to work when I click my submit link. Please can someone point out what I may be doing wrong here? Many thanks.
Regards
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#myform').submit(function() {
$.post('demoprocess.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
});
});
</script>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/><br>>
<label for="email" id="email_label">Email</label>
<input type="text" name="email" id="email" size="30" value=""/><br>
<a href="#" title="" class="pay-button" style="margin-top:5px;" onclick="document.myform.submit()">SUBMIT</a>
</form>
<!-- We will output the results from demoprocess.php here -->
<div id="results"><div>
The problem is that your form doesn't contain any element that fires the javascript
submit
eventFrom jquery Documentation
.submit()
:So, in order to make
.submit()
works you need to add one of:<input type="submit">
,<input type="image">
,or
<button type="submit">
.to your form, so you will need to add something like:
The trouble is that you are binding a jQuery
submit
handler but firing the native DOMsubmit
method. This does not fire asubmit
event, so the jQuery handler is never notified.You should trigger the event with jQuery instead. It's probably also easiest to do this in jQuery, rather than using an
onclick
attribute:Note that this isn't very good design, IMO, because users without Javascript will not be able to submit your form.
Try preventing the default behaviour on form submission:
You can do:
or