I would have thought the form object would have been populated with formmethod and formaction.
Question: Is there a way to get to formaction? Or find out which button in the form was clicked, to access them from the button?
Do I need to rewrite my event handler to catch clicks on the button ($(document).on('click', '.myformbtn', function(e)
) and use var queryString= $(this).parent('form').serialize();
to access the form.
<form>
<button type="submit"
formmethod="POST"
formaction="/mysave">Save</button>
<button type="submit"
formmethod="GET"
formaction="/mydata">Get new data</button>
</form>
$(document).ready(function()
{
$(document).on('submit', 'form', function(e) {
e.preventDefault();
var formaction = $(this).getFormAction();
var queryString= $(this).serialize();
$.ajax({
type: formmethod,
url: formaction,
data: queryString
});
});
});
I have found similar questions and the answer is always $(this).attr('formaction')
which is incorrect as the form does not have that attribute. I'm hoping providing an example of how it would be used will get peoples brains working.
The formaction attribute specifies where to send the form-data when a form is submitted. This attribute overrides the form's action attribute. The formaction attribute is only used for buttons with type="submit" .
When you submit a form through the GET method, PHP creates a $_GET associative array in this format, $_GET['name as key'] to enable you to retrieve the form data. The GET method is suitable to send non-sensitive content/information to the server.
Considering your code we can get the button which caused the form submission in following way:
var target = e.originalEvent || e.originalTarget;
var clickedElement = $( target.currentTarget.activeElement);
$(document).ready(function()
{
$(document).on('submit', 'form', function(e) {
e.preventDefault();
var target = e.originalEvent || e.originalTarget;
var clickedElement = $( target.currentTarget.activeElement);
var formaction = $(clickedElement).attr("formaction");
var formmethod = $(clickedElement).attr("formmethod");
alert(" formaction "+formaction);
var queryString= $(this).serialize();
$.ajax({
type: formmethod,
url: formaction,
data: queryString
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
This is my form with 2 submit buttons<br><br>
<button type="submit"
formmethod="POST"
formaction="/mysave">Save</button>
<button type="submit"
formmethod="GET"
formaction="/mydata">Get new data</button>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With