Form tag and AJAX request - javascript

I made a simple page with a couple of radio buttons and a textfield as an exercise:
<html>
...
Student list: <input type="radio" name="list" value="students">
Lession list: <input type="radio" name="list" value="lessons">
<h2>Type the course code:</h2>
Code: <input type="text" name="code" id="code">
<input type="submit" id="submit">
</html>
And I added a listener to the button through Javascript.
Now via Javascript I collect the data from the various input fields, and pack them in a request:
function prepareRequest(req) {
var radios = document.getElementsByName("list");
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
value = radios[i].value;
}
}
var code = document.getElementById("code").value;
var url = "../AjaxServlet?value="+value+"&code="+code;
req.open("GET", url, true);
req.send();
}
I call my servlet through Javascript, GET my data, and then handle the response.
If I wanted to do this with "pure" HTML, I'd enclose those inputs in a FORM tag, like this:
<form action="../AjaxServlet" method="get">
...
<input type="submit" id="submit">
</form>
Now when I hit submit, the servlet is called "through" the form, which sends all the data it collected automatically. Of course this is synchronous and the page has to reload/redirect.
What I'm wondering is, with AJAX, is there any need for the form tag? What I did seemed intuitive enough, get the input elements from the DOM, extract the data and then pack them in a request manually. Is this right or wrong? Is there a standard or better way to do this?

This answer assumes jQuery use (which your question is not, kudos).
One of the benefits of using the form tag is the serialization of the form. Allowing for a cleaner approach of passing form data to your processing page.
It's also a bit cleaner (IMO) for form validation. Obviously there are many ways to validate form input but you can easily pass the form object and search for required elements having a valid value.
Adapted from Ajax and Forms on Learn.jQuery.com.
Although I would agree with celerno do what you need to do, but keep it at a minimum.

if you use form tag then your current web page will be change form tag page
example
in blabla.html
<form action=/api/send_hi method="POST">
<button name="ID" value="hi">
</form>
click button then current web page will be blabla/api/send_hi.html and result is
{ID: 'hi'}
if you use ajax then your current web page will not be change form tag page
in blabla.html
blabla ~~~
<script type="text/javascript">
function hi(){
$.ajax({
url: '/api/send_hi',
method: 'POST',
dataType: 'JSON',
data: {'ID': 'hi'},
async: false
}).done(function(data)){ // do if ajax communication success}
</script>
<body>
<button onclick=hi()>
</body>
this result is same as form tag result but current web page is not changed
still blabla.html not /api/send_hi.html

Related

HTML Form method vs jQuery function type

I'm totally a newbie on frontend development and just learning about jQuery.
I'm confused about "submit a HTML form with jQuery ajax". Here is a simple example:
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "PUT",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
As you see, when we click the button Send, the function formSubmit() will be invoked and the jQuery.ajax will do its job. It will send a http request with the type PUT.
But there is an attribute in the HTML form method="post", now I'm confused. When we click the button, what will actually happen? The jQuery.ajax will send a request in the js function but what will the method="post" do? Or method="post" can be ignored? If it does nothing, can we make the attribute method empty: <form class="form" action="" method="">?
Additional
Now I realise that the type of the buttion in this example is button, instead of submit. If I change the type into submit and click it, what will happen? Will it send two http requests, a post request comes from the form and a put request comes from the jQuery.ajax?
This example is badly designed and confusing.
The formSubmit function will only be called when the button is clicked. When the button is clicked, that function will run, and nothing else will happen; since the input is not a submit button, the form will not attempt to submit. All network activity will result from the jQuery.ajax inside the function. In this case, the <form> and the method="post" are ignored completely, since the form doesn't get submitted - the method used will be the one in the .ajax function, which is PUT.
But the form is still submittable, if the user presses enter while focused inside the <input type="text". If they do that, then the formSubmit function will not be called (since the button wasn't clicked), and the user's browser will send the name and the message as form data to the server, on the current page - and yes, as a POST. (Is the current page this code is on submit.php? If not, that may be a mistake. Perhaps the person who wrote the code completely overlooked the possibility of the form being submitable without using the button.)
To make the example less confusing, I'd change the button to a submit button, and add a submit handler to the form instead of a click listener to the button. Then have the submit handler return false or call e.preventDefault so that all network activity goes through the .ajax call.
The method attribute in HTML Form is used to send the form data when you're sending it without the help of an Ajax Request or any other scripting language.
When you use a scripting language like JS and Jquery, you have the chance to send the data via an AJAX request. Inside the AJAX request, you can define the method again. So, it won't rely on the HTML Form's method attribute.
Few resources you can follow:
https://api.jquery.com/jquery.ajax/
https://api.jquery.com/jquery.post/
The form tag gives support by giving several inbuilt default actions, but since you have defined a submit button and made a function to be executed onclick manually, so the form tag will only confuse the structure. So it's better to remove the form tag completely and you code will look like
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "PUT",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
Actually method and action tags are useful when you are not using any ajax request.
➡️ Suppose you are not using the ajax request then what will happen?
Since your method is POST it'll append the form-data inside the body of the HTTP request.
Then the form-data is sent to the page specified in the action attribute.
But since you are now controlling the form submission manually through ajax. You can skip those attributes. On that case you can specify on your formSubmit method what to do when your submission is completed.
You can also prevent the form submission using preventDefault.
For example:
<form onSubmit="formSubmit(event);">
<button>submit</button>
</form>
function formSubmit(e) {
e.preventDefault();
// Now you can set where to go when your form is submitted successfully.
}

Passing variables through multiple forms to PHP [duplicate]

Is it valid html to have the following:
<form action="a">
<input.../>
<form action="b">
<input.../>
<input.../>
<input.../>
</form>
<input.../>
</form>
So when you submit "b" you only get the fields within the inner form. When you submit "a" you get all fields minus those within "b".
If it isn't possible, what workarounds for this situation are available?
A. It is not valid HTML nor XHTML
In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:
"form must not contain other form elements."
http://www.w3.org/TR/xhtml1/#prohibitions
As for the older HTML 3.2 spec,
the section on the FORMS element states that:
"Every form must be enclosed within a
FORM element. There can be several
forms in a single document, but the
FORM element can't be nested."
B. The Workaround
There are workarounds using JavaScript without needing to nest form tags.
"How to create a nested form." (despite title this is not nested form tags, but a JavaScript workaround).
Answers to this StackOverflow question
Note: Although one can trick the W3C Validators to pass a page by manipulating the DOM via scripting, it's still not legal HTML. The problem with using such approaches is that the behavior of your code is now not guaranteed across browsers. (since it's not standard)
In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.
<form method="post" action="ServerFileToExecute.php">
<input type="submit" name="save" value="Click here to save" />
<input type="submit" name="delete" value="Click here to delete" />
</form>
The server side could look something like this if you use php:
<?php
if(isset($_POST['save']))
echo "Stored!";
else if(isset($_POST['delete']))
echo "Deleted!";
else
echo "Action is missing!";
?>
HTML 4.x & HTML5 disallow nested forms, but HTML5 allows a workaround with the "form" attribute ("form owner").
As for HTML 4.x you can:
Use an extra form(s) with only hidden fields & JavaScript to set its input's and submit the form.
Use CSS to line up several HTML form to look like a single entity - but it might be complicated to do.
As others have said, it is not valid HTML.
It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.
No, the HTML specification states that no FORM element should contain another FORM element.
A possibility is to have an iframe inside the outer form. The iframe contains the inner form. Make sure to use the <base target="_parent" /> tag inside the head tag of the iframe to make the form behave as part of the main page.
You can answer your own question very easily by inputting the HTML code into the W3 Validator. (It features a text input field, you won't even have to put your code on a server...)
(And no, it won't validate.)
rather use a custom javascript-method inside the action attribute of the form!
eg
<html>
<head>
<script language="javascript" type="text/javascript">
var input1 = null;
var input2 = null;
function InitInputs() {
if (input1 == null) {
input1 = document.getElementById("input1");
}
if (input2 == null) {
input2 = document.getElementById("input2");
}
if (input1 == null) {
alert("input1 missing");
}
if (input2 == null) {
alert("input2 missing");
}
}
function myMethod1() {
InitInputs();
alert(input1.value + " " + input2.value);
}
function myMethod2() {
InitInputs();
alert(input1.value);
}
</script>
</head>
<body>
<form action="javascript:myMethod1();">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input type="button" onclick="myMethod2()" value="myMethod2"/>
<input type="submit" value="myMethod1" />
</form>
</body>
</html>
As workaround you could use formaction attribute on submit button. And just use different names on your inputs.
<form action="a">
<input.../>
<!-- Form 2 inputs -->
<input.../>
<input.../>
<input.../>
<input type="submit" formaction="b">
</form>
<input.../>
no,
see w3c
No, it is not valid. But a "solution" can be creating a modal window outside of form "a" containing the form "b".
<div id="myModalFormB" class="modal">
<form action="b">
<input.../>
<input.../>
<input.../>
<button type="submit">Save</button>
</form>
</div>
<form action="a">
<input.../>
Open modal b
<input.../>
</form>
It can be easily done if you are using bootstrap or materialize css.
I'm doing this to avoid using iframe.
Fast Solution:
To obtain different validations to different forms and keep their submits in separated functions you can do this:
<form id="form1" onsubmit="alert('form1')"></form>
<form id="form2" onsubmit="alert('form2')"></form>
<div>
<input form="form1" required />
<input form="form1" required />
<div>
<input form="form2" required />
<input form="form2" required />
<button form="form2" type="submit">Send form2</button>
</div>
<input form="form1" required />
<button form="form1" type="submit">Send form1</button>
</div>
A non-JavaScript workaround for nesting form tags:
Because you allow for
all fields minus those within "b".
when submitting "a", the following would work, using regular web-forms without fancy JavaScript tricks:
Step 1. Put each form on its own web page.
Step 2. Insert an iframe wherever you want this sub-form to appear.
Step 3. Profit.
I tried to use a code-playground website to show a demo, but many of them prohibit embedding their websites in iframes, even within their own domain.
You are trying to implement nested form which is not supported in HTML.
Every form must be enclosed within a FORM element. There can be
several forms in a single document, but the FORM element can't be
nested.
Workaround
You can implement this functionality with some change in HTML and JavaScript. (without using html forms)
Steps
1. Create both forms with div tag as follows (do not use form tag)
<div id="form_a">
<input.../>
<div id="form_b">
<input.../>
<input.../>
<button id="submit_b">Submit B</button>
</div>
<input.../>
<button id="submit_a">Submit A</button>
</div >
2. Add JQuery and Ajax to submit each form data
<script>
// Submit form A data
$('#submit_a').click( function() {
$.ajax({
url: 'ajax-url',
type: 'post',
dataType: 'json',
data: $('#form_a input').not( "#form_b input" ).serialize(),
success: function(data) {
// ... do something with the data...
}
});
});
// Submit form B data
$('#submit_b').click( function() {
$.ajax({
url: 'ajax-url',
type: 'post',
dataType: 'json',
data: $('#form_b input').serialize(),
success: function(data) {
// ... do something with the data...
}
});
});
</script>
If you need your form to submit/commit data to a 1:M relational database, I would recommend creating an "after insert" DB trigger on table A that will insert the necessary data for table B.

submitting a form with link

I have following form structure
<form action="{Basket-Addproduct}" method="post" id="items-form">
<button class="button-text button-gray-custom" type="submit" value="Submit" name="{dynamically generated name}"><span>Submit</span></button>
</form>
here "dynamically generated name" is the key field which tells which element or product to submit..
I want it to convert it into link,
I have tried following
Add This
Its getting submitted but not able to add the product...
Its expecting the name parameter also to be passed so it knows which product to add...
Stuck....:(
Any solution appreciated...
you should have <input type="submit".
There is no need to do JavaScript.
Just remove JS and then have as many <input type="submit" buttons as you want.
The GET/POST should have the key/value you look for.
E.g.
<input type="submit" name="item1" value="submit" />
when you click it, the recipient receives (sorry PHP used here):
$_GET['item1'] = submit
and other submits do not have value.
You can use jQuery to do this clean and easy.
So, here's your link:
<a id="form-submit-btn" href="#" name="{dynamically generated name}">Add This</a>
And your form:
<form action="{Basket-Addproduct}" method="post" id="items-form">
<!-- form contents -->
</form>
Now write a JavaScript which submits your form data on a button click:
$('#form-submit-btn').click(function(e) {
e.preventDefault();
var $form = $('#items-form');
$.post($form.attr('action'), $form.serialize(), function(data){
// do something with the data
});
});
Your code should work, I have created an example for you to test, here it is: http://jsfiddle.net/afzaal_ahmad_zeeshan/yFWzE/
<form id="form">
<input type="text" name="something" id="something" />
</form>
Submit
By using this you will submit the form using the id of it. And other user told you to use jQuery, which I am afraid you don't want to. In jQuery you use .preventDefault but if you want to stick to the simple JS then you will be using href="#" which will automatically prevent any anchor tag execution.
And the result of the request can be checked, which sadly is an error. But it makes sure that the request has been sent to the server.
Then you can test the methods and other type of executions by having some if else blocks as
if(condition == true) {
// if post
} else {
// if get
}
The parameter might be mis handled on the server side, because when the form is submitted you need to take out the data from the QueryString (the request is GET). So, you need to check that, or if that's not the issue then make sure you're pointing the element well. Otherwise if there is no such element, nothing will be sent.
I am not sure, which language you're using but here is the code for ASP.NET
var value = Request.QueryString["something"];
PHP version is already present above. That all depends on the parameters you send with the request. You are more likely to convert the code to a function. Such as
Submit
And the function
function submit() {
// create variable
var value = document.getElementById("something").value;\
// now submit the form and all that other bla bla, which
// you want to be process,
}
If you find this one tricky, using jQuery as
var values = $('form').serialize();
will be easy. This will create a string of the form and will send it with the request.

Does a HTML form need an Action/Method in order to be submit?

Could this be submitted to a servlet without a Action or Method? I.E.(could you use Jquery alone to send this?, or some other method?)
<form id="form2">
<input type="text" value="12" name="ID"/>
<input type="text" value="NameThatComesFirst" name="FirstName"/>
<input type="text" value="NameThatComesLast" name="LastName"/>
<input type=submit id="submit" value="submit"/>
</form>
No, it doesn't need to be there, by default it will submit to the currently loaded script, using a GET.
If you want to submit it with AJAX, you can define it when calling it instead of through the action/method attribute if you want using the jquery form plugin.
$('#form2').ajaxForm( {
url: 'comment.php',
type: 'PUT',
success: function() {
alert('Thanks for your comment!');
}
});
// The suggested way is to put action and method on the form and `$.ajaxForm`
// will find it.
$('#form2').ajaxForm({ success: function() {
alert('Thanks for your comment!');
}});
You can always send the form yourself by querying the DOM and sending an AJAX request
The answer is yes if you want something to actually happen. By default if no value for the action attribute is specified then it will use the existing page. As for using jQuery only to handle for submission the answer is no. You must use some type of server-side code such as PHP, ASP, JSP, etc to handle the form. Optionally, you can also use server-side JavaScript like node.js if you want.
You can, however submit the form via ajax using jQuery. See the API
Default action for form submission is METHOD="GET" and ACTION="SELF". From the docs.
If the ACTION is missing, the URL for the document itself is assumed.

Prevent page reload on form submit

I am trying to submit a form using get method but I dont want the form to refresh or rather when it reloads I want to maintain the data. There seems to be lot of questions on similar lines but none that I tried helped. I am posting my code here:
<script type="text/javascript">
function formSubmit()
{
document.getElementById('form1').submit();
return false;
}
</script>
<form id = "form1" method = "GET">
<br> Query: <input name="query" id="query" type="text" size="50" value="">
<input type="button" name="search" value="Get News" onclick = "formSubmit()">
</form>
I am using python on the server side.
Thanks
The statement:
I am trying to submit a form using get method but I dont want the form to
refresh or rather when it reloads I want to maintain the data.
Implies to me that your end goal requires AJAX or at least some passing of data to the server and back. You will not be able to retain scope within Javascript over a page refresh without the use of something like cookies or passing data to/from the server. Having said that these are more akin to secondary storage mechanisms while you want to retain scope (or primary storage). To do this I would recommend AJAX.

Categories