简体   繁体   中英

Ajax call just before form submitting does not work

I've got a Spring MVC - JSP web application. Before submitting a specific form I need to fill a text value input with JS/jQuery so the form POSTed contains that info. This text value is the result of an ajax call that should be done when the submit button is clicked but before the form data is send to the controller. The relevant pieces of code in my JSP are the following:

    <script>
                //Gets from model a new valid file code number
                function getFileCodeNumber(res){
                    $.ajax({
                        type: "post",
                        url: "getFileCodeNumber",
                        cache: false,
                        data: { department: $("#department").val(), docType: $("#docType").val() },
                        success: res,
                        error: function(){  alert('Error while request..');}
                    });
                }
            </script>

    <script>
                $(function() {
                    //Other JS code
                    $("#submitForm").click((function(event) {
                        if($("#chkLanguage").prop('checked')){
                                  //some stuff
                        }else{
                            getFileCodeNumber(function(data){
                                  //do some stuff with 'data'
                            });
                        }
                    }));
                });
            </script>

     <form:form id="form" class="form-horizontal" method="post" action="AddDoc" commandName="document" enctype="multipart/form-data">
    <div class="row" style="text-align:center;">
                    <input id="submitForm" type="submit" class="btn btn-primary btn-lg" name="commit" value="Finish">
                </div>
                </br>
            </form:form>

Just to let you know, the ajax call works perfectly when called from another trigger action in the same JSP, but when called from the "click" function it retrieves an alert error but is shown on screen for less than 1 second and therefore I cannot tell you what does it say. By the way, Firebug throws "NS_ERROR_NOT_AVAILABLE: prompt aborted by user". Note that I tried to replace "click" trigger for "submit" that happens exactly the same. My guess would be that the form is being submitted before the ajax call is completely done, but I expected "submit" and "click" functions to do the its job before POSTing the data.

Does anybody have a clue?

EDIT : I found out that the alert that I wasn't able to see is printing the error code of the ajax call. However, I've checked the controller's function that gives response to this call and I've seen it gets completed succesfully and retrieves the expected value. What's more, when I call this function from another trigger in the same JSP it works perfectly. Just to let you see the simple code in the controller:

@RequestMapping(value = "getFileCodeNumber", method = RequestMethod.POST, headers = "Accept=*/*")
    public @ResponseBody
    String getFileCodeNumber(@RequestParam(value = "department", required = true) String department,
            @RequestParam(value = "docType", required = true) String docType) {
        int n = cdocs.getNewCode(department, docType);
        if (n == 0) {
            return "EEEE";
        } else {
            char[] zeros = new char[4];
            Arrays.fill(zeros, '0');
            DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
            System.out.println(df.format(n));
            return df.format(n);
        }//END_IF
    }//END_METHOD

Any ideas?

Try that:

function getFileCodeNumber(res) {
    return $.ajax({
        type: "post",
        url: "getFileCodeNumber",
        cache: false,
        data: {
            department: $("#department").val(),
            docType: $("#docType").val()
        },
        success: res,
        error: function () {
            alert('Error while request..');
        }
    });
}

$("#submitForm").click(function (event) {
    event.preventDefault();
    if ($("#chkLanguage").prop('checked')) {
        //some stuff
    } else {
        getFileCodeNumber(function (data) {
            //do some stuff with 'data'
        }).done(function () {
            $('#form').get(0).submit();
        });
    }
});

代替在按下submitbutton时执行JavaScript,而是使用普通按钮并从脚本执行submit函数。

You could do something like this:

function getFileCodeNumber(res){
    $.ajax({
        type: "post",
        url: "getFileCodeNumber",
        cache: false,
        data: { department: $("#department").val(), docType: $("#docType").val() },
        success: res,
        error: function(){  alert('Error while request..');}
    })
}

$(function() {
    if($("#chkLanguage").prop('checked')){
        //some stuff
        $("#form").submit();
    }else{
        getFileCodeNumber(function(data){
        //do some stuff with 'data'
        }).done(function(){
            $("#form").submit();
        });;
    }
});    

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