10

I have looked through all the similar posts out there but nothing seems to help. This is what I have

HTML:

<section>
  <form id="contact-form" action="" method="post">
    <fieldset>
      <input id="name" name="name" placeholder="Name" type="text" />
      <input id="email" name="email" placeholder="Email" type="text" />
      <textarea id="comments" name="comments" placeholder="Message"></textarea>
      <div class="12u">
        <a href="#" id="form-button-submit " class="button" onClick="sendForm()">Send Message</a>
        <a href="#" id="form-button-clear" class="button" onClick="document.getElementById('contact-form').reset()">Clear Form</a>
      </div>
      <ul id="response"></ul>
    </fieldset>
  </form>
</section>

JavaScript/jQuery:

function sendForm() {
  var name = $('input#name').val();
  var email = $('input#email').val();
  var comments = $('textarea#comments').val();
  var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
  $.ajax({
    type: 'post',
    url: 'js/sendEmail.php',
    data: formData,
    success: function(results) {
      $('ul#response').html(results);
    }
  }); // end ajax
}

What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things. I would really appreciate your help on this.

Weafs.py
  • 22,731
  • 9
  • 56
  • 78
Vettan Maximillion
  • 167
  • 1
  • 2
  • 10

8 Answers8

31

Modify the function like this:

function sendForm(e){
  e.preventDefault();
}

And as comment mentions, pass the event:

onclick = sendForm(event);

Update 2:

$('#form-button-submit').on('click', function(e){
   e.preventDefault();

   var name = $('input#name').val(),
       email = $('input#email').val(),
       comments = $('textarea#comments').val(),
       formData = 'name=' + name + '&email=' + email + '&comments=' + comments;

    $.ajax({
      type: 'post',
      url: 'js/sendEmail.php',
      data: formData,
      success: function(results) {
        $('ul#response').html(results);
      }
    });
});
What have you tried
  • 11,018
  • 4
  • 31
  • 45
  • 1
    Don't forget that the event object needs to be passed into the function call – Sterling Archer Oct 25 '14 at 21:39
  • `onclick="sendForm(this)"` not `event` – Samuel Cook Oct 25 '14 at 21:46
  • Thank you but it doesn't work. Thing is just before it refreshes I can see that ul was populated. I tried aside from preventDefault() using return false in the onClick such as "sendForm(); return false;" putting return default after ajax, having both preventDefault() and return false; and any combination of placements really. – Vettan Maximillion Oct 25 '14 at 21:51
  • @VettanMaximillion Get rid of the inline event handler, and then see my "update 2" – What have you tried Oct 25 '14 at 21:52
  • Thank you so much. I tried that before and it didn't work, turns out in my ignorance and desperation I didn't realize that my script was in the head and not the body. With your assistance I nailed it down. Thank you and especially for such a quick reply. – Vettan Maximillion Oct 25 '14 at 22:45
4
function sendForm(){
    // all your code
    return false;
}
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
3

I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-

Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-

<form method="POST" enctype="multipart/form-data" id="test-form">

var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();

var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);

var formData = new FormData(document.getElementById('test-form'));
request.send(formData);


This would send your data successfully ...without page reload.

Kaif Khan
  • 166
  • 1
  • 6
2

Have you tried using

function sendForm(event){
    event.preventDefault();
}
stf
  • 31
  • 2
2

Simple and Complete working code

<script>
    $(document).ready(function() {
        $("#contact-form").submit(function() {
            $("#loading").show().fadeIn('slow');
                $("#response").hide().fadeOut('slow');
                 var frm = $('#contact-form');
                 $.ajax({
                     type: frm.attr('method'),
                     url: 'url.php',
                     data: frm.serialize(),
                     success: function (data) {
                         $('#response').html(data);
                         $("#loading").hide().fadeOut('slow');
                         $("#response").slideDown();
               }, error: function(jqXHR, textStatus, errorThrown){
              console.log(" The following error occured: "+ textStatus, errorThrown );
            } });
           return false;
        });
    });
</script>

#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form

1

Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
    <button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>

This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
John
  • 3,458
  • 4
  • 33
  • 54
  • Unfortunately this won't hit the button when a user presses [enter], but still tries to submit the form. – ti7 Sep 23 '20 at 17:32
0

I expect anyone to understand my idea very well as it's a very simple idea.

  1. give your required form itself an id or you can get it by any other way you prefer.

  2. in the form input "submit" call an onclick method from your javascript file.

  3. in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
    To clarify that see this:

    // element refers to the form DOM after you got it in a variable called element for example:
    element.addEventListener('submit', (e) => {
       e.preventDefault();
       // rest of your code goes here
    });  
    

    The idea in brief is to deal with the form by submit event after dealing with submit button by click event.

Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.

Of course it will work only with forms.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Ahmed Mabrouk
  • 31
  • 1
  • 6
0

The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:

<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
                            onclick="javascript:sendRequest()">Save
                            changes</button>
<div>

Javascript:

function sendRequest() {

        $.ajax({
            type: "POST",
            url: "/some/url/edit/",
            data: {
                data: $("#myform textarea").val()
            },
            success: function (data, status, jqXHR) {
                console.log(data);
                if (data == 'success') {
                    $(`#mymodal`).modal('hide');
                }
            }
        });

        return true;
}

I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.

Note: The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

Yashas
  • 809
  • 8
  • 16