client-side form validation after clicking SUBMIT - javascript

I have 2 php files "source.php" and "target.php". In the source.php part I have,
<form method="POST" id="form1" action="target.php">
...
<input type="submit" name="submit" value="Submit"/>
</form>
When I click on submit it goes to the "target.php" (even if I have errors in the form), but I want that, only after all form fields are validated it will go to the target page, else it shows some kind of warning message and stays on the same page. Please help! Maybe this is a stupid question for some but I am a beginner. (I know how to do all the field validations and its working fine).

Duplicate of duplicate questions.Please search throughly before you post next time.
Generally javascripts are used for validation.But there are cases when javascripts become inefficient,for example when you need to validate country and its states.Its not practical to send the entire list of countries and states to the client. In such scenarios AJAX is used.By using AJAX the client sends the data to server immediatly after the user enters it.then it fetch only the required data.Its a simultaneous two way communication between client and server.for example if the user enters country name as INDIA,using AJAX states of INDIA are loaded for validation,thus saving bandwidth.
JavaScript and AJAX are not easy to learn,you must research try and correct different codes.Just google "JavaScript form validation"...
This is from w3Schools...
Required Fields
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
here is more basic examples http://www.w3schools.com/js/js_form_validation.asp
Good Luck

You can use AJAX to validate your form. JavaScript is not recommended for form validation.
A simple tutorial for AJAX Validation is available here
But be aware, even if you are validating your form before submission to target.php, always make sure that you check the data in target.php too. This is because JavaScript can be changed (thanks to the modern DOM interpreters) in the browser. It can be made so that the form is submitted without AJAX verification. So you should check it twice, before and after submission.
Also make sure to escape the data, as user input can never be trusted.
You should also user strip_tags($string) to prevent use from inserting php code.

JavaScript is most likely the easiest way to do this (read the other posts).
However, if you don't want to use JavaScript you could always check if all forms are set using isset() or something similar and then passing on the $_POST variables in the URL and grabbing those using $_GET. Of course make sure there isn't any sensitive information in the URL. In addition: you could always work with global variables.
Another way to do this without JavaScript is submit to a database after several checks (like escaping the strings etc.), perhaps even encrypt, but I don't suggest this since this is the long way around.

Related

change the way the form is submitted without using javascript

I have a form that is used for search on a website.
<form method="get" action="example.com/search">
<input type="text" name="search"/>
<input type="submit"/>
</form>
Lets say that I searched for "stack" when submitting I want the user to get redirected to example.com/search:stack
right now when submitting user gets redirected to : example.com/search?search=stack
How can I achieve that and allow it on devices that does not support javascript!?
You could set up your search page to redirect your users from /search?search=stack to /search:stack.
PHP:
if(isset($_GET['search']))
{
$search = $_GET['search'];
header('Location: /search:'.$search);
}
else
// no query handling
You'll need Url rewriting to do that.
URL Rewriting for Beginners
You cannot. Submitting a form in the way you describe, i.e. with the GET method, encodes the content of the form as a query string, which has this form:
?search=stack
See section 4.10.22 of the HTML5 Living Standard or section 17.13.3 of the HTML 4.01 Specification.
Correction: I'm sorry, I did not understand your question correctly. You indeed cannot change how the form is submitted, but you can redirect afterwards as you suggest.
Álvaro Martínez suggests a good way to accomplish that in his answer.

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

what happens on form submits in Coldfusion?

I'm struggling a little to understand the server-side of things using Coldfusion8 and thus far doing client-side stuff only.
Say I have a basic Coldfusion page layout like this:
<script type="text/javascript">
function foo() { docoument.myForm.submit(); }
</script>
<cfif isdefined("sendMyForm")>
... running coldfusion...
... displaying something...
</cfelse>
<form action="nextPage.html" method="post" name="myForm">
<input type="text" name="formContains" />
<input type="hidden" name="sendMyForm" value="yup" />
<input type="button" name="sender" value="send" OnClick="foo() />
</form>
</cfif>
Question:
What actually happens server-side when I submit the form? Is the page getting "re-loaded" and the cfif causes coldfusion to run and display results? Just looking for some basic info so I understand what's happening.
Thanks for hints!
Think of CF and most web servers/systems as accepting input (url/get, form/post, cookie, etc) and returning output (html, json, text, etc). That cycle generally repeats. Someone types in a web address in a browser, request goes to server, page returned with form. User hits submit, request goes to server, page returned with results. User clicks link, request goes to server...and on and on.
You need to have the form action submit back to itself due to the way the if statements are organized. If in form.cfm file then action should be form.cfm. Unless you setup specific mappings in the webserver to have CF handle html files then the file will need to be .cfm
You mention leaving the action attribute out all together submits the form back to the same page but I don't believe this works in every browser.
It is also more common/safer to have form method="post", then check for structkeyexists(form, "fieldname")
Ok. Not the latest links, but valuable information.
http://www.tek-tips.com/viewthread.cfm?qid=523839l
http://cookbooks.adobe.com/post_Email_contact_form_in_ColdFusion-16882.html
I was trying to understand how form submits work in Coldfusion. If the page structure is:
<cf "inputName" = "someValue">
... run the from logic
</cfif>
<cfoutput>
<form>
<input name="inputName" />
... more form
</form>
</cfoutput>
So when I submit the form without action, it gets submitted to the page it's on and therefore the first CF-part can run....

javascript code to prevent bots from submitting form

I need a javascript code to prevents bots from submitting forms.
But i need a client side code in javascript that work like CAPTCHA but don't call the server
thank you
Most straight forward and simple way will be to add or edit form data on the fly when the button is actually clicked:
<input type="hidden" name="SubmittedByHuman" value="NO" />
<input type="submit" value="Submit me" onclick="this.form.elements['SubmittedByHuman'] = 'YES';" />
Having this, on the server side check the value of form element called "SubmittedByHuman" - if it will be "NO" it means something bypassed the submit button - or as people mentioned correctly in comments, user did click but has disabled JavaScript.
do something like
<h1>Type the result in the input box : 1+1</h1>
<input id="sum" type="text"/>
and before submitting you check if the value in the input is 2 and then submit it.
To improve this type of code you could randomly create these 2 values in the h1 and save them into a var and before submiting check if input and sum are the same.
I doubt this is possible, as bots are sophisticated enough to bypass most things.
Remember, the bot isn't going to open the webpage in a browser and press submit. It'll probably scan the page for a <form>, make a list of all the <input> fields, and perform a POST request containing all the data for each one.
It won't run any javascript, or press any buttons. You'll have to make the check server-side.

Making sticky javascript

I have a javascript form where I am using innerHTML to set some text.
When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.
Thanks
<form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
Quick example I am capturing the name and need the div to show the name after the form submits.
You will need to persist the data somehow. There are several options:
Store it on the server. When the form is submitted, your server-side script will receive the data; it can persist it in a database, session variable, or some other form of storage that's appropriate for your application. Whenever the client re-visits the page with the form, have the server generate the form's HTML with the persisted data.
Use HTML5's local storage. While not supported in legacy browsers, all modern ones provide the local storage API. When the user submits the form (attach an event listener to the form's "submit" event), you can store the form data by making calls to localStorage[key] = value and retrieving it with localStorage[key].
Store it in a cookie. Although I don't recommend this approach, you can create a cookie with the form data. The only restriction is that the data needs to be represented as a string, but I recommend JSON. However, you probably should not use this approach since cookies are sent to the server for each request; if the form fields contain a lot of data, then you're also unnecessarily sending a lot of data to the server.
Using HTML5's local storage gives you a self-encapsulated approach that requires no server-side configuration:
<form action="" name="myform">
<input type="text" name="name">
<div id="theName"></div>
</form>
<script type="text/javascript">
(function() {
var form = document.getElementsByName('myform')[0];
if (localStorage['name'] !== undefined) {
var displayArea = document.getElementById('theName');
displayArea.textContent = localStorage['name'];
}
form.addEventListener('submit', function() {
var nameField = document.getElementsByName('name')[0];
localStorage['name'] = nameField.value;
}, false);
})();
</script>
Are you setting the "value" attribute of the input tags to something or blank? you can just remove (remove the attribute itself) that so that the last value set will be used (true only for non-password type inputs. also, haven't tried it in all browsers.).
Or better yet, you can use serverside script like (PHP, ASP, RUBY, etc) to set the attribute value to the previously submitted.
<form method="post">
<input type="text" name="txtinput" id="txtinput" value="<?php echo $_POST['txtinput']?>"/>
<input type="submit" value="submit">
</form>
doing it in js only is much more complicated and unreliable since your going to use cookies.
PS: I'm assuming your not using XHR(AJAX) to submit your forms since XHR's don't refresh pages or re-initializes inputs unless you told them to.
This should be happening server-side. Javascript is for enhancing a page, it's not to be depended on for data manipulation.
Your script, converted to PHP, would look like
<form action="" method="post" name="myform">
<input type="text" name='name">
<div id="theName"><?php
if(isset($_POST['name'])) { echo $_POST['name']; }
?></div>
</form>
...and it would work every time, without having to call any JS.
You'll have to handle the form data somehow anyway - how were you intending to retrieve the data without a server-side script?

Categories

Resources