AJAX: Submitting a form without refreshing the page

前端 未结 8 2015
感动是毒
感动是毒 2020-11-30 11:43

I have a form similar to the following:

8条回答
  •  我在风中等你
    2020-11-30 12:12

    /**
     * it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
     * for explanation why, try googling event delegation.
     */
    
    //$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
    $("#myForm").on('submit', function(event, optionalData){
        /*
         * do ajax logic  -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
         * $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
         * i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
         */
        //example using post method
        $.post('mail.php', $("#myForm").serialize(), function(response){
            alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
        })
        //example using ajax method
        $.ajax({
            url:'mail.php',
            type:'POST',
            data: $("#myForm").serialize(),
            dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
            success: function(response){
                alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
            },
            error: function(response){
                //as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
                alert("something went wrong");
            }
        })
        //preventing the default behavior when the form is submit by
        return false;
        //or
        event.preventDefault();
    })
    

提交回复
热议问题