Vettan Maximillion
Vettan Maximillion

Reputation: 167

Prevent page reload and redirect on form submit ajax/jquery

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.

Upvotes: 10

Views: 78485

Answers (8)

Yashas
Yashas

Reputation: 999

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.

Upvotes: 0

Ahmed Mabrouk
Ahmed Mabrouk

Reputation: 29

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.

Upvotes: 0

John
John

Reputation: 4006

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>

Upvotes: 1

Kaif Khan
Kaif Khan

Reputation: 166

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.

Upvotes: 3

What have you tried
What have you tried

Reputation: 11148

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);
      }
    });
});

Upvotes: 31

firstmadcoding
firstmadcoding

Reputation: 65

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

Upvotes: 2

Samuel Cook
Samuel Cook

Reputation: 16828

function sendForm(){
    // all your code
    return false;
}

Upvotes: 4

stf
stf

Reputation: 31

Have you tried using

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

Upvotes: 2

Related Questions