Passing parameters from JavaScript - javascript

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/

Related

JavaScript validation does not stop submission to php script

I want to validate my code with javaScript and determine if it is okay to submit to php.
If it is correct I want the form to not submit to the php file that I have in 'action'.
If it is inncorrect I do not want the form to submit to the php file, and I want to display an error message.
Right now the form uses "onsubmit="return Validate()"" to call the validation function which displays a message and returns false to stop the form action. The problem is that the form action does not get stopped, and still runs. For some reason when I click the submit button twice the php message gets displayed then the java script message gets displayed.
My html form:
<form action="<?= base_Url(); ?>index.php/Login/loginuser" onsubmit="return Validate();" method="post" name="Login" accept-charset= "utf-8" >
Username: <input type="text" name="Username" maxlength="21" />
<br><br>
Password: <input type="text" name ="password" maxlength="20" />
<br><br>
<input type = "submit" value = "Login" class = "loginbutton" />
</form>
My java script function.
function Validate() {
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
From what I read online when onsubmit="return Validate()" gets returned false the form is supposed to not run. Thought this was right but cant figure out why its not working.
EDIT: I am useing codeigniter to display the url, and for other purposes on the project.
EDIT2: This is still not working... When the onsubmit is changed too, onsubmit="false" the php will not be called. Which is expected. When changed to onsubmit="true", the php will be called. Which is expected.
When onsubmit="return Validate();" and the Validation() function on says "return false;". It will for as expected. Same with return true. But when code gets placed in the function the boolean does not appear to be returned. The code below will not stop the php file from running when the login name is empty.
function Validate() {
if (document.getElementsByName("Username")=="" )
{
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
else
{
return true;
}
}
I am testing with chrome and firefox. There are no error messages displayed in the console on google chrome. I am not familiar with the debug tool for fire fox but i see no error messages displayed either.
I am now going to change the jquery script line to an updated version, maybe it will help..
I am using code igniter with controllers, views, libraries...
Everything was working fine until i started with the javascript validation.
You should use return false only when mandatory fields are empty
function Validate() {
// check whether mandatory fileds have some value or not
// document.getElementsByName("Username") always returns an array and will be robust way to access value by index 0 iin array like - document.getElementsByName("Username")[0]
if(document.getElementsByName("Username")[0].value == "" || document.getElementsByName("password")[0].value)
{
document.getElementById("errorMSG").innerHTML = "All fields required";
return false;
}
return true;
}
Please try this one 100% work
onsubmit="myFunction();return false;"
1.It should be just "Validate()" for onsubmit, not "return Validate().
And use onclick instead of onsubmit
Try this
<input type = "submit" value = "Login" class = "loginbutton" onclick = "Validate()"/>

Making form's onsubmit to work only for particular submits

In PHP program, I have JS function which validates submit <form ...onsubmit='return isOK();'>. It works OK. The problem is I want it to work only for particular submits, not for all. Is there any way inside the JS function to find out which submit was pressed, or some PHP trick
instead of onsubmit u can use onClick.
<input type="submit" onclick="return pressSubmit1()" value="submit1" />
<input type="submit" onclick="return pressSubmit2()" value="submit2" />
<form action="action.php" method="post">
...
<input name="submit" type="button" value="check me" onclick="submitform('check')" />
<input name="submit" type="button" value="do not check me" onclick="submitform('not check')"/>
</form>
in javascript:
function submitform(check)
{
if(check=='check') checkfrom();
}
in PHP
if($_POST['submit']=="check me")
checkform();
<form class="allowed" onsubmit='return isOK();'>
----
function isOK() {
if($(this).hasClass('allowed')) {
// Do stuff
}
}
your question is not clear, are you using a single submit button or different ones. If you're using different submit buttons then ofcourse you can make checks based on the id of the submit button. On the other hand if is a single submit button then it depends on what the conditions are for submitting or not submitting
It's better you write some HTML and Java Script code which you are using. So, it's easy to correct mistake is you have made somewhere in code snippet.
We can check which submit button is clicked, using PHP.
In the PHP page corresponding to the form submit, write
if(extract($_POST) && isset($submitbtn1)) {
// some validation for first submit button
}
elseif(extract($_POST) && isset($submitbtn2)) {
// some validation for second submit button
}
Note: we can use $ followed by submit button name inside the extract function. ie. $submitbtn1 is same as $_POST['submitbtn1']
Yes different onclick looks fine as mentioned in the accepted answer. But in the event handler you should have the
code as below. Note the preventDefault.
Also since submit is A button that submits the form. You can use button type instead of submit type and then there is no need for preventDefault. Here is the link of the code http://jsbin.com/wikose/4/
function testlogin(){
event.preventDefault();
var test = 'not validated';
if(test === "validated")
alert("not valid login");
else
$('form').submit();
return false;
}

How to stop form being submitted?

I'm using an asp.net webform page. I have some javascript that checks if some dynamically generated fields have values and then displays a message if not. The problem is that I haven't found a way to stop the form from being submitted when this check fails.
<form id="myform" name="myform" runat="server" onsubmit="finalCheck();">
I've tried button and input types:
<button type="submit">submit</button>
<input type="submit" value="submit"/>
The finalCheck() method always executes and does return false. But the form goes anyways.
Is there something else I need to do to prevent the form from being submitted?
write your html like this:
<form id="myform" name="myform" runat="server" onsubmit="finalCheck(event);">
then into your finalCheck(event) write this, on the first line for good practices:
event.preventDefault();
that will stop the submit and you can add more code after the preventDefault function to process the form data
The code in the event handler has to return the value from the function that it calls:
onsubmit="return finalCheck();"
The event handler function needs to return false. That function is onsubmit, not finalCheck.
onsubmit="return finalCheck();"
If you were using modern code, you could call preventDefault on the event object instead.
<script>
document.getElementById('myform').addEventListener('submit', finalCheck);
function finalCheck(event) {
var myForm = this;
// do stuff
event.preventDefault();
}
</script>

Form fields value get reset without page load

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.

How can I prevent a webform from submiting on 'Enter'

I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:
<input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/>
<div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/>
<script type="text/javascript">
//<![CDATA[
var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {})
//]]>
</script>
You should add an event handler to the form itself which calls a function to decide what to do.
<form onsubmit="return someFunction();">
And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false.
Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.
Trap the event and cancel it.
It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which.
You could use a regular button that submits the form on click instead of your submit button.
If you want the enter key to work in other fields, just handle it there and submit the form.
in the input element for the button do:
<input type='submit' value='submit' onclick='submiFunction(); return false;'>
or on the form itself
<form blabla onsubmit='someAjaxCall(); return false;'>
Which should stop the form from submitting.
the return false is the action that actually stops the form from submitting (it cancels the current event, which is sbumit)

Categories