I want to save this form data using ajax. Anyone help me to resolve below issue.
If I am entering all entries correct and submits it refreshes page.
And if i enter any on incorrect and submit it send error. and then if i fill all correct it works fine.
But get refresh in first case.
Below is the script
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/lib/jquery-1.10.2.js'></script>
<script type='text/javascript' src='script/plugin/form-validator/jquery.form-validator.min.js'></script>
<script>
$(document).ready(function(){
$.validate({
modules : 'location, date, security, file',
borderColorOnError : '#ddd',
//errorMessagePosition : $messages,
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
});
function validate_rgn(){
$('#registration_form').submit();
$.validate({
form : '#registration_form',
onSuccess : function() {
alert('right');
return false; // Will stop the submission of the form
},
});
}
</script>
</head>
<body>
<form action="/registration" method="POST" id="registration_form">
<p>
Name (4 characters minimum):
<input name="user" data-validation="length"
data-validation-length="min4"/>
</p>
<p>
Year (yyyy-mm-dd):
<input name="birth" data-validation="date"
data-validation-format="yyyy-mm-dd"/>
</p>
<p>
Website:
<input name="website" data-validation="url"/>
</p>
<p>
<input type="button" value="save" onclick="validate_rgn()" />
</p>
</form>
</body>
</html>
Validation script from http://formvalidator.net
The event handler doesn't return anything:
onclick="validate_rgn()"
The function between " and " has no return statement. You call another function and ignore the return value.
validate_rgn doesn't return false. The only return statement inside it belongs to a different function, the anonymous one you pass to to onSuccess.
The form is submitted because you call $('#registration_form').submit();, there is nothing preventing that from firing.
A dirty solution would be to forget about returning anything and just move $('#registration_form').submit(); inside the onSuccess function.
A cleaner solution would be to:
Use a real submit button
Bind your event handler to the submit event of the form (instead of the click event of the button)
Set up your validation routine so it does actually return (no idea how you would do that, it looks like it is asynchronous, I'd look at rewriting it so it wasn't)
Related
Here's my situation. I have a submit button. When clicked, some backend/database validation takes place and if everything's good, submit the form and disable the button so the form can't be submitted twice. If it does not pass validation, submittal cannot take place and the button stays active, so the user can resubmit the form. It sounds simple but I can't make it work. This is a C# web application.
I have tried to add the code to the button on page load. When the submit button is clicked and if validation fails, remove the code that disables the button. But here is my problem. Since the "disable" code is removed and the user fixes any error and resubmit, the button can be clicked more than one as the code is no longer there.
I do not want to use Ajax for this because the backend check is very complicated. Is there another way to do it? I've tried to add the "disable" code on "load" but it does not work on post back when the validation fails.
if (window.addEventListener)
window.addEventListener("load", lockSubmit, false);
else if (window.attachEvent)
window.attachEvent("onload", lockSubmit);
else window.onload = lockSubmit;
Any help is appreciated.
Try the snippet below
window.onload = function(){
// Insert the following function somewhere in your .js file / section
(function prevent_over_submitting(){
var form = document.forms.theform;
if(form || form.nodeName == 'FORM'){
form.onsubmit = function(){
form.submit.value = 'Proccesing...';
form.submit.disabled = true;
};
}
})();
};
While your form should look something like this one
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<input type="text" name="lastname" value="" />
<input type="submit" name="submit" value="submit" />
</form>
Here is a working jsBin so you can play around.
Update:
The logic behind the snippet above
// server-side code (rather in pseudo-code this time)
if(form_has_been_submitted){ // check if the form has been submitted
errors[] = validate_data(post_data); // call the method to validate data
if(errors_array_is_empty){ // if everything is fine
submit_data(); // submit data
redirect_or_do_something; // (maybe) do other things
} // otherwise don't do anything
}
// validation method
validate_data(post){ // the only argument here represents all your form data
error = array;
if(post['firstname'] == wrong){ // check for error
error['firstname'] = 'Check your firsname'; // if you found one, push it to the error array
}
if(post['lastname'] == wrong){ // the same as in previous case
error['lastname'] = 'Check your lastname'; // the same as in previous case
}
return error; // return that array, it might be full or empty
}
// client-side code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyApplication</title>
<script type="text/javascript">
// the JavaScript snippet from above
</script>
</head>
<body>
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<!-- show the error if you found one, otherwise show an empty string -->
<span><% (error['firstname'] ? error['firstname'] : "") %></span>
<input type="text" name="lastname" value="" />
<!-- same as in the previous case -->
<span><% (error['lastname'] ? error['lastname'] : "") %></span>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
As you can see, the JavaScript snippet above only disables the submit button onclick to prevent over-submitting; it will be enabled once the page is loaded again. This isn't my favorite way of validation but I followed your logic.
you can add this code in the onclick function:
First, add a global javascript variable, say var click = false;
and add this condition before validation occurs:
if(click){
return false
} else {
your normal validation code
}
if your page reloads each time you submit, then there is no need to add anything further, but if doesn't then add setInterval method which will reset the click variable for next use if validation fails.
The state of the click variable will remain true after first click and will further stop multiple clicks, unless page reloads or we reset the variable manually through code.
I'm learning javascript and tried my hand at calling functions. Based on the example here, I tried to use the logic in my test html:
<html>
<head>
<script>
function ShowForm()
{
var field_value = document.forms["test_form"]["my_name"].value;
document.write(field_value);
}
</script>
</head>
<body>
<form action="" name="test_form" onsubmit="return ShowForm();" method="post">
<input type="text" name="my_name" placeholder="Type your name"/>
<button type="submit">My button</button>
</form>
</body>
</html>
I found that the html renders correctly, however upon clicking the "My button" button, the page simply reloads without displaying the additional html I expected.
The main different is that I'm trying to use <button> for the click/submit action. Is it possible to use a <button> and activate the javascript? Or should I just style the <input> as a button?
What am I doing wrong here?
Use
onsubmit="ShowForm();return false"
Instead of
onsubmit="return ShowForm();"
Adding return false will prevent page from reloading, removing return from return ShowForm(); will allow javascript to run return false after ShowForm().
Example
I have form and the form submission can be done by either clicking on a hyper link or on a submit button. However I want my server to realize what has been used for form submission.
Current code snippet looks like this:
<a href=javascript:{} onclick="formSubmit()";>Next</a>
<input type="button" name="search" value="Get Result" onclick = "formSubmit();">
And my formSubmit() looks like this
<script type="text/javascript">
function formSubmit()
{
document.getElementById('form1').submit();
return false;
}
Any pointers as to how to go about it.
Thanks
Use a hidden parameter in your form.
< input type="hidden" value="0" name="flag"/>
When the form is submitted using javascript change flag value to '1' in the script.
function formSubmit()
{
document.form1.flag.value="1";
document.getElementById('form1').submit();
return false;
}
in case submit button is pressed the flag = '0'.
you can get this parameter on the server to determine how the form is submitted
edit : change your button type to 'submit' or call different scripts for both actions.
Pass a value (say an int or boolean) into the function. The value passed can be used to determine the source.
you invoke the same function to submit the form,so if you want your server to realize what has been used for form submission,i think you must pass a parameter to your server
You can use event.target to get the source that triggered the event and then set a flag to pass to server. See the example below:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(e)
{
alert(e.target);
}
</script>
</head>
<p>
Click on a paragraph. An alert box will alert the element that triggered the event.</p>
<p>
<strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.</p>
This Link Click will return "javascript:{}"
<a href=javascript:{} onclick="myFunction(event)";>Next</a>
<p>
This Button Click will return "[objectHTMLInputElement]"
<input type="button" name="search" value="Get Result" onclick = "myFunction(event);">
</p>
</body>
</html>
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'm working on a script where all I want it to do (right now) is redirect the user based on which button they press. Eventually it will take form input and incorporate that into the redirect, but right now I'm just trying to get the buttons to send the user off to the appropriate site. However, My redirects aren't working.
<html>
<head>
<title>
Home
</title>
</head>
<body>
<script type="text/javascript">
<!--
var textstring;
var btnWhichButton;
//Gets the text from the form
function getQ() {
textstring = document.forms['Search'].elements[0].value;
}
//Does a Google Search
function googleSearch() {
window.location ="http://www.google.com";
}
//Does a YouTube Search
function youtubeSearch() {
window.location = "http://youtube.com";
}
//Figure out which button was pressed
function whichButton() {
if (btnWhichButton.value == 'Google Search' ) {
googleSearch();
} else if (btnWhichButton.value == 'YouTube Search' ){
youtubeSearch();
}
}
//main function to run everything
function main() {
getQ();
whichButton();
}
// -->
</script>
<form name="Search" >
<input type="text" name="q" size="31" maxlength="255" value="" />
<input type="submit" value="Google Search" onclick="btnWhichButton=this; main();" />
<input type="submit" value="YouTube Search" onclick="btnWhichButton=this; main();" />
</form>
</body>
</html>
When either button is clicked, the page just reloads with ?q= appended to the url, it doesn't redirect. Any help?
You want to use a button not an input type='submit'. Your current buttons are submitting the form, not performing their onclick actions.
Or block the submit action in some way. Or you could use your functions to set the form action to the url and just let it submit.
Your scripts seem highly overcomplicated. Why not have three functions: getQ, googleSearch, and youTubeSearch? Then inside the onClick event you can call the exact function, including this.value inside the input parameters and calling getQ from inside that function? Your method seems highly inefficient. If you're going to have separate functions for each of them anyways, there's no use in going through two other functions in order to get to them.
A submit button will always submit the form without a return false at the end of the onClick event, and since the default posting method is GET, its attaching ?q= to the end of your URL because that field is blank and it's the only input field in the form.
For redirecting to new page you no need to use the big javascript function.
<html> <body>
<input type="button" value="Google Search" onclick="javascript:window.location.href='http://www.google.com'" />
<input type="button" value="You tube Search" onclick="javascript:window.location.href='http://youtube.com'" />
</body></html>
Please check whether it helps you.
Well as jasonbar says, change your input to be of type 'button' and not 'submit'. Plus, I'd rather use window.location.href instead of window.location only. I don't know possible this is good practice...happy programming.