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>
Related
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_);
});
});
I'm not very experienced at JS (PHP is my strong side) so I need your help about something.
I have a script with 2 drop down menus that shows hidden content. I'm using this example Change content based on select dropdown id in jquery
When I execute a PHP script, it checks for errors and if there are some it will return the user to the form. The problem with this is that it will not show the hidden content. I can set some sort of PHP vars and put them in the input like $selected_one = 'selected="selected"' and the dropdown menus will have the right selection, but the jQuery function does not work like that. I think it puts some sort of class that shows and hides the content.
I can't quite put my finger on what's going on, so I need your help. Can any body give me a hint how to fix this?
Here's some code to make things visual
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<style>
.list_publish, .list_news, option_value {
display: none;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<?php
$selected_news = '';
$selected_review = '';
$selected_news_text = '';
$selected_news_video = '';
if(isset($_POST['submit_news_text'])){
$selected_news = 'selected="selected"';
$selected_news_text = 'selected="selected"';
$news_title = $_POST['news_title'];
// Checks blank forms and return error
if(empty($news_title)) {
$error_message = 'This field must not be empty!';
$proceed = false;
} else {
$proceed = true;
}
}
if($proceed){
// do stuff
echo 'do stuff';
} else {
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<select class="change_publish" name="publish_type" id="publish_type" style="width: 238px;">
<option value="publish_type" data-title="choose">Publishing...</option>
<option value="publish_news" data-title="news" <?php echo $selected_news ?>>Publish News</option>
<option value="publish_review" data-title="review" <?php echo $selected_review ?>>Publish Review</option>
</select>
<div class="list_publish publish_type">
</div>
<div class="list_publish publish_news">
<select class="change_news" name="news_type" id="news_type" style="width: 238px;">
<option value="news_type" selected="selected" data-title="choose">News Type</option>
<option value="news_text" data-title="text" <?php echo $selected_news_text; ?>>Text</option>
<option value="news_video" data-title="video"<?php echo $selected_news_video; ?>>Video</option>
</select>
<div class="list_news news_type">
</div>
<div class="list_news news_text">
<input name="news_title" type="text" id="news_title">
<input name="submit_news_text" type="submit" value="Publish" id="submit_news_text" />
</div>
<div class="list_news news_video">
> This function is not available at the moment.
</div>
</div>
<div class="list_publish publish_review">
> This function is not available at the moment.
</div>
</form>
<?php
echo $error_message;
}
?>
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
</script>
</body>
</html>
And here's a demo http://www.demirevdesign.com/public/form.php
Trigger the change event on document load, like here:
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
</script>
Im using the following (seemingly common) method to save scroll position on submit in a php page:
<script type="text/javascript">
<!-- script for scroll position on submit -->
function saveScrollPositions(theForm) {
if(theForm) {
var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
var scrollx = typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement.scrollLeft;
theForm.scrollx.value = scrollx;
theForm.scrolly.value = scrolly;
}
}
</script>
</head>
<body>
<form id="ReportForm<?php echo $userNumber; ?>" name="ReportForm" method="POST" action="<?php echo $editFormAction; ?>" onsubmit="return saveScrollPositions(this);">
<input type="hidden" name="scrollx" id="scrollx" value="0" />
<input type="hidden" name="scrolly" id="scrolly" value="0" />
-- various form controls here --
</form>
<?php
$scrollx = 0;
$scrolly = 0;
if(!empty($_REQUEST['scrollx'])) {
$scrollx = $_REQUEST['scrollx'];
}
if(!empty($_REQUEST['scrolly'])) {
$scrolly = $_REQUEST['scrolly'];
}
?>
<script type="text/javascript">
window.scrollTo(<?php echo "$scrollx" ?>, <?php echo "$scrolly" ?>);
</script>
</body>
In the body the form is wrapped by a repeat region to get multiple reports from a database, but each form in the loaded page at runtime needs a unique id, so in the form tag i have:
id="reportForm<?php echo $userNumber ?>"
which causes the saveScrollPositions to fail. Removing the userNumber that is tacked on to the end works. Any idea how i can fix this?
I very much appreciate any help you can offer on this and thank you in anticipation.
Kind regards,
John
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/
I want to post some values from a simple HTML form, validate them with an ajax call and if successful submit to a PHP script and redirect to that script. I have got the ajax part set up, just not sure how to post and redirect (as if you would on a standard form submit without ajax).
Here's what I have:
HTML:
<div id=audiencesearch>
<h1>Audience Search</h1>
<form id="audiencesearchform">
<p>Passion Point</p>
<select id="passionselect">
<option selected="selected">Please select</option>
<option>3D</option>
<option>Music</option>
<option>Playstation</option>
</select>
<p>Gender Bias</p>
<select id="genderselect">
<option selected="selected">Please select</option>
<option>Male</option>
<option>Female</option>
</select>
<p>Sort Group By Age Range</p>
<select id="ageselect">
<option selected="selected">Please select</option>
<option>Under 21</option>
<option>21 - 30</option>
<option>31 - 40</option>
<option>41 - 50</option>
</select>
<br/>
<br/>
<input onClick="ajaxaudiencesearch()" class="submitaudiencesearch" value="Search" type="button"/>
Ajax Call:
<script type="text/javascript">
function ajaxaudiencesearch(){
var passionpoint = $("select#passionselect").val();
var genderbias = $("select#genderselect").val();
var agerange = $("select#ageselect").val();
var passedstring = 'passion='+ passionpoint + '&gender=' + genderbias + '&age=' + agerange;
$.ajax({
type: "POST",
url: "processaudiencesearch.php",
data: passedstring,
success:function(retval){
if (retval == 'oktoprocess'){
audiencesearchprocess();
} else {
audiencesearcherror();
}
}
})
}
function audiencesearcherror(){
$('#audienceerror').html('GOTTA SELECT EM ALL');
}
function audiencesearchprocess(){
window.location.href = "searchresults.php";
//THIS IS WHERE I WANT TO POST AND MOVE TO SEARCHRESULTS.PHP
}
</script>
PHP to handle Ajax:
<?php
include('sonymysqlconnect.php');
session_start();
$nullselection = "Please select";
//get the posted values
$postedpassion = ($_POST['passion']);
$postedgender = ($_POST['gender']);
$postedage = ($_POST['age']);
if (($postedpassion != $nullselection ) && ($postedgender != $nullselection ) && ($postedage != $nullselection)){
echo 'oktoprocess';
} else {
echo 'error';
}
?>
Preferably I could achieve this using jQuery. I'm sure it's extremely simple but I'm not sure how to do it?!
It's worth mentioning that this is all set up correctly. I have used PHP includes.
Thanks in advance...
Why not add action and method attributes to your form and then submit it with .submit()?
With plain html / php it is not even really a true redirect, its just the url value in "action" that can be found in the form element
<form action="/someUrl/someAction" method="POST">
...
</form>
If you're doing it with ajax (jquery), you'd say:
$.ajax({
url: '/someUrl/someAction',
type: 'POST',
data: {
argName1: 'argVal1',
argName2: 'argVal2'
},
success: function( response ) {
// keep in mind that response is usually in json...
// which means you'd be accessing
// the data in object notation: response.data.someVal
if(response == 'whatYouWanted') {
//do something... like redirect?
window.location = '/new/page';
}
});