Submitting a jQuery ajax form with two submit buttons

前端 未结 8 953
花落未央
花落未央 2020-12-05 07:31

I have a form that looks like this:

相关标签:
8条回答
  • 2020-12-05 08:00

    Based on Emmett's answer, my ideal fix for this was just to kill the form's submit with Javascript itself, like this:

    $(".vote_form").submit(function() { return false; });
    

    And that totally worked.

    For completeness, some of my JS code in the original post need a little love. For example, the way I was adding to the serialize function didn't seem to work. This did:

        $form.serialize() + "&submit="+ $(this).attr("value")
    

    Here's my entire jQuery code:

    $(".vote_form").submit(function() { return false; });
    $(".vote_up, .vote_down").click(function(event) {
        $form = $(this).parent("form");
        $.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
            // do something with response (data)
        });
    });
    
    0 讨论(0)
  • 2020-12-05 08:03

    Another solution is to use a hidden field, and have the onclick event update its value. This gives you access from javascript, as well as on the server where the hidden field will get posted.

    0 讨论(0)
  • 2020-12-05 08:12
    var form = jQuery('#myform');
    
    var data = form.serialize();
    
    // add the button to the form data
    var btn = jQuery('button[name=mybuttonname]').attr('value');
    data += '&yourpostname=' + btn;
    
    var ajax = jQuery.ajax({
        url: url,
        type: 'POST',
        data: data,
        statusCode: {
            404: function () {
                alert("page not found");
            }
        }
    });
    ... rest of your code ...
    
    0 讨论(0)
  • 2020-12-05 08:13

    You can also try out the jquery From Plugin which as all sorts of nice tools for submitting forms via ajax.

    http://malsup.com/jquery/form/

    0 讨论(0)
  • 2020-12-05 08:15

    Without resorting to the Form plugin (which you should use) you should be handling the submit event instead. The code would stay pretty close to the original:

    $("form").submit(function()) {
      $.post($(this).attr("action"), $(this).serialize(), function(data) {
        // work with the response
      });
      return false;
    });
    
    0 讨论(0)
  • 2020-12-05 08:20

    You can trigger the form submit on the click of the images. This will work with the preventDefault().

    var vote;
    $(".vote_up, .vote_down").click(function(event) {
        vote = $(this).attr("class");
        $(".vote_form").trigger("submit");
    });
    
    $(".vote_form").submit(function(event) { 
        $form = $(this);
        $.post($form.attr("action"), $form.serialize() + "&submit="+ vote, function(data) {
            // do something with response (data)
        });     
        event.preventDefault();
    });
    
    0 讨论(0)
提交回复
热议问题