Making sticky javascript - 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?

Related

Sending data to php script without ajax

I am required to send data from an html page, via input elements to a php script and I cannot use ajax for some reason. How to accomplish this?
My code is something like this:
HTML:
First Name : <input type"text" name="first_name">
<br><br>
Last Name : <input type"text" name="last_name">
<br><br>
<button id="submit_btn">Submit</button>
Now, I want the javascript to be something like :
function redirect_from_here() {
close(); //close the current window
window.location='./phpfile.php'; //load the new page which will process the data sent to it.
}
My question is how do I send the value in the input elements in the HTML portion, as data to be processed, to the php script (phpfile.php in this case).
Please note that I prefer not to use html form for doing the job.
You are using HTML form as there are input fields in you code.
Inputs are part of a form and should be wrapped by a form element
Why using JS for submitting the form when you can use <form action='script.php'.. for that?
I suggest that you revise your requirements instead of trying to come up with a hackish way of how to send the data..
Just submit a form with action="phpfile.php"
if not interested with html,
then in the window location bind the values as a GET form method do

client-side form validation after clicking SUBMIT

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.

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

Accessing data before sending it to server with Form.Request?

Is there a way to access the whole data array/object (which contains all the data form input fields etc) before sending it to the server with Form.Request? I know there is the extraData option which allows you to pass in other data, but I would like to access the actual form data and to some manipulation with it.
Before being sent to the server? I'm not entirely sure, the send method attached to Form.Request sends in the form itself, and the data, but this is probably after the request has already been fired off.
I tend not to use Form.Request, precisely because I have to do these form manipulations and such.
Instead of using a Form.Request Class, I simply iterate through the form's inputs as necessary.
e.g.
<form id="foobar">
<input type="text" id="lorem" />
<select id="ipsum">
<option>...
</select>
</form>
<script>
var formValues = document.id('foobar').getElements('input, select');
</script>

Submit HTML form to display entered info in new page

I have a HTML form (called form.html)and a JavaScript function such that when form is submitted, information in that form will be displayed.
Now I want all those info will be shown in new HTML page (called confirm.html), where should I go from?
NOTE: No php or sever-side or anything that really seriously related, it's just simple OFFLINE HTML-form problem, I just have 2 html place in same folder, I will test it on my browser, that's it. Only thing that I worry is how to use information from form.html file in confirm.html file since they are obviously separated.
Thank you very much, here is my form.html ( I dont have confirm.html yet)
<HTML>
<HEAD>
<TITLE>Contact</TITLE>
<script type="text/javascript">
function addtext()
{
var fname = document.myform.first_name.value;
var lname = document.myform.last_name.value;
var email = document.myform.email.value;
document.writeln("Thank you! You have just entered the following:");
document.writeln("<pre>");
document.writeln("First Name : " + fname);
document.writeln("Last Name : " + lname);
document.writeln("Email Address : " + email);
}
</script>
</HEAD>
<BODY>
<center>
<b>CONTACT US</b> <br></br>
<form name="myform">
<label for="first_name">First Name </label>
<input type="text" name="first_name" maxlength="50" size="30">
<br>
<label for="last_name">Last Name </label>
<input type="text" name="last_name" maxlength="50" size="30">
<br>
<label for="email">Email Address</label>
<input type="text" name="email" maxlength="80" size="30">
<br>
<input type="submit" value="Submit" onClick="addtext()">
</form>
</BODY>
</HTML>
Check out the window object of JavaScript: http://www.devguru.com/technologies/javascript/10855.asp
It has a property location, if you write into it, your browser will redirect:
window.location = "http://www.google.com";
Note though, that this will not post your data to confirm.html. what you are trying to do without server-side scripting is not very useful. An HTML form will use CGI (common gateway interface) to send data to a server, that can then process the information. If you use the file:// protocol (as you seem to be doing; all local, static files), there is no server-side to process the data, only JavaScript.
If using the GET method of sending the data through CGI, you could extract the data from the URL using javaScript (as mentioned in another question). To do this, just update your form like this:
<form action="confirm.html" method="get">
And do not put a onClick handler on the submit button, just let it submit.
Many other tools exist though that way more are suitable for the job: server-side scripting languages, examples include PHP, ASP, JSP. For local setups, your best best is using XAMPP.
If you don't want to rely on server-side technology, this becomes more complicated (and hacky, I might add). Probably the easiest would be to generate a url like this on submit -
http://localhost/confirm.html?first_name=val1&last_name=val2&email=val3
then add some code to confirm.html to unpack this. Here's a related question you may find helpful.
If you'd allow me a moment of editorializing, what exactly are you trying to do? If this is just a personal project to see how html works, then I'd strongly recommend starting to learn about server-side technology - once you start wanting to handle user data and persist state, you're pretty much forced to use the server. The web is by design pretty stateless; you can't pass variable in-between pages without either using the server, or through some very complicated AJAX & DOM updating techniques which tend to rely on specialized server files anyway. You can run a PHP & MySQL server locally using existing technology, and if you're interested in expanding your knowledge of web technology this is an inevitable step.

Categories

Resources