Let me Clear what title means:
In my code for a validation purpose of one field dependent on field "t1" I need to auto submit my form once (Just Once). But my below code is submitting it infinite times and I know the reason why its happening.
I guess Reason is everytime the form submits again JS in header runs. Please help me avoid this. Following is my code:
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm" method="Post">
<input type="text" id="t1" name="t1"/>
</form>
</body>
</html>
I tried stopping it using variable like flag and static variables like arguments.callee.count = ++arguments.callee.count || 1 and placing my CheckForm.submit() line in if clause. But nothing worked. Any advice or help is appreciable.
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("t1");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("CheckForm.t1");
temp1.value = "Task";
}
if(window.location.search=="")document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm">
<input type="text" id="t1"/>
</form>
</body>
</html>
Surely your form is more complex than:
<form name="CheckForm">
<input type="text" id="t1">
</form>
That will not submit anything to the server since there are no successful controls (the only control doesn't have a name).
Since the form is just submitting to the same page, you can submit a hidden value like:
<form name="CheckForm">
<input type="text" id="t1">
<input type="hidden" name="hasBeenSubmitted" value="yes">
</form>
Now when the form submits the URL of the new page will include ...?hasBeenSubmitted=yes so you can look for that value in the URL, e.g.
if (/hasBeenSubmitted=yes/.test(window.location.search)) {
// this page loaded because the form was submitted
}
If it exists, don't submit the form again.
So since you are using a post method the easiest way's to handle this is to ubmitted to a new url , however you seem set on keeping the form submitted to the same url in which case is you are using php (or really any other language) you can check if the http request has a post attribute with a value t1
<?php
if(isset($_POST['t1']){
$your_text=$_POST['t1'];
/*do some string checking to make safe and the throw into your database or mdo whatever you please with data
if you wanted to include the ip address of the user you can get a basic and most likely client ip address like so
$ip_address= $_SERVER['REMOTE_ADDR'];
if you are handing a mulitpage form look into php session or similar tech ... cookies is kind of over kill for this scenario
then include a succes page as the form has been submitted
or you could end php with this tag ?> and then have your html and start again with <?
*/
include 'form_submitted.php';
}else{
//this would be the html page that you included in your question and can be handle in same ways as form submitted
include 'my_form.php'
}
?>
Ip address may not be best included as it would stop 2 user from filling out the form if they are in the same LAN for eg. 2 people in same office or same house (if your page is acttual on the worldwide web).
I would take a look at #RobG answer as it he is basically suggesting the same type of thing with a get instead of post
ANyways hope this helps
Related
I am attempting to create a couple of web pages that will allow me to fill out a form on input.html and have the entered data appended to a different HTML file, index.html.
I have been searching for an answer for a couple of hours now and it might just drive me insane!
Here is some example code of what I'm trying to do:
HTML form input.hmtl:
<form>
<label>
Enter something:
<input type="text" id="userinput" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
Javascript to get entered data and pass to index.html:
var userInput = document.querySelector("#userinput");
var submit = document.querySelector("#submit");
function addToIndex()
{
// create new element on index.html
}
submit.addEventListener("click", addToIndex, false);
HTML output file index.html:
<div id="contentstart">
<!-- newly created element here -->
</div>
I have attempted using this solution, but Chrome's console gives me an error and tells me that newWindow is not a function. I just stumbled upon using the <iframe> element in a couple of answers but don't quite understand it yet (I'm a noob).
Thanks in advance!
The best option is to use a web server or a serverless implementation. Server code can be written in multiple languages. Some of the languages include PHP, NodeJS, and ASP.NET.
However, you can pass data using browser storage.
But, browser storage is not secure and can be wiped at any time by the user. If you are storing information such as passwords or data that should be visible to multiple users, you should use a web server and/or database.
You need to have a script on both pages. The page with the form will store/set the data. The index page will retrieve the data and use javascript to render more content.
function addToIndex()
{
localStorage.setItem('input', userInput .value)
}
The script for the index page would look something like this.
var data = localStorage.getItem('input');
if (input) {
document.querySelector('#contentstart').innerHTML = data;
}
I put together a simple demo here.
http://plnkr.co/edit/iAitGxtdsHwXowNg
For you to receive data from a form in a different file, you will need a server-side language like php.
So the form will have this structure
<form action="external_file.php" method="get">
<label>
Enter something:
<input type="text" id="userinput" name="user_input" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
Note the action="external_file.php and the name="user_input" attribute added to the input element.
Then the file: external_file.php might have the following structure to receive the content from the form
<?php
$input = $_GET["user_input"];
//do something with $input
echo 'The data you entered is: ' . $input;
?>
I showed you the way to start. The rest is up to you, you can do whatever you want to do. I hope you could help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id ="form">
<label>
Enter something:
<input type="text" id="userinput" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
<script>
let form = document.getElementById("form");
let userInput = document.getElementById("userinput");
form.addEventListener("submit", submitForm) //this function will work when the form is submit
function submitForm (e) {
e.preventDefault() // this event will prevent page refresh when form submit
let userInputValue = userInput.value; // userinput value
console.log(userInputValue);
moveToAnotherPage(userInputValue); //we send the value we get from userinput to use in another function.
}
function moveToAnotherPage (value) {
// Select the index2 html elements and add with innerhtml or something.
//to do this, you may need to save the userinput value you received to localStorage and pull it from it. I suggest you look into localStorage .And if you know php, you can use it.
}
</script>
</body>
</html>
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
I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.
I am a noob to programming, so I'd appreciate any advice from you more knowledgeable folks out there. I am working on a bit of javascript for a web page and I need the javascript to print to that current HTML page, preferably in the div tag I have set up for that purpose. Here's what I have so far:
<html>
<head>
<title>Tardy Reporting</title>
<script src="students.js" type="text/javascript">
</script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" onSubmit="getId(parseInt(document.idForm.studentId.value));">
<input type="text" name="studentId" id="studentId"/>
<input type="Submit" name="Submit" />
</form>
<div id="div1"></div>
<p>
</body>
</html>
and my JS file:
var studentNumberArray = [50011234, 50012345, 50013456];
var studentNameArray = ["Mike Simpson", "Greg Pollard", "Jason Vigil"];
var studentLastPeriodArray = ["George Washington", "Darth Vadar", "Obi Wan Kenobi"];
var tardyArray = [0, 0, 0];
function getId(studentId) {
for (i = 0; i < studentNumberArray.length; i++){
if(studentId === studentNumberArray[i]){
tardyArray[i] += tardyArray[i] + 1;
document.getElementById('div1').innerHTML='test';
}
}
}
Mind you, this is just the basic framework, so it's not nearly done yet, but the thing that is bugging me is that it'll go through the code correctly and print it out, but the result only lasts a fraction of a second on my browsers (chromium and firefox). Any help would be appreciated.
Here is an easier/better way to accomplish what you are trying to do
var students = {};
// Add students to object
students[50011234] = { 'id': '50011234', 'name':"Mike Simpson", 'lastPeriod':"George Washington", 'tardy':0 };
students[50012345] = { 'id': '50012345', 'name':"Greg Pollard", 'lastPeriod':"Darth Vadar", 'tardy':0 };
students[50013456] = { 'id': '50013456', 'name':"Jason Vigil", 'lastPeriod':"Obi Wan Kenobi", 'tardy':0 };
function getId(studentId) {
students[ studentId ].tardy += 1;
document.getElementById('div1').innerHTML='test';
}
Also, as pointed out below, you should change your button to not submit if that is not what you are intending to happen:
<form method="POST" name="idForm">
<input type="text" name="studentId" id="studentId"/>
<input type="button" onclick="getId(parseInt(document.idForm.studentId.value));" name="Mark Tardy" />
</form>
The reason why you see it only for a fraction of a second is that you are actually causing a submit. A submit is a full call back to the server which returns the page to its initial status.
To fix this simply make the function call on the onclick event of the button:
<html>
<head><title>Tardy Reporting</title>
<script src="students.js" type="text/javascript"> </script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" >
<input type="text" name="studentId" id="studentId" />
<input type="button" onclick="getId(parseInt(document.idForm.studentId.value));" value="submit" />
</form>
<div id="div1"></div>
<p>
</body>
</html>
What do you mean by "result"? It appears that you are setting the innerHTML of div1 to "test" over and over again.
Perhaps you mean to write
document.getElementById('div1').innerHTML += 'test';
Doing this is not efficient and it is preferable you concatenate on a string, or even better, join an array, before assigning the innerHTML.
but the result only lasts a fraction of a second on my browsers (chromium and firefox).
That is because you are submitting the page, so the page gets refreshed. You need to change the button type to button from submit. Also add a onclick to the button and call the js function getId
Forms are a special construct that allows communication with a server:
When a form is submitted, the form data is "POSTED" to a server via an HTTP request.
Typically, the browser displays the server's response as a new web page.
Forms use the action attribute to specify which server page should process the request
In your case, no action is specified, so the form POSTS to the current page, which is equivalent to refreshing the page. This means that all client-side (JavaScript) changes are wiped out, which is why you only see them for a split-second.
To achieve your desired result, change the input type from submit to button:
<input type="button" onclick=".." value="submit" />
Ideally, the student data exists in a database that is manipulated by code on a server. Your form would POST a request that returns an HTML page containing the desired data.
References
HTTP
Forms
I had to take my working example here. For some reason, it does not work as easily as the initial example.
New Example
Suppose I want to see M5s every time the page loads. So how can I fire the same query for M5 every time the page load?
I copied the critical part here:
<body>
<div id="search">
<form onSubmit="makeRequest(1); return false;" style="margin: 2px; padding: 2px; font-size: 1.2em;">
<input id="searchinput" type="text" name="tags" size="20" value="">
<input id="searchbutton" type="button" onClick="makeRequest(1);" value="Create VideoWall"><br />
...
</form>
</div>
Response to the idea in MiffTheFox's and Tom's reply
So I added the command before the form above:
<body onload="document.getElementById('myform').submit();">
However, the wall stays black. It should be full of M5s.
Emerged problem to the initial Question: Why does it not work? Why does the wall stay black?
makeRequest asked by Tom
function makeRequest(page){
startrequest = 0;
for(i =1; i < 4; i++){
clearList('ul'+i);
var tags = encodeURI(document.getElementById('searchinput').value);
if(i == 1 || i == 2){
quantity = 45;
}
if(i == 3){
quantity = 36;
}
insertVideos('ul'+i,'search',tags,quantity,startrequest);
startrequest = startrequest + quantity;
}
}
Please, see the url at the top and press CTRL+U to see the code.
Well, thereĀ“s on load attribute inside the body element
<body onload = "javascript:doSubmit()">
...
</body>
<script>
function doSubmit(){
var form = document.getElementById("myform");
if (form !=null)
form.submit();
}
</script>
Also, you could add javascript at the end of your html page. This is not as portable as the first option
<html>
<body>
<form id="myForm" ...>
...
</form>
<script>
//this executes when the page finishes loading
var form = document.getElementById("myForm");
if (form!=null) form.submit();
</script>
</body>
</html>
First add an ID to the form, then add an onLoad handler that submits it.
<body onload="myForm.submit();">
<form id="myForm" name="input" action="form_action.asp" method="get">
...
Not sure what you're trying to accomplish, but you can certainly use jQuery to do
$(document).ready( function() {
$("#submitButton").click();
});
The problem is ensuring that this only happens the first time the document is submitted; you will need to keep track of that on the server-side and remove the submission code after the first time.
A better approach is probably to compose your HTML on the server side so that whatever initial state you want to display is displayed. Many web applications have a form to submit a query of some kind (say, a search) but start with some initial sample result below the form. This is just created on the server side before loading, not by "pre-submitting".