简体   繁体   中英

I have successfully loaded a form into a <div> element using jQuery $.Ajax. I need to know how to submit that form using jQuery Ajax

I have used .on() of jQuery for event delegation and to set up a 'submit' event handler for the dynamically the loaded form eg

<script>

    $(document).on('submit','#my_form_id',function(e){


                    e.preventDefault();
                    e.stopPropagation();


                    $.ajax({

                           url:$this.href,
                           type:"POST",
                           data: $('#my_form_id').serialize(),
                           dataType: "html"

                     }).done(function(update_result){

                         $('#id_of_div_that_will_hold_the result').html(update_result);  
                     });

                     return false;

      });



  </script>  

But it is not working as the form gets submitted directly not asynchronously.

Also where should the above script be put in the main page or in the page that contains the HTML code for dynamically loaded form? I ask this as it seems the script is not being called

Any general short example will help and be highly appreciated. I cannot provide the code here as it is too long in MVC architecture using codeigniter.

You can do something like this to POST the form:

$("#my_form_id").submit(function (e) {
    e.preventDefault();
    $.post($(this).attr("action"), $(this).serialize(), function (data) {
      // put any code handling return values here
    });
});

The $.submit works the same as $.on('submit') but easier to read and type. The $(this).serialize() function will convert all the form data into a string to be submitted to the server.

You should stop the default event handler (submit) from firing.

$(document).on('submit', '#my_form_id', function(e){ 
    e.preventDefault();
    ajax form submision code goes here....
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM