Search code examples
javascriptjqueryajaxpython-2.7bottle

jquery $.ajax is not working. form post


I want use jquery to sent form data to server, and I follow this page↓

how do i submit a form using get method in jquery.

But is not working, has no any window alert. I don't know why....

I already import the jquery script in head(version 1.11.3).

<script src="./static/jquery-1.11.3.js" type="text/javascript"></script>

this is my script.

<script>
    function test(){
            document.getElementById("form_test").submit( function() {
                $.ajax({
                    url     : $(this).attr('action'),
                    type    : $(this).attr('method'),
                    data    : $(this).serialize(),
                    success : function( response ) {
                        alert( response );
                    },
                    error:function(){
                        alert("error");
                    }
                });
                return false;
            });
        }
</script>

this is my form code.

<form id="form_test" class="appnitro"  method="post" action="">
    <div class="form_description">
        <p>test.</p>
    </div>                      
    <ul >
        <li id="li_1" >
            <label class="description" for="info">info</label>
            <div>
                <input id="info" name="info" class="setInfo" type="text" maxlength="16" value=""/>
                <label id="infoMsg" class="Message"></label><br/>
            </div>
        </li>           
        <li class="buttons">
            <button type="button" class="mbutton" onclick="test()">submit</button>
        </li>
    </ul>
</form>

Solution

  • Remove the submit handler from test()

    document.getElementById("form_test").submit(function () {
    

    This is not required as the function test is being called when user clicks on the button.

    function test() {
        var $form = $('#form_test');
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            success: function (response) {
                alert(response);
            },
            error: function () {
                alert("error");
            }
        });
        return false;
    }
    

    I would also suggest you to use jQuery on() to bind event

    $('#form_test').on('submit', function () {
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success: function (response) {
                alert(response);
            },
            error: function () {
                alert("error");
            }
        });
        return false;
    });