Do I still need a form element when using an AJAX request?
This might be a stupid question, but it's really important for me to know, do we really need to PROVIDE our input elements on the a side <form>
, even though we are using jQuery Ajax to send and receive data from Server or Database?
I mean while Ajax method has parameters like type, url, data and even dataType like below
$.ajax({
type: "POST",
url:"process.php",
data: data,
dataType: "JSON"
});
Do we still need a form? From the security aspect, I think we can validate user inputs without a form element, but I'm not sure if this is correct or not ?! If you think we still need a form, how are we supposed to deal with Form attributes like action
and method
? should we leave them blank? Thanks to
No, there is no need to wrap input (or other) elements in form tags when using ajax.
However, there are times when using a form construct is a good idea, for example if you want an input key to submit a form.
However, if you are using a form or submit button <input type="submit"
, you must remember to use return false;
or e.preventDefault();
events in your code to prevent the form from being submitted and the page refreshed. For example:
$('#myForm').submit(function(event){
event.preventDefault();
//do your validation, ajax, etc stuff
});
As a result, I rarely (if ever) used form tags and instead used jQuery / js to manipulate the ux itself.
Link:
Why use a form tag when submitting via ajax?
When using Ajax, the form serves several purposes. It provides:
- a way to send data to the user to the server if failure for some reason is impossible.
- convenient DOM interface for controls inside it (
formElement.elements.field_id_or_name
) - semantic grouping that is (for example) used by screen reader software
- handling an enter key press to trigger a send event across all fields
You don't need it strictly unless you want a reliable, accessible, and effortless page.