7

I have a form similar to the following:

<form method="post" action="mail.php" id="myForm">
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="text" name="email">
    <input type="submit">
</form>

I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.

I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):

$.post('mail.php', $('#myForm').serialize());

If possible, I would like to get help implementing this using AJAX,

Many thanks in advance

AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • you need to prevent the default action. try prevent default function in jquery – Edwin Alex Jan 09 '13 at 12:51
  • 2
    @EdwinAlex Or just use simple `button` instead of `submit` – nanobash Jan 09 '13 at 12:52
  • @DaHaKa we can change it also. But why should we need while having option in script itself. – Edwin Alex Jan 09 '13 at 12:55
  • 1
    Changing it in the markup makes some sense too - the Submit button is specifically to tell the form that it needs to submit. Using a button instead means that there is no default behavior to worry about stopping (e.preventDefault or return false) and is, overall, less Javascript. – phatskat Jan 09 '13 at 12:59
  • 2
    The problem with changing the markup is that you remove the in built redundancy for anyone who has javascript disabled. – Rory McCrossan Jan 09 '13 at 13:00
  • What @RoryMcCrossan said is extremely important. If you use the page with JavaScript disabled, and you use `button` instead of `submit`, the form will no longer work at all. – Juha Untinen Sep 20 '13 at 10:16

8 Answers8

10

You need to prevent the default action (the actual submit).

$(function() {
    $('form#myForm').on('submit', function(e) {
        $.post('mail.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});
Kristof Claes
  • 10,797
  • 3
  • 30
  • 42
  • +1 Thanks for the reply. I would like to accomplish this using AJAX. – AnchovyLegend Jan 09 '13 at 12:54
  • $.post is a shorthand method for $.ajax({method: 'POST'}); – Thijs Kramer Jan 09 '13 at 12:57
  • 1
    My solution *is* using AJAX :-) It says "When the form is submitted (`$('form#myForm').on('submit', ...`), post the data using AJAX (`$.post(...)`) and prevent the default submit (`e.preventDefault()`)". – Kristof Claes Jan 09 '13 at 12:57
  • Oh... :) oops. I see what your saying. The only problem is on success or fail orf the `mail.php` html is outputted to the screen, I would like that to be returned as it normally would be using $.ajax(), is this possible? – AnchovyLegend Jan 09 '13 at 12:59
  • honestly speaking this answer helped me – Humphrey Aug 19 '15 at 14:29
4

You haven't provided your full code, but it sounds like the problem is because you are performing the $.post() on submit of the form, but not stopping the default behaviour. Try this:

$('#myForm').submit(function(e) {
    e.preventDefault();
    $.post('mail.php', $('#myForm').serialize());
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • +1 But I think a `return false` would be better (one less function call and property access) – Joseph Jan 09 '13 at 12:54
  • @JosephtheDreamer personally I prefer `preventDefault()` as it does not stop event bubbling etc. `return false` is an absolute blunderbuss approach to stopping an event. – Rory McCrossan Jan 09 '13 at 12:54
  • +1 Thanks for the reply. Can you please show how this can be done in Ajax? – AnchovyLegend Jan 09 '13 at 12:56
  • @MHZ I don't understand what you mean - the code in my example will solve your problem, unless there's something else you mean? – Rory McCrossan Jan 09 '13 at 12:58
  • The only problem is on success or fail orf the mail.php html is outputted to the screen, I would like that to be returned as it normally would be using $.ajax(), is this possible? something like `success: function(data){ $(".smart").html(data); ...` – AnchovyLegend Jan 09 '13 at 13:00
  • `ReferenceError: e is not defined` - how shall `e` be defined to avoid this error? – Markus L Jun 20 '17 at 12:19
  • Have you added in to the function call? `$('#myForm').submit(function(e) {` <-- – Rory McCrossan Jun 20 '17 at 12:39
4
/**
 * it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
 * for explanation why, try googling event delegation.
 */

//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
    /*
     * do ajax logic  -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
     * $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
     * i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
     */
    //example using post method
    $.post('mail.php', $("#myForm").serialize(), function(response){
        alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
    })
    //example using ajax method
    $.ajax({
        url:'mail.php',
        type:'POST',
        data: $("#myForm").serialize(),
        dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
        success: function(response){
            alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
        },
        error: function(response){
            //as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
            alert("something went wrong");
        }
    })
    //preventing the default behavior when the form is submit by
    return false;
    //or
    event.preventDefault();
})
Bodybag
  • 318
  • 2
  • 11
2

try this:

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});
axelduch
  • 10,769
  • 2
  • 31
  • 50
Japneet Singh
  • 261
  • 1
  • 3
  • 10
1

The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:

var form = document.getElementById('myForm');
var params = {
  method: 'post',
  body: new FormData(form),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
};

form.addEventListener('submit', function (e) {
  window.fetch('mail.php', params).then(function (response) {
    console.log(response.text());
  });
  e.preventDefault();
});
Greg
  • 9,963
  • 5
  • 43
  • 46
0

try this..

<form method="post" action="mail.php" id="myForm" onsubmit="return false;">

OR

add

e.preventDefault(); in your click function

 $(#yourselector).click(function(e){
      $.post('mail.php', $(this).serialize());
      e.preventDefault();
 })
bipen
  • 36,319
  • 9
  • 49
  • 62
0

You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.

By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).

If don't want this default action use preventDefault() method.

If you are using other than submit, no need to prevent default.

 $("form").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'save.asmx/saveData',
      dataType: 'json',
      contentType:"application/json;charset=utf-8",
      data: $('form').serialize(),
      async:false,
      success: function() {
        alert("success");
      }
      error: function(request,error) {
        console.log("error");
      }
Tom
  • 4,257
  • 6
  • 33
  • 49
-1

Take a look at the JQuery Post documentation. It should help you out.