Home php Correct example of Ajax request for form submission using jQuery and JavaScript

Correct example of Ajax request for form submission using jQuery and JavaScript

Author

Date

Category

We need a correct example of Ajax request for submitting a form using jQuery and JavaScript, but so that after submitting the form data, there is no transition to the page specified in the “action” attribute of the form. Thanks in advance.


Answer 1, authority 100%

$ (function () {
   $ ('form'). submit (function (e) {
    var $ form = $ (this);
    $ .ajax ({
     type: $ form.attr ('method'),
     url: $ form.attr ('action'),
     data: $ form.serialize ()
    }). done (function () {
     console.log ('success');
    }). fail (function () {
     console.log ('fail');
    });
    // cancel the default action for the submit button
    e.preventDefault ();
   });
  });

Answer 2, authority 39%

$ ('form'). submit (function (e) {
  e.preventDefault ();
  var data = $ ('form'). serializeArray ();
  $ .ajax ({
    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType});});

well, of course, url should contain the address of the page to which the request is sent.
Also, instead of preventDefault , you can return a value: return false;


Answer 3, authority 22%

$ (document) .ready (function () {
  $ ("# btn"). click (
    function () {
      sendAjaxForm ('result_form', 'ajax_form', 'action_ajax_form.php');
      return false;
    }
  );
});
function sendAjaxForm (result_form, ajax_form, url) {
  jQuery.ajax ({
url: url, // url of the page (action_ajax_form.php)
    type: "POST", // sending method
    dataType: "html", // data format
    data: jQuery ("#" + ajax_form) .serialize (), // Serialize the object
    success: function (response) {// Data sent successfully
      result = jQuery.parseJSON (response);
      document.getElementById (result_form) .innerHTML = "Name:" + result.name + "& lt; br & gt; Phone:" + result.phonenumber;
    },
    error: function (response) {// No data sent
      document.getElementById (result_form) .innerHTML = "Error. Data not sent.";
    }
  });
}

Full example with Backend in php: https : //ru.wh-db.com/article/kak-otpravit-formu-bez-perezagruzki-stranici/

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions