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);
}
Related
Website works like that there is a radio button with satisfaction from a product.
There are 2 options (sts1 and sts2) and if client selects any of those 2 they get to satisfied page after sending a form to an email.
3 other options (dsts1, dsts2, dsts3) get client to dissatisfied page after sending a form to an email.
The problem is that: when i press submit button it takes me to satisfied or dissatisfied page based on the radio button but I don't get any email from that form. I've commented out onsubmit="return redirection();" and It worked normally and I got an email but I need that redirection as well. Im kind of new so I would appreciate a little help with that.
HTML
<form autocomplete="off" id="msform" method="POST" action="send.php" name="frm" onsubmit="return redirection();">
JS
function redirection() {
if(document.getElementById('sts1').checked || document.getElementById('sts2').checked){
window.location='satisfied.html';
return false;
}
if(document.getElementById('dsts1').checked || document.getElementById('dsts2').checked || document.getElementById('dsts3').checked){
window.location='dissatisfied.html';
return false;
}
return true;
}
I have an app that wants to redirect after submitting and I would like to freeze it after clicking submit. The app is a multiform that has an end slide that I would like the animation to trigger and then freeze it from redirect/refresh.
<form id="form" class="msform hs-form stacked hs-custom-form" accept-charset="UTF-8"
action="confidential-url" enctype="multipart/form-data" method="POST" novalidate="">
<!-- form stuff -->
</form>
$(".submit").click(function () {
return true;
e.preventDefault();
});
I have tried adding onSubmit="return false" to my <form> tag as well as various e.preventDefault(); methods. All of them will either:
• Cause it to prevent the redirect/refresh but not update the fields in the DB
• Update fields but page will still redirect
EDIT:
After trying to do this in AJAX I found out that I was being blocked out from the external URL, thanks to to r4phG for helping me figure it out!
Is your submission causing your redirection/ refresh ?
If you have to submit your form to update fields in your database, you'll have to submit your form. But if you don't want to refresh all your page, you should think of using Ajax, as your submission will not refresh your page
Example from jquery ajax doc :
$("#form").submit(function() {
$.ajax({
url:'confidential-url',
method:'POST' ,
data:$(this).serialize() //submits your form information
});
return false; // prevent the server form submission
});
jQuery ajax documentation
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" >
Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.
I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a submit button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page writing location = mail.php but it appears that the form parameters don't get passed to my PHP page this way.
How do I validate input in JavaScript and pass parameters to my PHP page when ok?
TIA
Steven
You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.
You'd have a javascript function something like this:
function check_it_all() {
if (all_ok) {
return true;
} else {
return false;
}
}
And the form
<form action=..... onsubmit="return check_it_all();">
....
</form>
Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here.
You should still use the submit button to submit the form, that is the correct behavior.
Input validation should be done using the <FORM>'s onSubmit event.
It should look something like this:
<script>
function validate() {
var isFormValid = whatever; // validate form
return isFormValid;
}
</script>
<form action="your.php" method="POST" onSubmit="return validate()">
<!---fields--->
</form>
The function validate() returns a bool.
This will stop the submission if validate() returns false.
<input type="submit" onclick="return validate()" value="click" />
I am an aspx.net developer so I am used to putting the validation call on the button.
If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.
Such as
http://bassistance.de/jquery-plugins/jquery-plugin-validation/