Soda
Soda

Reputation: 89

Form submission from javascript event, not form action

Ok, so this might be a little confusing question, but anyway: I have a form, targeting an external URL for validation.

<form
  id="form1"
  name="form1"
  class="formclass"
  accept-charset="UTF-8"
  autocomplete="off"
  enctype="multipart/form-data"
  method="post"
  novalidate
  action="https://www.external_url.com"
  >

However, I want to do something in the time, where the user clicks the submit button and the form gets send to the external URL. Basically, I'm trying to achieve that by deleting the action from the form there and creating an event handler:

button=document.getElementById("SubmitButton");
button.addEventListener('click', submitaction);

function submitaction() {
// Do something and THEN submit it to external URL
}

When I'm done "doing something" (e.g. maybe to display an alert before sending it), I want to take the whole form and send it to external. What do I need to do to exactly achieve the same output as the action in form?

Thanks guys!

EDIT:

I took the advice regarding the submit event listener. However, an AJAX request shall be made before submitting the form.

form1.addEventListener('submit', function(e) {
    $.ajax({
    type: 'POST',
    url: 'form_submission.php',
    data: {'check_input': input.value}, 
    success: function(response){
    if (response == true){
    alert("Thank you for your inquiry!");
    }
    }
    else {
    alert("Your input entered was incorrect.")
    e.preventDefault();
    }
    }
    }
    ); 

Somehow, the event listener just ignores my AJAX request and still submits the form. It doesn't even show the alerts, which is super strange.

Upvotes: 2

Views: 1018

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

This is a small snippet, illustrating the use of a fetch-post to check the input value before submitting the form. Only if the numerical value of the input field is >0 the form will be submitted.

form1.addEventListener('submit', function(e) {
  e.preventDefault();
  fetch("https://jsonplaceholder.typicode.com/users",{
   method: 'POST',
   headers: {'Content-Type':'application/json'},
   body: JSON.stringify({usrVal:input1.value})
  }).then(r=>r.json()).then(o=>{
    if (+o.usrVal>0) form1.submit()
  })
})
<form id="form1" name="form1" class="formclass" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate action="https://www.external_url.com">
  <input id="input1">
  <button>submit</button>
</form>

Upvotes: 0

Spectric
Spectric

Reputation: 31992

Removing the action attribute won't prevent form submission, it'll only reload the page.

You should instead attach a submit event listener on the form and add the code you wish to execute before submitting in the callback:

form1.addEventListener('submit', function(){
  alert('submit!');
})
<form id="form1" name="form1" class="formclass" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate action="https://www.external_url.com">
  <button>submit</button>
</form>

For conditional form submission, Event.preventDefault() is used to prevent form submission:

form1.addEventListener('submit', function(e) {
  if (!input.value.length > 0) {
    console.log('You have not filled out the input field')
    e.preventDefault();
  }
})
<form id="form1" name="form1" class="formclass" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate action="https://www.external_url.com">
  <input id="input">
  <button>submit</button>
</form>


If you're making an AJAX request, your code should look like:

form1.addEventListener('submit', function(e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'form_submission.php',
        data: {
            'check_input': input.value
        },
        success: function(response) {
            if (response == true) {
                alert("Thank you for your inquiry!");
                form1.submit();
            }
        }
        else {
            alert("Your input entered was incorrect.")
        }
    })
});

Upvotes: 2

Related Questions