AJAX: Submitting a form without refreshing the page

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

I have a form similar to the following:

相关标签:
8条回答
  • 2020-11-30 12:12

    You need to prevent the default action (the actual submit).

    $(function() {
        $('form#myForm').on('submit', function(e) {
            $.post('mail.php', $(this).serialize(), function (data) {
                // This is executed when the call to mail.php was succesful.
                // 'data' contains the response from the request
            }).error(function() {
                // This is executed when the call to mail.php failed.
            });
            e.preventDefault();
        });
    });
    
    0 讨论(0)
  • 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();
    })
    
    0 讨论(0)
  • 2020-11-30 12:19

    try this:

    $(function () {
        $('form').submit(function () {
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });
    
    0 讨论(0)
  • 2020-11-30 12:20

    The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:

    var form = document.getElementById('myForm');
    var params = {
      method: 'post',
      body: new FormData(form),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    };
    
    form.addEventListener('submit', function (e) {
      window.fetch('mail.php', params).then(function (response) {
        console.log(response.text());
      });
      e.preventDefault();
    });
    
    0 讨论(0)
  • 2020-11-30 12:21

    Take a look at the JQuery Post documentation. It should help you out.

    0 讨论(0)
  • 2020-11-30 12:28

    You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.

    By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).

    If don't want this default action use preventDefault() method.

    If you are using other than submit, no need to prevent default.

     $("form").submit(function(e) {
        e.preventDefault();
        $.ajax({
          type: 'POST',
          url: 'save.asmx/saveData',
          dataType: 'json',
          contentType:"application/json;charset=utf-8",
          data: $('form').serialize(),
          async:false,
          success: function() {
            alert("success");
          }
          error: function(request,error) {
            console.log("error");
          }
    
    0 讨论(0)
提交回复
热议问题