简体   繁体   中英

POST form on button click using jquery ajax

i'm trying to load form via ajax and submit form then write response to "#pagediv".

Here is my working code

    $(function() {              
    $.ajax({
        url: "<?php echo $_SERVER['PHP_SELF']; ?>",
        type: "GET",
        data: { <?php echo $ajxparam; ?> },
        dataType: "html",
        cache: false
    }).done(function( msg ) {
        $("#pagediv").html(msg);
        $("#savebtn").click(function(event){ event.preventDefault(); $("#testform").submit(); });       
    }).fail(function() {
        $("#pagediv").html( "Request Failed. Please Try Again Later." );
    });
});

modified code in form submit part(refer below); its not working, did i missed anything?

    $(function() {              
    $.ajax({
        url: "<?php echo $_SERVER['PHP_SELF']; ?>",
        type: "GET",
        data: { <?php echo $ajxparam; ?> },
        dataType: "html",
        cache: false
    }).done(function( msg ) {
        $("#pagediv").html(msg);
        $("#savebtn").click(function(event){
            event.preventDefault();
            $("#testform").submit(function(evt) {
              evt.preventDefault();
              var $form = $( this ),
                  url = $form.attr( 'action' );
              var posting = $.post( url, $(this).serialize() );
              posting.done(function( dte ) {
                $("#successdiv").html(dte);
              });
            });
        });
    }).fail(function() {
        $("#pagediv").html( "Request Failed. Please Try Again Later." );
    });
});

Note:- Form POST URL is different from ajax load main page.

Inside your click event handler you're adding a submit event handler and not actually submitting the form. Since you're uploading the data via ajax on a button click just call the ajax in the button click callback.

    $("#savebtn").click(function(event){
          event.preventDefault();
          var $form = $("#testform"),
              url = $form.attr( 'action' );
          var posting = $.post( url, $form.serialize() );
          posting.done(function( dte ) {
            $("#successdiv").html(dte);
          });
    });

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