Though a novice in javascript, I need to take javascript variable (an array) reflecting what a user has done on client side and post it to a PHP server page on submit.
It was suggested that I include this as a value in a hidden field in a form to post to the php page. However, since the JS variable is dynamically created by the user, I can't write to the page for inclusion in the form unless I call a function that refreshes the page. To avoid a double page refresh, I'd prefer to have the submit function both grab the data and simultaneously post it to the php script. AJAX if I understand correctly, should not be needed because I'm okay reloading the page once on submit. I just don't want to reload twice.
The following uses the function suggested by Andrew to set the js variable and post. Th form posts as I get the other hidden variable in the form but I am not getting the variable set by js, possibly because there is a mistake with the naming of the variables.
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function postData(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
window.location = "posttoserver.php?data="+options[i].value;
}
function setTheValue(val) {
var options = document.getElementById(listBoxID).options;
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<form id="myForm" action="getdata.php" method="get">
<input type="hidden" name="data" />
<input type="hidden" name="mode" value="savedit">
<button onclick="setTheValue(options)">Submit Data</button>
</form>
</body>
</html>
On the other end I have in getdata.php:
<?php
$mode = $_REQUEST['mode'];
$option = $_REQUEST['data'];
echo $mode;
echo $option;
print_r ($option);;
?>
Finally solved it days later with document.getElementById('varname').value
For newbs like me, document.getElementById does not merely retrieve data as you might think and most documentation mentions. It also sets data.
The key is to write the statement backwards and also (as you must do to retrieve a value) put id== into the element you want to set.
If you write var test = document.getElementById('text'); and you have put id="text" in some field, it will retrieve the value of text. That's what the usual documentation mentions. However, if you write:
document.getElementById('varname').value = "dog"
it will insert "dog" into the element that contains id=varname.
While that may be obvious to the more experienced, it certainly confused me.
Following code works.
<html>
<head>
<script>
function Post(data)
{
document.getElementById('varname').value = data
}
</script>
</head>
<body>
<form action = "" method="get">
<input id="varname" type="hidden" name="d">
<button onclick="Post('dog')">Post to Server</button>
</form>
</body>
</html>
You can go ahead and create a form like you normally would with an empty hidden field:
<form id="myForm" action="posttoserver.php" method="get">
<input type="hidden" name="data" />
...
<input type="submit" value="Submit" />
</form>
And you can use a JavaScript function to set the value of the hidden field:
function setTheValue(val) {
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
You can then call the function setTheValue(val) when your button is clicked or whatever.
I hope this helps!
jQuery actually makes this very simple. You have the right idea but using window.location is going to change your page. What you are looking to do is make a async request to another url while you remain on your current page.
http://api.jquery.com/jQuery.ajax/
Related
hello I'm trying to use a form to post variables from an index.html to an action_page.php then somehow get those variables from a new results.html page (is this possible to do?)
my index form looks like this
<form action="action_page.php" method="post">
<select name="race" style="width: 180px;">
<option value="White">White</option>
<option value="Asian">Asian</option> //
</select>
edit:
<p><input type="submit" value="formSubmit" name="formSubmit"></p>
</form> </p> <!-- there is a lot more code in between -->
my php looks like this
<?php
if(isset($_POST["formSubmit"]) )
{
$varRace = $_POST["race"];
echo $varRace; // this doesn't work why?
}
function redirect($url, $statusCode = 303)
{
header('location: ' .$url, true, $statusCode);
die();
}
$varRedirect = "results.html";
// call to function removed but it would call redirect($varRedirect);
?>
ultimately i'd like my results.html page to display a variable $varRace for instance.
since forms post to themselves is this possible to get ? is there a php function I could write to send the variable?
you can do that using cookies get posted data from action_page.php and set data to cookie value called race end after that inside the results.html you can get that value and print that on the results.html
and after that delete cookie(set past expire time)
# first close form tag and add input type="submit" to your form
<form action="action_page.php" method="post">
<select name="race" style="width: 180px;">
<option value="White">White</option>
<option value="Asian">Asian</option> //
</select>
<input type="submit" name="formSubmit" value="submit">>
</form>
change action_page.php
<?php
if(isset($_POST["formSubmit"]) )
{
$varRace = $_POST["race"];
setcookie("race", $varRace, time()+600);
$varRedirect = "results.html";
redirect($varRedirect);
}
function redirect($url, $statusCode = 303)
{
header('location: '.$url, true, $statusCode);
}
?>
results.html
<html>
<head>
<script type="text/javascript">
function init() {
var race = getCookie('race');
document.getElementById("test").innerHTML = race;
document.cookie = "race=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
</script>
</head>
<body onload="init()">
your race is :
<p id='test'></p>
</body>
</html>
Here's my JS code...
function da(){
var a=document.forms["user"]["age"].value;
if(this.age.value < 18 || this.age.value > 85) {
alert('some text...');
this.age.focus();
return false;
}else{
window.location.href='file.php?&'+a;
}
}
It simply passes the parameters to the page where I'm standing...
Here's the form just in case (I'm a beginner keep in mind)...
<form name="buscar" method="GET"> Some text <input onmouseover="Aj2('d');document.getElementById('box').style.display='block';" onmouseout="clean();" type="number" name="age" id="age" > Age <div id="help" ><!-- --> </div><br />
<input type="button" value="Send" onclick="da()">
</form>
The Aj2 function is not the problem here...
Thanks for any help y might get...
Just a thought, if you don't actually have to reload the page and just want to get information to your javascript code from PHP, you could do something like
<script>
<?
$phpvariable = "my variable";
?>
var jsvariable = <?php echo json_encode($phpvariable); ?>;
</script>
Now the javascript variable, jsvariable, will hold the PHP variable's content.
Some thing like this I am not a expert.
$('button name').on('click', function() {
var age_ = document.getElemenetById('age');
$.get('path of your file', {'age' : age_}, function(resp) {
// code to pass parameter
alert(age_);
});
});
<form action ="/submit-page/" method='post' class="editable">
<fieldset>
<select name="status" id='status'>
<option value="Submitted">Submitted</option>
<option value="Canceled">Canceled</option>
<option value="Application">Application</option>
</select>
<input type="submit" name="submit" value="SAVE">
</form>
I have a form above: When I click on the drop down value "Canceled" and hit the Save button I want to give alert box with a warning message with a Yes and No button.
If the user cicks on Yes, take him to the submit-page as desired in the form action parameter.
if the user clicks No, stay on the same form page without refreshing the page.
Can this be done in jQuery?
Hmm... theres is a problem with the other answers on here: they don't work against your HTML.
There's a bug in jQuery (I assume it's a bug), where if an element on your form has aname of submit, then triggering the submit event of the form will not work.
You will need to remove the name attribute from your input type="submit" button or simply give it a name other than "submit".
HTML
<form action ="/submit-page/" method='post' class="editable">
<fieldset>
<select name="status" id='status'>
<option value="Submitted">Submitted</option>
<option value="Canceled">Canceled</option>
<option value="Application">Application</option>
</select>
<input type="submit" value="SAVE" name="submit-button"/>
</fieldset>
</form>
jQuery
$('#status').on('change', function() {
var $this = $(this),
val = $this.val();
if (val === 'Canceled' && confirm("are you sure?")) {
$this.closest('form').submit();
}
});
PHP
$submitted = !empty($_POST['submit-button']);
if($submitted)
{
// Submit button was pressed.
}
else
{
// Form was submitted via alternate trigger.
}
Example
Working: http://jsfiddle.net/xixonia/KW5jp/
Not Working: http://jsfiddle.net/xixonia/KW5jp/1/
Edit
You have since updated your question, and this answer is no longer a valid solution for what you are looking for. Instead, look at Chris Platt's answer.
Edit Again
This is a modified version of Chris Platt's answer. It simply waits until the DOM is ready (elements are loaded) before it executes the logic contained within the first $(...).
$(function() { // this first jQuery object ensures that...
/// ... the code inside executes *after* the DOM is ready.
$('form.editable').submit(function(){
if ($('#status').val()=='Canceled') {
if (!confirm('Warning message here. Continue?')) {
return false;
}
}
});
});
$('form.editable').submit(function(){
if ($('#status').val()=='Canceled') {
if (!confirm('Warning message here. Continue?')) {
return false;
}
}
});
yes, it can be done:
$('#status').change(function(){
var val = $(this).val();
if( val == 'Submitted' ) {
$('.editable').submit();
return false;
} else if (val == 'Canceled')
{
var answer = confirm('are you sure');
return false;
} else {
...
}
});
This, as opposed to Chris Pratts solution will do it, as soon as you change the selected value in the dropdown box. His will do it, once you click the submit button.
The most direct method to intercept the form submission in jQuery is like this:
$("form.editable").submit(function(){
if(confirm("Really submit the form?")) {
return true;
} else {
return false; //form will not be sumitted and page will not reload
}
});
See http://jqapi.com/#p=submit for more detail.
I am posting a form in an expressionengine (1.6.8) template. I'm doing it using jquery but have tried an HTML form too - same result. The PHP superglobal $_POST is empty after posting the form, even though I have PHP enabled on my templates (on input for the template containing the form and output on the processing template) and can see the POST variables in firebug.
Can anyone suggest what might cause this?
<html>
<head>
<script type="text/javascript" src="/_scripts/jquery-1.6.1.min.js"></script>
</head>
<body>
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(e){
e.preventDefault();
var path = "/select-locale/processing"
var form = $('<form/>');
form.attr("method", "post");
form.attr("action", path);
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", 'locale');
field.attr("value", 'NZ');
form.append(field);
$('body').append(form);
form.submit();
});
});
</script>
</body>
</html>
server-side code (inherited, not my own) :
<?php
var_dump($_POST);
var_dump($_GET);exit;
if ( ! isset($_POST['locale']))
{
$locale = FALSE;
$returnPage = "/";
}
else
{
$locale = $_POST['locale'];
$returnPage = $_POST['returnPage'];
}
if (isset($_GET['locale'])) {
$locale = $_GET['locale'];
$returnPage = "/";
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"} <?php
}
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"}
{exp:session_variables:get name="testSession"}
{if '{exp:session_variables:get name="testSession"}'=='yes' }
{redirect="<?php echo $returnPage;?>"}
{if:else}
{redirect="/nocookies/"}
{/if}
check the network tab if the parameters you want are really sent out
check the url if it's correct
if you use any sort of routing mechanism or url rewrite, you might wanna review it also
check your validation and XSS rules (if any) as it may reject the whole array once hints of XSS is found.
happened to me a while ago (CI) and i was sending it to the wrong url
You might want to re-check the action attribute, are u sure you're sending the data to the right url? I doubt that anything could be filtered.
it seems like form is getting submitted twice because of either action attribute of form tag or oath value in jquery function
It may be useful
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body name="test">
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(){
var form ='<form action="/select-locale/processing" name="newform" method="POST"><input type="hidden1" name="locale" value="NZ"></form>';
$('body').append(form);
alert('added');
document.newform.submit();
});
});
</script>`
I've created an HTML form that has checkboxes that are checked dynamically due to a variable from a previous page (there is only one checkbox checked each time).
What I'd like is to echo the value of this checkbox out (to make the main title of the page so javascript alert is not adapted).
Example :
<html>
<body>
<h1>Here I'd like to echo the value of the checkbox that is checked<h1>
<form id="myform" name="myform">
<p>
<input type="checkbox" name="car" id="porsche" /> <label for="porsche">porsche</label><br />
<input type="checkbox" name="car" id="ferrari" /> <label for="ferrari">ferrari</label><br />
</p>
<script type="text/javascript">
function loopForm(form,car) {
var cbResults = 'Checkboxes: ';
var radioResults = 'Radio buttons: ';
for (var i = 0; i < form.elements.length; i++ ) {
if (form.elements[i].type == 'checkbox') {
if (form.elements[i].id == car) {
form.elements[i].checked = true ;
}
}
}
}
...
// This function will check one of the two checkboxes
loopForm(document.myform,car);
</script>
</body>
</html>
The best I can do, I'm afraid, is the following:
var inputs = document.getElementsByTagName('input');
var checkboxes = [];
for (i=0; i<inputs.length; i++){
if (inputs[i].type == 'checkbox' && inputs[i].getAttribute('checked') == 'checked'){
checkboxes.push(inputs[i].value);
}
}
document.getElementsByTagName('h1')[0].innerHTML = checkboxes;
JS Fiddle demo.
This is slightly clunky, but does, at least, use plain JavaScript; albeit it does seem to require that the checked checkboxes be marked up as following: checked="checked".
You can use jQuery to achieve this. Listen for the change() event on the checkboxes and change the text() of the h1 when this happens.