Why does firefox(haven't tested in another browser) has problems loading form values when a #; is in the addressbar?
If i have an <input type='radio' checked="checked">, the presence of this element in the addressbar may lead to the input not actually getting checked(as expected)
How can i avoid this behavior?
Example code:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr" style="min-height:100%;">
<head>
<title>stuff2test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body class="popup" >
<form action="" id="frm">
add #; to addressbar, and refresh
<?php $rnd = mt_rand(1, 4); ?>
<label for="r_v1"> <input id="r_v1" type="radio" value="v1" <?php if($rnd==1){ echo 'checked="checked"';}?> name="r"></input> checked?</label>
<label for="r_v2"> <input id="r_v2" type="radio" value="v2" <?php if($rnd==2){ echo 'checked="checked"';}?> name="r"></input> checked?</label>
<label for="r_v3"> <input id="r_v3" type="radio" value="v3" <?php if($rnd==3){ echo 'checked="checked"';}?> name="r"></input> checked?</label>
</form>
<button onClick="getElementById('frm').submit();" type="button">submit</button>
<br/>
RND: <?php echo $rnd;?>
<?php
if($rnd>0 && $rnd<=3){
echo "Checkbox {$rnd} should be checked";
}
?>
<br/>
<?php
var_dump($_GET);
?>
</body>
</html>
Edit2: cleaned the code a little, added an echo
You have links like this, right?
link
And you do something with them using JavaScript (here: jQuery too), right?
$('a').click(function() {
alert(1);
});
You need to add return false at the end of the function.
$('a').click(function() {
alert(1);
return false;
});
Edit:
After looking at your code... Do NOT use inline JavaScript!
You need some element that will do something on click? Just add class, ID - you name it... so you can distinguish between elements and then...
$('a.my_class').click(function() { // $('a#my_id')
// All you need to do.
return false; // For preventing browser to add '#' after current link (if you have 'href="#"').
});
From reading the comments on the question, the answer seems clear.
The problem is that Firefox tries to remember the state of the form when you reload the page, which includes which checkboxes are checked and which aren't. So even though you vary the default values in the HTML on reload, Firefox sees it as the same form and ignores the defaults set in the HTML in favor of what it has saved from before the reload.
I've heard you can disable this behavior by supplying the HTTP header Cache-Control: no-store, or by specifying autocomplete="off" on the form elements. But I have not tested either solution personally. Or you could use Javascript to reset the form on page load (either with the form object's reset() or by explicitly setting each field's value).
The hash (#) is a special character in a URL. Anything that comes after it is not sent to the server, so if you're using hashed URLs you really need to use POST (or an AJAX request to a non hashed URL if GET is essential) to send your form data.
An alternative is to implement something similar to Google's _escaped_fragment_ to ensure that the contents of your URL after the hash will be sent to the server.
I use that "trick" massively, and don't have problems, because I use the input type="submit" control.
If you replace the line:
<button onClick="getElementById('frm').submit();" type="button">submit</button>
with
<input type="submit" value="submit" />
solve the problem without changing the anchors and without touching the javascript code.
Good Luck!
Related
I want to make an HTML (or php maybe?) page that constructs a new HTML page based on input parameters the user gives to a drop-down box. I just don't know how you handle the input.
Here's my HTML:
<html>
<body>
<input type="number" min="1">
</body>
</html>
Yes I know it's not the full HTML page, but I just want to focus on the <input> tag. I know you probably have to set it equal to a PHP variable maybe?
I want it to generate a different HTML page that looks like this:
<html>
<body>
<p>You have chosen: $input </p>
</body>
</html>
I might be asking this all wrong, but I hope it makes sense what I'm looking for. I need to know how to handle the user input. I couldn't find a thread that discusses this. Do I need to generate a new HTML file? Or just override the current one and maybe have a reset button? I'm so confused.
In the simple case, you'll have two pages: your form and your result page. You can send data from the form page to the results page with one of two methods: GET or POST.
GET means that the data you're sending gets put in the page URL. This is useful because then you can link to a specific version of the results page, but potentially dangerous because you don't want to put sensitive data in the URL bar.
POST means that the data is sent with the HTTP request in the background. This is preferable for something like a password.
The GET and POST data can be read by nearly any server-side language and used to generate HTML on-the-fly. The example below uses PHP.
The form page doesn't necessarily need any server-side code, just basic HTML. Here's a simple example:
<!DOCTYPE html>
<html>
<form method="GET" action="my_result.php">
<input type="text" name="my_value">
<input type="submit">
</form>
</html>
Your second page (the results page) should bear the name that you specified in the form's action attribute. This is the page which will need server-side code. So here is an example my_result.php:
<!DOCTYPE html>
<html>
<p><?php echo $_GET['my_value']; ?></p>
</html>
Obviously, my_value can and should be replaced by whatever you want to call your data, as long as the name attribute of the input element matches the key in the PHP.
This example uses the GET method. You can use POST by changing the method attribute of the form and using $_POST instead of $_GET (if you are using PHP).
If you use $_REQUEST rather than $_GET or $_POST, it finds a value that was passed via either GET or POST. This is usually less safe than explicitly stating how your value was passed.
Addendum: Some servers are configured to disallow you from directly using the values of php superglobals such as $_GET, $_POST, and $_REQUEST for security purposes. That is because you really should always sanitize user input before using it in an application. The type of sanitization required depends on the type of input and how it is being used, and is well outside of the scope of this question. For this purpose, php provides the filter_input function.
The sanitization filter is an optional parameter for the filter_input function, so if you really want to use the data unfiltered, you can simply omit it (but know that this is dangerous). In this case, you can replace all instances of $_GET['my_value'] in the above code with filter_input(INPUT_GET, 'my_value').
This is not a tutorial, but I guide you to some important points:
You can get user input with html by using form element. read more about form and methods of form (GET and POST).
Then, how can you print user input when submitted by user? php supports both (GET and POST) using $_GET and $_POST with input name as key.
Dealing with user-input needs extra care because of security. user might submit malicious content that later attacks you or another user.
Try like below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if ($_POST) {
echo "<h3>You have selected ".$_POST['number']."</h3>";
} else {
echo '
<form method="post" action="">
<select name="number" id="number">
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
</select>
<input type="submit" value="submit">
</form>
';
}
?>
</body>
</html>
To handle a user input you have to use forms
<form action="action_page.php">
<input type="number" min="1 name="my-number">
<input type="submit" value="Submit">
</form>
After user set number and press submit button, you will get the value in action_page.php in $_REQUEST['my-number']
I have a simple form that posts signup info to a mailchimp account. The form and messages back from the include file work perfectly in Firefox, but nothing is happening in IE. If no email address is entered, it should come back with an error just like it does in Firefox. I have no idea how to trouble shoot this type of issue. If there is an error, it should echo back the error into a div on the form which again works perfectly in Firefox and nothing happens in IE. It makes no sense to me. I need to have this working by today. I have tried moving the files to the same location as the index.php, changed permissions, etc. with no luck. I need some major help! I can't even get this piece of code to come back in IE: if(!$_GET['email']){ return "No email address provided"; }
You can try the form at: www.terrybryan.com/index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Ajax Mailing List Sign Up System</title>
<link type="text/css" rel="stylesheet" href="css/default.css" />
</head>
<body>
<form id="signup" action="<?=$_SERVER['PHP_SELF']; ?>" method="get" style="width:250px;">
<fieldset>
<label for="email" id="email-label">Email Address</label>
<input type="text" name="email" id="email" />
<label for="zipcode" id="zipcode-label">Zip Code</label>
<input type="text" name="zipcode" id="zip" />
<label for="events" id="events-label">Receive future info from us?</label>
Yes<input type="radio" name="events" value="Yes" checked="checked" />
No<input type="radio" name="events" value="No" />
<label for="hearabout" id="hearabout-label">How did you hear about us?</label>
<select name="hearabout" id="hearabout">
<option value="Ice">Ice</option>
<option value="Radio">Radio</option>
<option value="Friend">Friend</option>
<option value="Door Hanger">Door Hanger</option>
</select>
<br /><br />
<input type="image" src="i/join.jpg" name="submit" value="Join" class="btn" alt="Join" />
<br /><br />
<div id="response">
<? require_once 'store-address.php'; if($_GET['submit']){ echo storeAddress(); } ?>
</div>
</fieldset>
</form>
<!-- Some fancy Ajax stuff to store the sign up info. If you don't want to use it, just delete it and the form will still work -->
</body>
</html>
and here is the include file that the message comes back from:
<?php
/*///////////////////////////////////////////////////////////////////////
Part of the code from the book
Building Findable Websites: Web Standards, SEO, and Beyond
by Aarron Walter (aarron#buildingfindablewebsites.com)
http://buildingfindablewebsites.com
Distrbuted under Creative Commons license
http://creativecommons.org/licenses/by-sa/3.0/us/
///////////////////////////////////////////////////////////////////////*/
require_once('MCAPI.class.php');
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('********');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "********";
// Merge variables are the names of all of the fields your mailing list accepts
// Ex: first name is by default FNAME
// You can define the names of each merge variable in Lists > click the desired list > list settings > Merge tags for personalization
// Pass merge values to the API in an array as follows
$mergeVars = array('ZIPCODE'=>$_GET['zipcode'],
'EVENTS'=>$_GET['events'],
'HEARABOUT'=>$_GET['hearabout']);
if($api->listSubscribe($list_id, $_GET['email'], $mergeVars) === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
//if($_GET['ajax']){ echo storeAddress(); }
?>
Does anyone have any idea why this simple form would not work in IE like it does in Firefox and other browsers?
Thanks,
T Bryan
Here's why: When using an image button in IE, when you click it, instead of sending $_POST['nameofbutton'], it sends $_POST['nameofbutton_x'] and $_POST['nameofbutton_y']. Now, Firefox sends both $_POST['nameofbutton_x'] and $_POST['nameofbutton_y'] as well as $_POST['nameofbutton']. The _x and _y values store the x and y coordinates of where you clicked on the image button, so you can do different things depending on where the user clicked for doing something like an image map.
So, when you test for if($_GET['submit']){ echo storeAddress(); } ?> you don't get it on IE because IE doesn't have $_GET['submit'] it has $_GET['submit_x'] and $_GET['submit_y'], so you must test for $_GET['submit_x'] or y.
Least I think the format was _x and _y, might be slightly different. Easy way to tell is to print_r($_GET);
Oh, also, by the way, be careful using Get for forms, particularly if they have to transfer a lot of potentially long information, IE has like a 255 character limit in the address bar and anything after that will get cut off and left out of $_GET or malformed. Best to use Post for forms. Get is only really good for things like structuring links for a CMS controller or registration email verification links and all that.
I suggest editing your html code for submit:
From:
<input type="image" src="i/join.jpg" name="submit" value="Join" class="btn" alt="Join" />
To:
<input type="submit" name="submit" value="Join" class="btn" alt="Join" />
type submit is generally reliable, other types (including, sadly, , image submits, etc) are often implemented differently in different browsers. Another thing not to rely on is the contents of submit, since ie in some cases submits html instead of the value (generally with things other than the standard submit value), or submit multiple forms on the page, annoying things like that.
So in general, it is best to go with a simple <input type='submit' ...etc, and go with a simple check for the -presence- of the submit and don't be too specific about what the submit contains.
I would suggest a very simple approach, style your button using CSS, or do <img src="path/to/your/image" alt="my image button" />
Since PHP runs on the server, it should (generally) provide the same response to the browser for the same input. Since the form uses the "get" method, the input is entirely specified by the URL (plus headers, including cookies, though those don't appear to factor in here).
In any case, when you submit the form from Firefox, you should see that the URL of the form submission appears in the Firefox address bar. If the PHP script issues a redirect as a response, then the URL may only appear very briefly. Either way, it should be available in your browser history.
If you can copy that URL into the address bar of IE and submit the same request from IE (again, assuming cookies aren't involved), then you should get pretty much the same response from the server. If you're not seeing the same thing in the browser window of IE as you do in Firefox, there may be several reasons.
View the source. (View -> View Source). If it's completely blank, the script probably failed to execute properly.
If you have access to the server error logs, check for an error message related to your request. A sane PHP implementation (in cooperation with a sane server) will provide error logging. Sometimes this is really the only way to know what's going on with your script. If you have access to the web server through an FTP account, you will probably find the logs at or near the top level.
If you don't have access to the server, you can still get a low-level view of what's happening with your request through the use of Firebug Lite or Fiddler2.
I'm using a PHP sticky form and was wondering is there a way I can clear a forms fields once its been submitted by the user?
A sticky form is simply a standard HTML form that remembers how you filled it out. This is a particularly nice feature for end users, especially if you are requiring them to resubmit a form (for instance, after filling it out incorrectly in the first place).
You could have some default values and update the fields to the values using Javascript , in case you do not want to reload the page. If you do want to reload the page, and use PHP sticky form, populate the form after clearing out the GET values.
If you want it to clear the data, you can do this:
<html>
<head>
<title>A Self-Clearing Form</title>
<script>
function clearForms()
{
var i;
for (i = 0; (i < document.forms.length); i++) {
document.forms[i].reset();
}
}
</script>
</head>
<body onLoad="clearForms()" onUnload="clearForms()">
<h1>A Self-Clearing Form</h1>
<form method="post" action="page2.php" name="test">
<input name="field1"/> Field One
<p>
<input name="field2" type="radio" value="One"/>One
<input name="field2" type="radio" value="Two"/>Two
<input name="field2" type="radio" value="Three"/>Three
<input name="field2" type="radio" value="Four"/>Four
<p>
<input type="submit" value="Submit Form Data"/>
</form>
</body>
</html>
This will clear the form when the HTML body loads completely.
It depends on your implementation, but the solution probably involves clearing the session variables that are used to hold the form data. If you're using a cut and paste solution I would suggest reading the documentation further or maybe looking over the code in detail to see how everything is stored.
If you want to check the session variables to see if the form data is in there you can use:
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
die; // this line is optional
I was wondering if my code below is even correct, I've been having numerous errors with this, but am not sure if the problem really exists here. The code is below:
The user will click 'Exit Group'.
<p class="logout"><a id="exit" name="logout" href="#">Exit Group</a></p>
The code that should be execute when 'Exit Group' is clicked is below:
if(isset($_GET['logout'])){
//CODE TO BE EXECUTED
}
However, the code I am trying to execute when the user clicks 'Exit Group' is not even being executed. There is nothing wrong with the code within the braces, as numerous people have checked it. But I was wondering if my problem may lie in the code above? Thank you.
If you click the link, nothing happens because the URL only contains the fragment identifier #. Not even a GET request will be issued.
You use this kind of link normally to jump to an element inside the page (e.g. Top to jump to an element with ID top). This is completely handled in the browser.
And if you only put the fragment identifier there, just nothing will happen. This is very often used if the link should execute some JavaScript and should actually not link to something else.
You are testing the $_POST array at the server side. But this array only contains elements, if you initiate a POST request by a form. That means you need to create a form with a submit button, e.g.:
<form action="" method="POST">
<input type="submit" name="logout" value="Exit Group" />
</form>
Here comes the name attribute into play, which will be the key in the $_POST array. But assigning this on a normal link will have no effect.
You could do it also with the link, but with a GET request this way:
<a id="exit" href="?logout=1">Exit Group</a>
<!-- ^-- parameter must be part of the URL, name has no effect -->
and
if(isset($_GET['logout'])){
//CODE TO BE EXECUTED
}
Note that you have to pass a parameter logout it here.
It seems you have mixed up GET and POST requests. If you have a form, the name s of the form elements will be transmitted as parameters to the server. That means given this form:
<form method="POST">
<input type="text" name="foo" value="" />
<input type="text" name="bar" value="" />
<input type="submit" name="send" value="Send" />
</form>
if the user clicks on the submit button, the $_POST array at the server side will have the keys:
$_POST['foo']
$_POST['bar']
$_POST['send']
This does not work with links though. A click on a link will create a normal GET request, and here, the parameters must be part of the URL, appended after a question mark ? and separated by an ampersand &:
Link
will result in
$_GET['foo']
$_GET['bar']
$_GET['andMore']
You probably should read about the HTTP protocol.
a isnt a form control. it needs to be an input or select if it's within a form.
For manual linking, do href="/page?logout"
You're using a regular hyperlink, no form will get posted. you need a submit button of some kind in a form with method="post" to do that. regular links just result in GET requests and nothing will ever be posted that way.
edit: added simple example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Form test</title>
</head>
<body>
<?if ($_SERVER['REQUEST_METHOD'] == 'POST'):?>
<pre><? print_r($_POST)?></pre>
<?endif;?>
<? // $_SERVER['REQUEST_URI'] holds the current URL, so we know that ?>
<? // we'll end up back in this file when the form is submitted. ?>
<form method="post" action="<?= $_SERVER['REQUEST_URI']; ?>">
<input type="text" name="textbox"
value="<?= isset($_POST['textbox'])?$_POST['textbox']:'Type something' ?>" />
<input type="submit" name="submitbutton" value="Submit" />
</form>
</body>
</html>
$_POST will only be filled if you use a form with method=post.
Yes. A POST and a GET are two different things ;)
if(isset($_GET['logout']))
This <a id="exit" name="logout" href="#"> should be <a id="exit" href="?logoff=true#">.
Then logoff will be in the $_GET array.
How do you use a value "submitted" by a form in javascript?
Facts:
It is a PHP document
I'm using JavaScript because I need some timing factors I don't think I can get from serverside-scripts :)
To simplify; what I want is, that when this form is submitted or a button is clicked:
<form method="POST" action="test.php">
<input type="text" name="foo" size="30">
<input type="submit" value="Click me"> //it doesn't have to be submitted
<input type="button" action="some_action" value="Click me"> //an alternative solution
</form>
the value of the text-input named "foo" is displayed elsewhere.
NOTE The form doesn't have to be submitted, what I realy want is, that when you press a button the value can be used elsewhere
Should I use GET instead? Can I just use the $_POST array? Should I use AJAX (which I am completely useless at)? I don't know what to do in this situation.
Since you mentioned that it does not depend fully upon whether the form is submitted or not, so it's more easier to catch the value w/o POSTing / GETing the form. After you have written your interface logic in the body section, you need to write the following code in the footer page at the end:-
anypage.php:-
<form method="POST" action="test.php">
<input type="text" name="foo" id="foo" size="30" />
<input type="submit" onclick="return writeFoo('foo_placeholder', 'foo');" value="Click me" /> //it doesn't have to be submitted
<input type="button" onclick="return writeFoo('foo_placeholder', 'foo');" action="some_action" value="Click me" /> //an alternative solution
</form>
The above code is your code only with some minor modifications, including calling a JS function "writeFoo()" on the "click" event of either a button / submit. This function takes 2 arguments:-
arg - It mentions the destination placeholder ID of the HTML element, in which the value is to be printed.
source - It mentions the source ID of the HTML element, from which the value is to be grabbed / taken.
rightpart.php:-
<div>
<span id="foo_placeholder"></span>
</div>
The above HTML code can be used for any panel, but must be included when the "anypage.php" page is to be shown to the user. This is because the placeholder element must be present when the "foo" element is being called. Be careful to use the same ID both in the "writeFoo()" function calling time & in this page.
footer.php:-
<script type="text/javascript"><!--
function writeFoo(arg, source) {
if(document.getElementById(arg) != null) {
document.getElementById(arg).innerHTML = document.getElementById(source).value;
}
}
// --></script>
And this page should contain the above JS code containing the definition of the "writeFoo()" function.
EDIT, as for #Latze:-
See you can include that "rightpart.php" page either in the same block of "anypage.php" page or in any block of any other page (like "header.php" / "footer.php" page). But the main logic is that both the source ID (from which the value is taken) & the target / placeholder ID (where the value is to be shown) must be present when you are viewing that particular page (in this case, it means when you are viewing the "anypage.php" page).
Hope it helps.
You can read the value from the $_POST or $_REQUEST array on the server side, and insert it into the output anywhere you like - even inside javascript, if you want to. Example:
<?php
$myValue = $_POST['foo'];
?>
<script type="text/javascript"><!--
function writeMyValue() { document.write('<?php echo $myValue; ?>'); }
// --></script>
PHP runs on the server. JavaScript runs on the browser. These two languages do not talk to each other; they don't even run at the same time, not to mention on the same machine. As soon as the user submits the form, the browser requests test.php from the server and the current page is gone forever, scripts and all.
It's really hard to figure out what you want to do exactly, so I'll provide you with some general hints:
JavaScript can intercept a form submission. You need to attach an onsubmit event handler to the <form> element. The function assigned to the event can do whatever it needs and then return true (and let the submission go on) or return false (and cancel the submission).
JavaScript can read and write almost any page element. You need to use the so called DOM methods.
PHP can generate whatever you need, including HTML input fields.
Example:
<?php
$foo_value = date('Y-m-d H:i:s');
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript"><!--
window.onload = function(){
var documentForms = document.getElementsByTagName("form");
for(var i=0, len=documentForms.length; i<len; i++){
documentForms[i].onsubmit = function(e){
var currentForm = e.target;
var fooValue = currentForm.elements.foo.value;
var p = document.createElement("p");
p.appendChild(document.createTextNode("Aborted submission: " + fooValue));
currentForm.appendChild(p);
return false;
};
}
};
//--></script>
</head>
<body>
<form method="POST" action="test.php">
<input type="text" name="foo" value="<?php echo htmlspecialchars($foo_value) ?>" size="30">
<input type="submit" value="Tryk her">
</form>
</body>
</html>
Update
A little note about this:
documentForms[i].onsubmit = function(e){
};
When you assign an event handler, the spec requires that whenever the function gets called it will receive an event object as its first argument. That object represents the event that triggered the function call and it can be used to obtain additional information, such as the original DOM node that triggered the event. It doesn't matter how you call it inside your function; I use e because I never know how to name stuff :)