简体   繁体   中英

Ajax prevent default and submit form on current page

I have the following script, which works perfectly BUT the problem is I need a form action attribute for it to work, thus my question how can I modify my current script that it prevents default form submit behaviour and submits form on current page without the need for an action attribute in form

$(function() {
  var form = $('#editRes');
  var formMessages = $('#formMsg');
  // Set up an event listener for the contact form.
  $(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();
    //do the validation here
    if (!validateLog()) {
      return;
    }
    // Serialize the form data.
    var formData = $(form).serialize();
    // Submit the form using AJAX.
    $.ajax({
      type: 'POST',
      url: $(form).attr('action'),
      data: formData
    }).done(function(response) {
      // Make sure that the formMessages div has the 'success' class.
      $(formMessages).removeClass('error').addClass('success');
      // Set the message text.
      $(formMessages).html(response); // < html();
      // Clear the form.
      $('').val('')
    }).fail(function(data) {
      // Make sure that the formMessages div has the 'error' class.
      $(formMessages).removeClass('success').addClass('error');
      // Set the message text.
      var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
      $(formMessages).html(messageHtml); // < html()
    });

  });
  function validateLog() {
    var valid = true;
    //VALIDATE HERE
    return valid;
  }
})

In your ajax, you are using url: $(form).attr('action') . This means the form will get submitted to whatever is the action attribute of your form. Since there is none, the ajax will not work.

If you want the form to be without an action tag, you can just write the form submit url ( page.php ) in the ajax url part

$.ajax({
    type: 'POST',
    url: 'page.php',
    data: formData,
    ...
    ...
});

Another option is to window.location.href .

Side-note: You do not need to rewrap form in $() as it is already a jQuery object in your second line -- same goes for formMessages .

$(function() {
    var form = $('#editRes'); // this is a jQuery object 
    var formMessages = $('#formMsg'); // this is also a jQuery object

    // Set up an event listener for the contact form.
    form.submit(function (e) {
        // Stop the browser from submitting the form.
        e.preventDefault();
        // do the validation here
        if (!validateLog()) {
            return;
        }
        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: window.location.href,
            data: form.serialize()
        }).done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            formMessages.removeClass('error').addClass('success');
            // Set the message text.
            formMessages.html(response); // < html();
            // Clear the form.
            $('').val('')
        }).fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            formMessages.removeClass('success').addClass('error');
            // Set the message text.
            var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
            formMessages.html(messageHtml); // < html()
        });
    });

    function validateLog() {
        var valid = true;
        //VALIDATE HERE
        return valid;
    }
});

At the end of your submit function add:

return false;

This will prevent to browser from navigating away.

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