Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting form with Ajax

I have a div set up with a form inside and set to post using ajax and returning the results in the div like so

$(document).ready(function(){
    $("#guestList").validate({
        debug: false,
        submitHandler: function(form) {
            // do other stuff for a valid form
            //$('form').attr('id', 'guestList1')
            $.post('brides_Includes/guestlistDisplay1.php', $("#guestList").serialize(), function(data) {
                $('#results').html(data)
                $("form#guestList")[0].reset();
            });
        }
    });
});

When the results come back it shows the correct changes and replaces the form. However when I post the form again. The relevent changes take place as they should but it then also refreshes the page and shows the posted info in the address bar

How can I post the form and replace it allowing it to post and call the script again without this happening?

like image 707
Patdundee Avatar asked Oct 21 '22 18:10

Patdundee


1 Answers

the problem with returning forms using ajax is that any JavaScrip code already on the page will not see/take advantage of the new form. The best way to get around this is to pass the JavaScrip and the HTML back using ajax.

Basically you pass the below code back each time you pass a new form back. You'll need to update the IDs and links (brides_Includes/guestlistDisplay1.php). You will need to replace your code on the main page with this code as well because this is needed to execute any JavaScrip passed back.

<script type="text/javascript">
$(document).ready(function(){
  $("#guestList").validate({
    debug: false,
    submitHandler: function(form) {
      // do other stuff for a valid form
      //$('form').attr('id', 'guestList1')
      $.post('brides_Includes/guestlistDisplay1.php', $("#guestList").serialize(), function(data) {
        $('#results').html(data);

        //This executes the JavaScript passed back by the ajax.
        $("#results").find("script").each(function(i) {
          eval($(this).text());
        });

        $("form#guestList")[0].reset();
      });
    }
  });
});
</script>
like image 90
Graham Walters Avatar answered Nov 04 '22 01:11

Graham Walters