简体   繁体   中英

How to pass form element values to the ajax success function?

I'm submitting a number of dynamic forms via ajax using this code:

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

    $.ajax({
        type: 'post',
        url: 'data/process.php',
        data: $(this).serialize(), // <----"this" is current form context
        success: function () {
            gaddress();
        },
        error: function (xhr) { //<----error function

            gerroraddress(xhr);

        }
    });
    e.preventDefault();
});

The code works well but the issue is that I want to be able to provide dynamic response like below:

function gaddress(form) {
    if (form = "addressform") {
        var msg = "Address form updated successfully.";
        jQuery.jGrowl(msg, {
            life: 10000,
            position: 'center'
        });
        vaddress();
    }
}

That way, I will provide appropriate response and redirect after successful form submit based on the form submitted.

How do I get the form name being submitted or the name of one of the form elements so I can pass it as a parameter to my success function: gaddress() ?

Also, I need to show a loading bar when form is processing and exit the loading bar after successful completion.

You can do:

$(document).on('submit', 'form', function (e) {
var form = $(this).attr("id"); //Or any attribute here
$.ajax({
  type: 'post',
  url: 'data/process.php',
  data: $(this).serialize(), // <----"this" is current form context
  success: function () {
     gaddress(form);
  },
  error: function (xhr) { //<----error function

      gerroraddress(xhr);

  }
});

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