0

I have written this code so that I can make a multi-step form and load and submit the data through AJAX.

The code is running well for the first form submission, but on the second attempt the page reloads itself. Can someone help me?

$(document).ready(function() {
  jQuery.ajax({
    type: "post",
    url: 'index.php'
  }).done(function(msg) {
    $('#main-container').html(msg);
    index();
  })

  function index() {
    $('#myForm').submit(function(e) {
      e.preventDefault();
      var formData = $('#main-container').find('form').serialize();
      console.log(formData);
      jQuery.ajax({
        type: "POST",
        url: 'index.php',
        data: formData
      }).done(function(msg2) {
        console.log(msg2)
        $('#main-container').html(msg2);
      });
    });
  }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Assuming each AJAX request reloads the `#myForm` element, then you probably just need to use a delegated event handler: https://stackoverflow.com/q/203198/519413 – Rory McCrossan Aug 04 '22 at 10:10
  • i tried it but the page at second click of button relaodes it self that's creating a problem to me..how can i stop the page from reloading – Aaryan Rathore Aug 04 '22 at 10:48

1 Answers1

0

#This is how it is done#

$.ajax({ //here i have inculded the php file where i am holding all the multi step form data in other page which i am going to show to the user
  type: "GET",
  url:'index.php'
}).done(function(msg) {
  $('#main-container').html(msg);
  nextBtn();
  backBtn();
})
    

function nextBtn() { //this is the next btn or you may call the submit btn 
  $(document).on('click', ".next", function () {
    var formData = $('#myForm').serialize();
    console.log(formData);
    $.ajax({
      type: "POST",
      url:'index.php',
      data: formData
    }).done(function(msg2) {
      console.log(msg2)
      $('#main-container').html(msg2);
    });
  });
}