Im loading a contact page using .load()
which contains a script that looks like this:
<script type="text/javascript">
$('#submit').click(function(e){
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.post("<?php echo bloginfo( 'template_directory' ) . '/inc/mailit.php';?>",
{
name: name,
email: email,
message: message
},
function(data) {
var n = data.indexOf('<span class="success_message">');
if (n !== 0) {
$('#message_box_1').empty().append(data);
} else {
$('#contact_form').empty().append(data);
}
}
);
});
</script>
The script works fine when I load the contact page directly (i.e. go to http://example.com/contact-us
) but it doesn't when I load the form and script into the dom using .load()
. When I click #submit
, the form submits without running the script. Any ideas what is going on?
Oh and the load script looks like this:
<script>
$('#top_links a').click(function (e) {
e.preventDefault();
var link = $(this).attr('href');
$('#content').empty();
$('#content').load(link + ' #content > *');
});
</script>
UPDATE:
Thanks to @pointy for pointing out the problems with .load()
. So now I have modified my code to use $.get
:
<script>
$('#top_links a').click(function (e) {
e.preventDefault();
var link = $(this).attr('href');
$('#content').empty();
$.get(link, { },
function(data) {
$('#content').replaceWith($(data).find("#content"));
}
)
});
</script>
The problem is the same, the AJAX Script above still doesn't prevent the form from submitting or send a post request when the user clicks the submit button. I have placed both scripts outside of the content that is being loaded with $.get