1

my HTML code is

    <form id="formoid" action="" title="" method="post" onSubmit="return myfunction(event)">
        <div>
            <label class="title">First Name</label>
            <input type="text" id="name" name="name" >
        </div>
        <div>
            <label class="title">Name</label>
            <input type="text" id="name2" name="name2" >
        </div>
        <div>
            <input type="submit" id="submit"  name="submit" value="Submit">
        </div>
 </form>

MY JS code is :

 <script src="https://code.jquery.com/jquery-1.9.1.js"></script>

            <script language="JavaScript">
function myfunction(event) {
      event.preventDefault();
   /// Here I am sending a post.. 
 //// how do I keep submitting? 

}
</script>

I made a function that stops the submission normally and I want to continue the submission after that. I need to stop the normal submission because I am sending a post using Ajax.

I tried many solutions like :

I could do

$(form).submit(function(e) {
  e.preventDefault();
  var self = this;

  // Code...

  if (true) {
    self.submit();
  } else {
    // Code...
  }
});

but I can't do it with the form name because I want to return the function onSubmit

is there a way to keep submitting without the need of $(form).submit(function(e) code line?

is there something that i can put in the function?

I.PSARN
  • 123
  • 1
  • 1
  • 5
  • Don't use `e.preventDefault()` and just use [`return true`](https://stackoverflow.com/a/35037437/1022914) as the final step when you want to submit (in your first code). – Mikey Jul 17 '17 at 18:07
  • Thanks mate, but I need to send a post in my function so I need to stop the page from submitting normally! any ideas? – I.PSARN Jul 17 '17 at 18:13

1 Answers1

0

With your code, I think if you did formoid.submit() you might re-fire myfunction() (or I could be wrong).

To stay on the safe side, I would just use onclick instead of onsubmit.

HTML

<form id="formoid" action="" title="" method="post">
    <!-- etc -->
    <div>
        <input type="button" id="submit" name="submit" value="Submit" onclick="myfunction()">
        <!-- note the use of type="button" to prevent the form from submitting normally -->
    </div>
</form>

JavaScript

var httpRequest;

// do the ajax call
function myfunction() {
    httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = callback;
    httpRequest.open('POST', 'some-path');
    httpRequest.send();
}

// once the callback has fired, submit the form
function callback () {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
            formoid.submit(); // submit form  
        }
    }
}

Sample AJAX code taken from here.

Mikey
  • 6,728
  • 4
  • 22
  • 45