Asked  7 Months ago    Answers:  5   Viewed   22 times

How do I prevent a form from submitting using jquery?

I tried everything - see 3 different options I tried below, but it all won't work:

    $(document).ready(function() { 

            //option A
            $("#form").submit(function(e){
                e.preventDefault();
            });

            //option B
            $("#form").submit(function(e){
                stopEvent(e);
            });

            //option C
            $("#form").submit(function(){
                return false;
            });
    });

What could be wrong?

Update - here is my html:

    <form id="form" class="form" action="page2.php" method="post"> 
       <!-- tags in the form -->
       <p class="class2">
           <input type="submit" value="Okay!" /> 
       </p>
    </form>

Is there anything wrong here?

 Answers

84

Two things stand out:

  • It possible that your form name is not form. Rather refer to the tag by dropping the #.
  • Also the e.preventDefault is the correct JQuery syntax, e.g.

        //option A
        $("form").submit(function(e){
            e.preventDefault();
        });
    

Option C should also work. I am not familiar with option B

A complete example:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

        <script type='text/javascript'>
         $(document).ready(function() {
            //option A
            $("form").submit(function(e){
                alert('submit intercepted');
                e.preventDefault(e);
            });
        });
        </script>
    </head>

    <body>
        <form action="http://google.com" method="GET">
          Search <input type='text' name='q' />
          <input type='submit'/>
        </form>
    </body>
</html>
Tuesday, June 1, 2021
 
eek
answered 7 Months ago
eek
60

Capture the form submission in jQuery and then stop it with preventDefault();

$(function(){
  $('#formID').on('submit', function(e){
    e.preventDefault();
    var formSrc = $(this).attr('action');
    var formMethod = $(this).attr('method');
    var formData = $(this).serialize();
    $.ajax({
      url: formSrc,
      type: formMethod,
      data: formData,
      success: function(data){
        //work with returned data from requested file
        alert(data);
      }
    });
  });
}); 

EDIT:

i should add that I chose to use on(); as opposed to the default submit(). This is because the form may or may not be available at DOM.ready.

Wednesday, March 31, 2021
 
Lorav
answered 9 Months ago
99

I do it like this and it works exactly how you want it to work:

$("#myform").submit(function(e) {
    e.preventDefault();
}).validate({
    rules: {...},
    submitHandler: function(form) { 
        alert("Do some stuff...");
        //submit via ajax
        return false;  //This doesn't prevent the form from submitting.
    }
});
Thursday, July 15, 2021
 
Raef
answered 5 Months ago
14

Update

And here is how you can submit:

var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);

// form data
var formData = $('#formID').serialize();

var data = varsData + '&' + formData;

$.ajax({
  type: 'POST',
  url: 'servers_side.php',
  data: data,
  success: function(res){ alert (res) }
})

You can use jQuery.param() to convert an array or an object into url-friendly name-value paris. You may also need to use jQuery.serialize() to convert form data into name-value paris. Here is how you can go about:

var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);

// form data
var formData = $('#formID').serialize();

var data = varsData + '&' + formData;

Now data contains all data of your custom vars and form elements you can send in ajax request.

Saturday, August 21, 2021
 
fatihk
answered 4 Months ago
10

The jQuery Form Plugin offers simplicity of using ajax with forms. It will use the form attributes to determine how and where to submit the form. The form's method attribute tells the plugin the request type to use. The form's action attribute tells it where to submit the form.

Considering an example form like this:

<form id="myform" action="submit.php" method="post">
<!--inputs and submit button go here-->
</form>

In essence it allows you to write:

$('#myform').ajaxForm();

instead of

$.post("submit.php", $("#myform").serialize());

The jquery Form plugin will also allow you to submit via Ajax from your code.

$('#myform').ajaxSubmit();

The jQuery Forms Plugin will serialize the form anyway, your going to have to serialize before you submit to the server. The jQuery Form Plugin just serializes the form behind the scenes. The examples above do not handle any responses from the server.
Using the code below you can append the response to elements whose class attribute contains "result".

$('#myform').ajaxForm({ target : ".result"});

You can use any selector that is supported in jQuery for the target option.

I'm not sure if you can use deferred methods with it or not. I doubt it because the compatibility is for 1.3.2+ and the native ajax methods are wrapped up in the plugin. Such that the Deferred object is never returned from the plugin internals.

The jQuery form does have a beforeSubmit option that can be used. So adding to the above code we get:

$('#myform').ajaxForm({ target: ".result", beforeSubmit: function(arr, $form, options) {
        // arr: The array of form data
        // The array of form data takes the following form: 
        // [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] 

        //some code to check if we already submitted the form

        // return false to cancel submit                  
    }
});

However, I would recommend against doing that if user is done with the page after they submit the form. It would only add unneeded complexity to your client-side code. Should be okay if the user will be doing other stuff on the page after the form submission. The jQuery Forms Plugin has a success option that takes a function callback to be called if the server returns a 200 "OK" response. You can also check out the authors website for the plugin http://jquery.malsup.com/form/ for much more info on the plugin.

Saturday, November 13, 2021
 
Classified
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share