0

I am trying to run two scripts: one for loading page content using ajax and the other uses ajax to submit a contact form.

Load page content:

<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>

Submit Form:

<script type="text/javascript">

$('#submit').click(function(event){

    event.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>

Both Scripts are in the footer and are not included in the dynamically loaded content. When I access the contact page directly without using ajax to load it's content, the form code works perfectly. But when I load the form using ajax, the submit script stops working.

This is actually a follow up question to one I posted earlier. After some thought, Im not 100% sure that the answer I received earlier was accurate. The answer relied on the assumption that the form submit code was part of the loaded content but thats not true since I put all the code in the footer which is unaffected by the content changes. Since I can't uncheck the answer, I needed to repost.

Community
  • 1
  • 1
Thomas
  • 5,030
  • 20
  • 67
  • 100
  • 2
    You're obviously changing something that's used by the second script, did you try : `$(document).on('click', '#submit', function(event){ ...` – adeneo Jul 04 '12 at 03:36

2 Answers2

1

You need to run the Submit form script after the form is loaded.

Try wrapping your submit form script in a function, like applySubmitFormEvents() {...} or something similar.

Then in your callback function you need to call applySubmitFormEvents().

Luke Mills
  • 1,616
  • 1
  • 11
  • 18
0

If submit button is in dynamically loaded content, you have to use $.live() function.

$("#submit").live("click", function(e){})
dirigeant
  • 374
  • 1
  • 10