I looked over stack for an answer with no success. Im looking to make a form with radio buttons. Depending on the radio buttons that are checked, pressing the submit button will direct you to a different page. Right now im using php with the get option. However the best im able to do is make dynamic pages based of the get info. Any help would be great
Thanks
In your PHP you could check $_GET['radio_option'] and based on the value redirect to other pages using header function, something like this:
switch($_GET['radio_option']) {
case 'val1':
header('location: page1.php');
exit;
case 'val2':
header('location: page2.php');
exit;
case 'val3':
header('location: page3.php');
exit;
}
//here handle everything else - although normally you shouldn't get here
The other alternative would be to use javascript to set the action attribute of the form before it is submitted. For example:
$(document).ready(function() {
$("input:radio[name=your_radio_naem]").click(function() {
var value = $(this).val();
var target = "main.php";
if(value == 'val1')
target = "page1.php";
else if(value == 'val2')
target = "page2.php";
else if(value == 'val3')
target = "page3.php";
$('#myform').attr('action', target);
});
});
Another way would be to set each radio button with a value of the redirect page.
$page=$_GET['radio_buttons'];
header('location: $page');
Related
How can I check if a checkbox is checked without submitting the form first?
I want to make a check out page and there is a billing adress form and a shipping adress form. I want the shipping adress form to disappear when I check a box that says "Shipping address is the same as my billing address". I want to do this without reloading the page. Is this possible? If yes, how? And if no, is there a different way i can get the same result using php?
Thanks in advance!!
You can achieve this with jquery base on your question, but it not actually php you really need but jquery.
Jquery prop
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
$("#result").html("Checkbox is checked.");
}
else if($(this).prop("checked") == false){
$("#result").html("Checkbox is unchecked.");
}
});
});
You also you jquery selector
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).is(":checked")){
$("#result").html("Checkbox is checked.");
}
else if($(this).is(":not(:checked)")){
$("#result").html("Checkbox is unchecked.");
}
});
});
Without submitting the form means a front-end validation.
On your trigger, try to use this:
document.getElementById("your-id").checked
Example:
function formTrigger()
{
let checkBox = document.getElementById("myCheck");
if (checkBox.checked == true){
console.log("it's checked.");
}
}
I want to redirect to a page after executing a php function and also submit a html form with the methode POST, at once.
I found many solutions with GET but I want to handle this with POST.
You can use cUrl to send POST data you want, then make the redirect.
Look on the net for: "php curl".
Make your form action point to the php document where you want to execute your function and then in the end place this header("location: your_location_file.php");
Step one - submit form to functions.php
Step two - do what ever you need to do with the submited data
Step three - Redirect
Example:
<form method="post" action="functions.php">
...
</form>
functions.php
<?php
...
all your code
...
header("location: your_location_file.php");
?>
Javascript can help if you don't want to rely on curl. Had this laying around. Pass in $_POST or an array of the data you want posted. Add error/parameter checking.
function http_post_redirect($url='', $data=array(), $doc=true) {
$data = json_encode($data);
if($doc) { echo "<html><head></head><body>"; }
echo "
<script type='text/javascript'>
var data = eval('(' + '$data' + ')');
var jsForm = document.createElement('form');
jsForm.method = 'post';
jsForm.action = '$url';
for (var name in data) {
var jsInput = document.createElement('input');
jsInput.setAttribute('type', 'hidden');
jsInput.setAttribute('name', name);
jsInput.setAttribute('value', data[name]);
jsForm.appendChild(jsInput);
}
document.body.appendChild(jsForm);
jsForm.submit();
</script>";
if($doc) { echo "</body></html>"; }
exit;
}
You could use a session to hold the POST data.
I am currently using code like below. On my first page load, the $_POST data is checked. If it contains certain values already in the database, then it redirects to a page for those values.
// This could be part of the same script as below, or a different script.
session_start();
if($_POST['my_value'] && valueExistsInMyDb($_POST['my_value']) ) { // check my db to see if this is an existing value
$id = getIdOfMyValue($_POST['my_value']); // e.g. '4'
$_SESSION['POST'] = $_POST; // take ALL post data and save it in the session variable
header("location: your.php?myvalue=" . $id); // redirect to bookmarkable target page where $_GET variable matches what was posted.
exit(); // ensure no other code is executed in this script after header is issued.
}
Then your other file (or maybe even the same file) could do this:
// your.php?myvalue=4
if(isset($_SESSION) && array_key_exists('POST',$_SESSION)) {
$_POST = $_SESSION['POST']; // creates or overwrites your $_POST array with data from the session. The rest of your script won't be able to tell that it's not a real $_POST, which may or may not be what you want.
unset($_SESSION['POST']); // you probably want to remove the data from the session.
}
// now your myvalue=4 is stored in GET, and you can handle the rest of the POST data as you like
I don't know if that is the best solution, but so far it seems to be working for me so far. I only just wrote the code a few days ago and haven't tested all aspects yet.
Another option is to use HTML5 to change the address bar. No redirect needed. But the downside is that only "modern Webkit browsers" can use it, apparently.
I have a column that has a button that when pressed, links to a URL set in PHP. I want to add a checkbox next to that button so that if it's checked when a user presses the button, it will take them to an alternate url. The PHP code setting the url:
<?php
$link = 'http://www.example.com';
?>
I realize that the code needs to be in javascript, which I don't know. I know only a tiny bit of php, so any help would be apprciated.
To clarify: (and of course I know this code will never work)
What I want to do is this:
<?php
If (checkbox is checked) {
$link = 'http://www.google.com';
} else {
$link = 'http://www.example.com';
}
?>
There is probably another way to do what you want to achieve. The value of the checkbox should be sent to a single php script on the server with the rest of the form's fields' values. Then you can use the checkbox's value (boolean) in php and do what you need to do accordingly, possibly requiring external scripts.
Checkbox value is not sent to server with form submit if it is not checked.
So, you can use something like this:
<?php
if (isset($_POST['checkbox_name'])) {
$link = 'http://www.google.com';
}else{
$link = 'http://www.example.com';
}
?>
Include the jQuery from Google:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
Then write the redirect function which you call after clicking the button;
<script>
function foo() {
if ($('#checkbox').is(':checked')) {
//redirect to google.com
window.location = "http://www.google.com/";
} else {
window.location = "http://www.example.com/"
}
}
</script>
And finaly your button should look like this:
<button onclick="foo();" >Your button</button>
This code assumes your checkbox has an id "checkbox".
Also, I don't think that what you're trying to do should be done with PHP - so you should learn Javascript/jQuery straight away instead of writing code the way it shouldn't be written.
Example: http://jsfiddle.net/5bdae/
Using jQuery this is fairly simple. You bind a function to the link, this function works out whether the checkbox is checked, if it is it links to one place, otherwise it links to another.
For an HTML structure like this:
<input id='myCheckbox' type="checkbox" name="box" value="box" />
<a href='#' id='myLink'>My Link</a>
The jQuery would be:
$('#myLink').click(function(event){
event.preventDefault();
if ($('#myCheckbox').is(':checked')){
window.location.href='http://www.example.com';
} else {
window.location.href='http://www.ask.com';
}
});
This could would go outside of the PHP tags, and you would need to include jQuery in your code.
I have a form on my page with a dropdown of counties. I want to somehow, with jQuery or PHP say that if a certain county is selected then redirect otherwise process the form.
I've created a fiddle to try and explain...
http://jsfiddle.net/KVjAc/
Just submit the form and use a php header command for the values you want to redirect. That would be the first thing to check in the form processor script.
No need for javascript unless you are using ajax to refresh parts of the page based on the selection.
I hope this helps(if you need a javascript/jquery solution),
$('#selectbox_ID').change( function() {
if($(this).val() == "your country"){
}
});
Do something like:
$(document).ready(function () {
$('#county').on('change', function () {
var value = $(this).val();
if (value == 'cheshire' || value == 'city of london' || value == 'durham') {
window.location.href = 'http://www.google.com/';
}
})
});
EDIT: Also, you need to add values to your option elements: <option value="cheshire">Cheshire</option>
I have 2 pages :
page1.php :
- has a form with text box and a "submit" button. Eg : <form name="frm_register" action="page1.php" method="post">
- php and mysql code to store the value of textbox to database. Javascript will redirect the page to php2.php after the value is submitted to database. Eg :
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query, $connection);
echo '<script language="javascript">window.location="page2.php";</script>';
page2.php
- mysql retrieve the data from database and display on this page.
Problem : When I press "back" button, the browser will pop up a warning message saying that the form will be resubmit. How to prevent resubmit the form when click "back" button? Is it I need to clear the cache of page1.php? How to do it with php or javascript or ajax?
Update 1 : Thanks for the answer of replacing javascript window.location="page2.php" to php header('Location: home2.php');. It fix 80% of problem. The rest of 20% problem show below :
if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
if (($username != "") AND ($username != $_SESSION[username])){
$_SESSION['servertime'] = $servertime;
$_SESSION['username'] = $username;
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query20, $connection);
header('Location: page2.php');
exit;
} else {
echo "same name"; //problem here
}
}else{
echo "submit multiple data too fast"; //problem here too.
}
}
The problem happen when do the following steps :
1) User submit data successfully, jump to page2.php view records.
2) User click "back" button, jump back to page1.php.
3) User submit data fail, stay on page1.php. (because too fast or same name)
4) User submit data successful, jump to page2.php view records.
5) User click "back" button, but browser shows warning message "form will be resubmited".
The problem is because of Step 3. Step 3 didn't run header('Location: page2.php');, didn't jump to page2.php. So it cause Step 5 show the warning message. How to fix this problem?
Update 2 : I have figured out the solution to fix the 20% problem, it works perfectly. I use session['error123'] to decide whether or not want to display the error message "same name". I kill session['error123'] if success submit data to database or if success jump to page2.php. I also use header('Location: page1.php'); to redirect to own page (same page) to make the page forget about form submission previously. Example of codes :
if ($_SESSION['error123'] == "toofast"){
echo $_SESSION['error123'] ;
}elseif ($_SESSION['error123'] == "samename"){
echo $_SESSION['error123'] ;
}
if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
if (($username != "") AND ($username != $_SESSION['username'])){
$_SESSION['username'] = $username;
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query20, $connection);
$_SESSION['error123'] = "aa";
header('Location: http://localhost/plekz/page2.php');
exit;
} else {
$_SESSION['error123'] = "samename";
header('Location: http://localhost/plekz/page1.php');
exit;
}
}else{
$_SESSION['error123'] = "toofast";
header('Location: http://localhost/plekz/page1.php');
exit;
}
}
}
Note : You need to buffer the output by <?php ob_start();?> because $_SESSION cannot put before header(). Buffer will stop all output including session, let header() send the output first.
Rather than
echo '<script language="javascript">window.location="page2.php";</script>';
you should use the header() function to redirect your user after the submission.
So in psuedo code,
click submit on page.php action page1.php
page1.php submits data to database calls
header('Location: http://example.com/page2.php');
This should prevent your clicking back problem
You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern).
Could be just a one-line if you've got the http_redirect function:
http_redirect("page2.php");
Instead of your javascript echo.
If not, that are two lines:
header("Location: http://example.com/page2.php");
exit;
Replace example.com with site's your hostname.
Related: Back button re-submit form data ($_POST); I am confused about PHP Post/Redirect/Get
One way is to submit the Formdata via Ajax to a remote Script and if the Query returns success you can jump the a "Thank You" Page.
So the User can hit the Back Button and the "Reload" Request doesn't pop up.
Hope the Idea helps you
Can you do it via an Ajax call instead? No action on the form, and the submit will call a the Ajax function. The Ajax call will execute the query, and provide a response (you can just echo a result), and you can then provide dynamic feedback based on the result. You'd never leave the page.
<form id="thisForm">
...form input fields...
<input type="button" onclick="return submitForm('thisForm')"/>
</form>
function submitForm(formId) {
$.ajax( {
type: "post",
url: 'page2.php',
data: $('#' + formId + ' input').serialize(),
... any other Ajax parameters...,
success: function(data) {
}
});
return false;
}
Add this code in the page that is showing as offline when the user clicks the back button:
<?php
session_start();
header_remove("Expires");
header_remove("Cache-Control");
header_remove("Pragma");
header_remove("Last-Modified");
?>
Create a Session like shown here
You should use session and validate the user from every page and you will amaze how SESSION works! AMAZING!