简体   繁体   中英

jQuery hold form submit until “continue” button pressed

I am trying to submit a form, which I have had working, but have now modified it to include a modal jQuery UI box, so that it won't submit until the user presses "continue". I've had various problems with this, including getting the form to hold until that button is pressed, but I think I have found a solution to that, but implementing it, I am getting a SyntaxError which I can't find the source of.

With the help of kevin B managed to find the answer was the form was submitting, but the returned JSON response wasn't quite formatted right. The response was that the form wasn't being submitted, so that problem is still occurring.

So updated the code with the provided feedback, now need to find out why the form isnt submitting. I know its something to do with the 2nd function isnt recognising the submit button has been pressed, so need to know how to submit that form data without the form needing to be submitted again.

Below is the new code:

function submitData() {
$("#submitProvData").submit(function(event) { 
    event.preventDefault();
    var gTotal, sTotal, dfd;
    var dfd = new $.Deferred();
    $('html,body').animate({ scrollTop: 0 }, 'fast');
    $("#submitProvData input").css("border", "1px solid #aaaaaa");
    $("#submitProvData input[readonly='readonly']").css("border", "none");
    sTotal = $('#summaryTotal').val();
    gTotal = $('#gptotal').val();
    if(gTotal !== 'sTotal'){
        $("#newsupinvbox").append('<div id="newsupinvdiagbox" title="Warning - Totals do not match" class="hidden"><p>Press "Continue", to submit the invoice flagged for attention.</p> <br /><p class="italic">or</p><br /> <p>Press "Correct" to correct the discrepancy.</p></div>') //CREATE DIV
        //SET
        $("#newsupinvdiagbox").dialog({
            resizable: false,
            autoOpen:false,
            modal: true,
            draggable: false,
            width:380,
            height:240,
            closeOnEscape: false,
            position: ['center',20],
            buttons: {
                'Continue': function() {
                    $(this).dialog('close');
                    reData();
                }, // end continue button
                'Correct': function() {
                    $(this).dialog('close');
                        return false;
                    } //end cancel button
                }//end buttons
            });//end dialog
            $('#newsupinvdiagbox').dialog('open');
        }
        return false;
    });
}

function reData() {
    console.log('submitted');
    $("#submitProvData").submit(function(resubmit){
        console.log('form submit');
        var formData;
        formData = new FormData($(this)[0]);
        $.ajax({
            type: "POST",
            url: "functions/invoicing_upload_provider.php",
            data: formData,
            async: false,
            success: function(result) {
                $.each($.parseJSON(result), function(item, value){
                    if(item == 'Success'){    
                        $('#newsupinv_window_message_success_mes').html('The provider invoice was uploaded successfully.');
                        $('#newsupinv_window_message_success').fadeIn(300, function (){
                            reset();
                        }).delay(2500).fadeOut(700);
                    } else if(item == 'Error'){      
                        $('#newsupinv_window_message_error_mes').html(value);
                        $('#newsupinv_window_message_error').fadeIn(300).delay(3000).fadeOut(700);
                    } else if(item == 'Warning'){      
                        $('#newsupinv_window_message_warning_mes').html(value);
                        $('#newsupinv_window_message_warning').fadeIn(300, function (){
                            reset();
                        }).delay(2500).fadeOut(700);
                    } 
                });
            },
            error: function() {
                $('#newsupinv_window_message_error_mes').html("An error occured, the form was not submitted");
                $('#newsupinv_window_message_error').fadeIn(300);
                $('#newsupinv_window_message_error').delay(3000).fadeOut(700);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
}

原始控制台错误

With much help from Kevin B, managed to get the form working as I wanted. The form now submits, the answer lay in using .serialise() rather than FormData to get the form to finally submit correctly.

Posted below is the completed code:

function submitData() {
$("#submitProvData").submit(function(event) { 
    event.preventDefault();
    var gTotal, sTotal, dfd;
    var dfd = new $.Deferred();
    $('html,body').animate({ scrollTop: 0 }, 'fast');
    $("#submitProvData input").css("border", "1px solid #aaaaaa");
    $("#submitProvData input[readonly='readonly']").css("border", "none");
    sTotal = $('#summaryTotal').val();
    gTotal = $('#gptotal').val();
    if(gTotal !== 'sTotal'){
        $("#newsupinvbox").append('<div id="newsupinvdiagbox" title="Warning - Totals do not match" class="hidden"><p>Press "Continue", to submit the invoice flagged for attention.</p> <br /><p class="italic">or</p><br /> <p>Press "Correct" to correct the discrepancy.</p></div>') //CREATE DIV
            //SET
            $("#newsupinvdiagbox").dialog({
                resizable: false,
                autoOpen:false,
                modal: true,
                draggable: false,
                width:380,
                height:240,
                closeOnEscape: false,
                position: ['center',20],
                buttons: {
                    'Continue': function() {
                        $(this).dialog('close');
                        reData();
                    }, // end continue button
                    'Correct': function() {
                        $(this).dialog('close');
                        return false;
                    } //end cancel button
                }//end buttons
            });//end dialog
            $('#newsupinvdiagbox').dialog('open');
        } else {
            reData(); //CONTINUE WITH FORM SUBMIT
        }
        return false;
    });
}

function reData() {
    var formData;
    formData = $("#submitProvData").serialize();
    $.ajax({
        type: "POST",
        url: "functions/invoicing_upload_provider.php",
        data: formData,
        async: false,
        success: function(result) {
            $.each($.parseJSON(result), function(item, value){
                if(item == 'Success'){    
                    $('#newsupinv_window_message_success_mes').html('The provider invoice was uploaded successfully.');
                    $('#newsupinv_window_message_success').fadeIn(300, function (){
                        reset();
                    }).delay(2500).fadeOut(700);
                } else if(item == 'Error'){      
                    $('#newsupinv_window_message_error_mes').html(value);
                    $('#newsupinv_window_message_error').fadeIn(300).delay(3000).fadeOut(700);
                } else if(item == 'Warning'){      
                    $('#newsupinv_window_message_warning_mes').html(value);
                    $('#newsupinv_window_message_warning').fadeIn(300, function (){
                        reset();
                    }).delay(2500).fadeOut(700);
                } 
            });
        },
        error: function() {
            $('#newsupinv_window_message_error_mes').html("An error occured, the form was not submitted");
            $('#newsupinv_window_message_error').fadeIn(300);
            $('#newsupinv_window_message_error').delay(3000).fadeOut(700);
        }
    });
}

A complete system to break form and post with jquery/ajax

$(document).ready(function(e) {
$('#form_sendemail').submit(function(e) {
$.ajax({
  url: 'sendmail.php',
  type: 'POST',
  data: $(this).serialize(),
  dataType: 'json',
  beforeSend: function (XMLHttpRequest) {
    //
    $('#form_sendemail .has-error').removeClass('has-error');
    $('#form_sendemail .help-block').html('').hide();
    $('#form_message').removeClass('alert-success').html('');
  },
  success: function( json, textStatus ) {
    if( json.error ) {
      // Error messages
      if( json.error.name ) {
        $('#form_sendemail input[name="name"]').parent().addClass('has-error');
        $('#form_sendemail input[name="name"]').next('.help-block').html( json.error.name ).slideDown();
      }
      if( json.error.email ) {
        $('#form_sendemail input[name="email"]').parent().addClass('has-error');
        $('#form_sendemail input[name="email"]').next('.help-block').html( json.error.email ).slideDown();
      }
      if( json.error.message ) {
        $('#form_sendemail textarea[name="message"]').parent().addClass('has-error');
        $('#form_sendemail textarea[name="message"]').next('.help-block').html( json.error.message ).slideDown();
      }
    }
    //
    if( json.success ) {
      $('#form_message').addClass('alert-success').html( json.success ).slideDown();

      setTimeout(function() {
        $('#form_message').slideUp("fast", function() {
          $(this).removeClass('alert-success').html('');
         });
      },4000);
      $('#form_sendemail')[0].reset();
    }

  },
  complete: function( XMLHttpRequest, textStatus ) {
    //
  }
});

return false;
});
});

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