Why is this form sending data twice? Also, the second time, the data is "undefined".
The form:
<form action="/loginPage" method="POST" >
Username: <input type="text" id="username"> <br><br>
Password: <input type="text" id="password"> <br><br>
<input type="submit" id="Login" value="Login" >
</form>
The client-side script:
$(document).ready(function(){
$('form').submit(function(event){
//event.preventDefault(); This prevents from sending data twice, but then the page doesn't redirect to "Hi, <username>"
$.post("/loginPage",{username: $("#username").val(),password: $("#password").val()}, function(data){
;
});
});
});
The server-side script:
app.post('/loginPage', function(req, res) {
var username = req.body.username;
console.log("Now, "+username);
res.send("Hi, "+username);
//res.sendFile(__dirname + '/lobby.html');
});
This is the output I get when I run this code:
Hi, Sho
Hi, undefined
I'm stuck at this one for the past whole day. Please help me.
When you submit the first time, jQuery fires and sends the POST through AJAX. The second submit is the HTML form firing. You want to stop the HTML form from submitting and use your custom handler instead.
The reason you're getting undefined is because you don't have name attributes on the inputs in your form.
You should return false; in your jQuery handler to prevent the form from firing, and do something with the response data as well.
Your code is posting via ajax, but it's not preventing the ordinary browser action of posting the form. You don't get any parameters from the normal form post because your <input> elements don't have "name" attributes.
You can return false; from the "submit" handler to prevent the normal form submission.
Try this instead: return false in your form onsubmit to prevent it from submitting twice
<form action="/loginPage" method="POST" onSubmit="return false" >
Related
Context
I have a working standard form, with method POST, with a standard submit button, and I would like to leave this in this way.
<form id="myform" method="post"... >
...
<input type="submit .../>
</form>
However in some circumstances, I would like to programmatically send the form data to server side and re-render the form. Sending the form data with GET would be great this case.
Question
How can I achieve that document.myform.submit(); use the GET method, instead the POST what is declared in the <form ...> element?
You can always send your data to your serverside by AJAX request and do whatever you please by the response value that you receive. There are plenty of examples if you research it.
Also here's another source to help you get through this problem.
Click here
In my opinion, I will do this(Explicitly Submit form from js)...
<form id="my-form" method="post"... >
...
<button id="btn-submit" type="button" .../>
</form>
<script>
const submit = document.getElementById('btn-submit');
submit.addEventListener('click', function(event) {
event.preventDefault();
const form = document.getElementById('my-form');
if(SOME CONDITION) // some usecases in which we need different method.
{
form.method = 'POST';
} else {
form.method = 'GET';
}
form.submit();
});
</script>
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.
}
I have a HTML form with some fields and a submit button. couple of fields are mandatory. I have a set of JavaScript code which i need to execute only if the form validation is successful. If there is some validation error on the form, the JavaScript code shall not execute. Below is the sample code:
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
/*JavaScript*/
$("#sampleForm").submit(function(){
//Set of JavaScript code to execute if validation is success.
});
For me above JavaScript code does not work.
Please help!
In a comment you've said:
But if i use $("#sampleForm").submit() to submit the form, the form gets submitted but if i write function inside submit() ($("#sampleForm").submit(function(){ //Set of JavaScript code to execute if validation is success. });) then nothing happens !
That function is called when the submit event is fired, but the event isn't fire when the controls are invalid because the form won't be submitted.
The individual form controls get an invalid event when the user tries to submit the form when they're invalid. You can use that to provide feedback beyond what the browser supplies if you like:
$("#sampleform")
.on("submit", function() {
alert("Got the 'submit' event; form is being submitted");
})
.find("input, select")
.on("invalid", function() {
// Will fire for *EACH* invalid control
alert("Validation failed");;
});
Fiddle (Stack Snippets don't allow form submission even when it's cancelled.)
In case you need to submit the form programmatically (by calling submit), you can use checkValidity first to see if the form is valid:
// When submitting programmatically
var form = $("#sampleForm");
if (form[0].checkValidity()) {
form.submit();
}
Side note: When you use jQuery to submit the form (above), submit event handlers will be called. But if you use the DOM to submit the form ($("#sampleForm)[0].submit()), they won't be.
Just write a submit handler and execute your codes.
$("#sampleForm").submit(function(){
// Your code.
})
Submit handler triggers only when you complete the validation by HTML5 custom validator.
Here is a demo : http://jsfiddle.net/sureshatta/9ky8Z/118/
Html5 form have checkValidity method.Also since it is a form and button type is submit it will default throw an error pop up if it is not valid. checkValidity method return a boolean value true if it is valid. You can take a look in this method for further your job
$("#sampleForm").submit(function(e) {
var result = document.getElementById('firstname').checkValidity()
console.log(result) // will log true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
Thanks everyone for the answers!
I tried each one of your's solution which helped me to reach to my solution. Below worked for me:
if($("#sampleForm").valid()){
$("#sampleForm").submit();
//Set of JavaScript code to execute.
}
I realize that Ajax is the recognized way to submit a form without page refresh but to do that involves cycling through each field and constructing the Post string to submit.
Is there not some alternative way to use the browsers built-in functionality to submit the form but intercept the returned html to stop the page being refreshed?
Edit:
Not the same as the suggested duplicate which asks about form validation: "I am wanting to run javascript user validation"
Edit2:
The primary problem is how to stop the servers response to the submit from navigating to a new page. Is there something the server could respond with which would stop the whole page getting refreshed?
Edit3:
What about returning an http 204 response:
Server has received the request but there is no information to send back, and the client should stay in the same document view. This is mainly to allow input for scripts without changing the document at the same time
yes there is.. the idea is to have the form action and the onsubmit event handled
consider the code below:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
at this point you are intercepting the call to ensure that the form is valid. if everything passes than a page refresh will trigger. If you want the refresh not to occur you need to handle the post via ajax where you will need to rebuild the entire call. hope this will help you out.. cheers
a simple way to do it, if you are using jquery is to serialize the data using the
http://api.jquery.com/serialize/ functionality
one way to do this is if you are using jQuery:
<form id="myForm" name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
$.post(url, data);
}
I have an html form like this:
<form action="myServer.com/test.php" method="post">
...
</form>
When the form is submitted, the user should be redirected to myServer.com/test.php and ofc send the post data to the script. BUT at the same time (or before), I want to post the same POST data to another script "myServer.com/test2.php".
$.post("myServer.com/test2.php", variableWithTheFormPOSTData);
I tried to attach an EventListener to the form submit, but that doesn't seem to work, maybe the jquery post cant be submitted fast enough before the redirection?
I hope you can help me. :(
Whenever you use a method with onsubmit, make sure it returns true, otherwise it won't submit.
use a button as your submit button sothat the form doesnt get posted at the same time you click on it. And trigger the ajax function to post the data indirectly to the second page.
<form name="myform" action="myServer.com/test.php" method="post">
...
<button onclick="doIndirectPost();"></button>
</form>
and in the success callback of ajax posting function trigger your form post
function doIndirectPost() {
//initialize variableWithTheFormPOSTData here
$.post("myServer.com/test2.php", variableWithTheFormPOSTData,function(success,error) {
//ajax post is completed now we trigger the form post to test.php
document.myform.submit();
});
}
You can do it using ajax itself, which will avoid reloading the page
<form id="form1">
.....
<input type="text" name="email"/> <!--Example input text box-->
<input type="button" id="submit"/>
</form>
and the jquery code
$("#submit").click(function()
{
$.post("myServer.com/test2.php", $("#form1").serialize());//$("#form1).serialize() will get the data in the form automatically
$.post("myServer.com/test.php", $("#form1").serialize());
});
.serialize() will automatically serialize the data from the form that is to be posted
in your server side page use this
<?php
parse_str($_POST['serialize'], $data);
$name = $data["email"]
// do your code
?>
Hope this helps,Thank you