Reputation: 4434
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
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
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";
}
});
Approach One
.submit()
will follow through to the action, which is the indented behaviour. Thus, $.ajax
never ran.Approach Two
URL
, thus - defaulted to GET
(Despite type: POST
) But there's no serialised. array given.Upvotes: 2