AnchovyLegend
AnchovyLegend

Reputation: 12538

AJAX: Submitting a form without refreshing the page

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

Upvotes: 7

Views: 38471

Answers (8)

SANJAY ARAKERI
SANJAY ARAKERI

Reputation: 49

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

Upvotes: 0

Greg
Greg

Reputation: 10352

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

Upvotes: 1

Japneet Singh
Japneet Singh

Reputation: 261

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

Upvotes: 2

Bodybag
Bodybag

Reputation: 318

/**
 * 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();
})

Upvotes: 4

Kristof Claes
Kristof Claes

Reputation: 10941

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

Upvotes: 10

a blue marker
a blue marker

Reputation: 42

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

Upvotes: -1

bipen
bipen

Reputation: 36551

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

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

Upvotes: 4

Related Questions