2

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.

0

2 Answers 2

2

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.")
        }
    })
});
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks! And what if I'd like to implement an "IF", which checks for something. When it's true the form is submitted. False the submitting is cancelled, even though the user clicked the button.
@Soda I've updated the answer to show you an idea of how you would add a conditional.
Hey, thanks for the fast answers! The problem I'm having right now, that I'm doing a ajax request this java function. This ajax request checks for something in my own PHP file. If the response comes back true, then the form should be submitted. If false, then not. Now, the problem is, ajax takes too long and gets ignored. The form is submitted anyways. I'll edit my original post!
you can use $("#form1").submit() after get true
I implemented the exact same code, putting e.preventDefault() before AJAX. The submit still fires, regardless the outcome of the AJAX request. The alerts are still not showing. What am I missing?
|
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.