post form values to html - javascript

I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>

Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists

You can't get POST values using JavaScript. You can use GET method to pass values.

If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/

You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.

Related

Set to true state a checkbox in a different page(javascript)

Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>

Missing POST parameters in AJAX call result in undefined index warnings in PHP script

I am using AJAX for the first time so I write a code and I followed a tutorial, but when I try to send my post with ajax I am getting undefined index and I really don´t know why, I tried to search answer hear but since I am using AJAX and javascript for the first time, the code there didn´t tell me anything.
Here is my code, I would be really greatful for any help, thank you.
js method
function post() {
var name = $('meno').val();
var priez = $('priezvisko').val();
$.post( "aktualizuj.php", {
'meno': name,
'priezvisko': priez
},
function (data) {
$('#result').html(data);
}
);
}
html form...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="prihlasenie.js"></script>
</head>
<body>
<form>
<label for="meno" >Meno:</label><input type ="text" name="meno" id="meno" value ="meno" ><br>
<label for="priezvisko" >Priezvisko:</label><input type ="text" id="priezvisko" name="priezvisko" value ="priezvisko" ><br>
<input type="button" value="ulozZmeny" onclick="post()" >
</form>
<div id="result"></div>
</body>
</html>
this where I should get from ajax/javascript
session_start();
require "pripojenie.php";
$meno = $_POST['meno'];
$priezvisko = $_POST["priezvisko"];
$login = $_SESSION['login'];
jquery doesn't serialize key:value pairs where value is undefined, i.e.
$.post(url, { foo:undefined });
results in jquery not sending any POST parameter.
The problem is because of the following lines,
var name = $('meno').val();
var priez = $('priezvisko').val();
This would look for an element meno and an element priezvisko (and then their values) as if you had a document like
<p>
<meno>...</meno>
<priezvisko>...</priezvisko>
</p>
But you're looking for elements that have meno/priezvisko as value of their id attribute(s):
var name = $('#meno').val();
var priez = $('#priezvisko').val();
You should nevertheless check the existince of the parameters in your php script. Nothing prevents another script/bot/user to invoke your script with different parameters or no parameters at all.
see also:
http://docs.php.net/isset
http://docs.php.net/filter

JavaScript upload size limit

so I'm trying to set up upload size limit, but it has been unsuccessful.
I have included the code with explanations, please hava a look and I would be very thankfull if you could help me.
More information on wha I needм help with is after the " // "
Here's the code: `
<html>
<p id="check"></p>
//ok so this part of <script> sends the user to "email.html"
<script type="text/javascript">
function getFile(){
document.getElementById("file").click();
}
function sub(obj){
var file = obj.value;
document.myForm.submit();
}
</script>
//here's the code for the button to upload a file (or image in my case)
<form action="e-mail.php" method="post" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">Yes</div>
<div style="text-align: center; overflow: hidden;">
<input type="file" value="upload" id="file" accept="image/*"
onchange="sub(this)"
size="1" style="margin-top: -50px;" "margin-left:-410px;" "-moz-opacity: 0;
"filter:
alpha(opacity=0);" "opacity: 0;" "font-size: 150px;" "height: 100px;">
</div>
</form>
<script>
var attachement = document.getElementById('file');
attachement.onchange = function() {
var file = attachement.files[0];
if (file.size < 1000000) {
function sub(obj){return true; }
//ok so here's the problem,
when I include this code between
'script' the user is not taken
to "e-mail.html" anymore... please help!!!
else { return false;}
}
}
</script>
</html> `
Thanks a lot:)
To go to a different page when the file is too big, you can assign the new URL to document.location. Note that the URL should be absolute (i.e. http://.../email.html).
I suggest to display an error when the file is too big and simply not submit the page. Otherwise, the user will see the new page and believe that everything was all right.
Also note that you need to do the same check on the server because an attacker might just create a POST request from scratch (without using the code from your page) to send files of arbitrary size to your server.
Because the funtion inside of the onchange is not global. It is only available to the onchange.
would would need to change it to
window.sub = function (obj){return true; }
BUT the flaw with this is the user can change the file a second time and submit since you just removed the return false. You could either add it back in on the else OR you can do validation when the form is submitted and not onchange.

JQuery not working through Google's CDN

For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here

Hidden form file POST in javascript

Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.

Categories

Resources