TTT
TTT

Reputation: 4434

Ajax form submission

I am using ajax to submit a html input form and to redirect the output page when it is done. I tried two approaches but not sure why their results are different.

HTML form is something looks like this:

<form id="output_post" method="post" action="output.html">
    <table class="input"></table>
</form>

Approach 1:

    var frm = $('#output_post');
    frm.submit()
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        success: function (url) {
            window.location = "/output.html"
        }
    });

Approach 2:

    var frm = $('#output_post');
    $.ajax({
        type: "POST",
        url: frm.attr('action'),
        success: function(url) {
            window.location = "/output.html"
        }

    });

Approach 1 worked as I expected but I got error message in Approach 2 405 Method Not Allowed The method GET is not allowed for this resource. The difference between Approaches 1 and 2 is frm.submit(), and I am very sure both approaches have successfully initiate calculation.

Could anyone give me some hints on this issue? Thanks!

Upvotes: 0

Views: 145

Answers (2)

Anand Solanki
Anand Solanki

Reputation: 3425

Try this:

var frm = $('#output_post');

$('#output_post').submit(function(event) {

$.ajax({
        type: "POST",
        url: frm.attr('action'),
        success: function(url) {
            window.location = "/output.html"
        }

    });

});

- Thanks

Upvotes: 0

MackieeE
MackieeE

Reputation: 11862

Firstly, I would actually say .submit() would be better reserved for allowing the Browser to actually go ahead with the natural/indented behaviour of following through to the action="" - if you wanted to actually have a different 'end result' - that's where $.submit() comes into help.

/**
 *   $.submit will listen to
 *   the .submit event, preventing
 *   default and allowing us to mimic
 *   the submission process and have our
 *   bespoke end result.
**/
$('#output_post').submit(function(event) {
    event.preventDefault();
    var getValues = $(this).serialize();
    $.post( 'yourScript.php', getValues, function() {
        window.location.href = "/output.html";
    } 
});

Comments to the Question

Approach One

  • This 'leaves' the function. Prematurely sending you away from the page before it's allowed to execute the rest of the script. The native .submit() will follow through to the action, which is the indented behaviour. Thus, $.ajax never ran.

Approach Two

  • Servers could/can decide on it's accepted content types.
  • No Data was sent to the URL, thus - defaulted to GET (Despite type: POST) But there's no serialised. array given.
  • This may 'act' different if you define 'data: values' in Approach Two.

Upvotes: 2

Related Questions