3

I need help to make a form submit using AJAX in Vanilla JavaScript (No jQuery). I have this jQuery Code that i need converted to JavaScript.

  $(document).ready(function() {
    $('.myForm').submit(function (event) {
      var data = $(this);
      $.ajax({
        type: data.attr('method'),
        url: data.attr('action'),
        data: data.serialize(),
        success: function (data) {

        }
      });
      event.preventDefault();
    });
  });
Tim Levinsson
  • 597
  • 2
  • 7
  • 20

1 Answers1

10

You can use the built-in Fetch API for AJAX calls and FormData to parse your form.

Other than that, just replace your jquery with event listeners, query selectors, and attribute getters.

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('.myForm').addEventListener('submit', function (event) {
    var data = this;
    fetch(data.getAttribute('action'), {
      method: data.getAttribute('method'),
      body: new FormData(data)
    }).then(res=>res.text())
      .then(function (data) {
        
      });
    event.preventDefault();
  });
});
skara9
  • 4,042
  • 1
  • 6
  • 21
  • Thanks, i will give it a try. But it seems like you missed 2 parentheses? – Tim Levinsson Jan 25 '22 at 01:33
  • @TimLevinsson yes, fixed – skara9 Jan 25 '22 at 01:35
  • I have tried it. I am trying to get the data from the php file as i can do with the jQuery. I tried like this document.addEventListener('DOMContentLoaded', function() { document.querySelector('.myForm').addEventListener('submit', function (event) { var data = this fetch(data.getAttribute('action'), { method: data.getAttribute('method'), body: new FormData(data) }).then(res=>res.text()) .then(function (data) { console.log(data) }) event.preventDefault() }) }) – Tim Levinsson Jan 25 '22 at 01:38
  • 1
    Sorry i dont know how to wrap in code in the comments... – Tim Levinsson Jan 25 '22 at 01:39
  • 1
    Anyway, the problem is that when i do console.log(data) it does not return the content from the php file. It returns all the html code from the html file – Tim Levinsson Jan 25 '22 at 01:41
  • nvm... All works. Thanks ! – Tim Levinsson Jan 25 '22 at 01:42