Setting PHP cookie from dropdown menu - php

I have a PHP script designed to allow users to decide which language a page is displayed in. The information is stored in a cookie and then read when needed to display the correct content.
Currently, I use an HTML dropdown box to allow the user to select the language and then they must press the form submit button to set the cookie. How can I make it so when they select the language in the dropdown menu it automatically selects that and submits the form? I hope you can understand my question.
My current PHP code is:
<?php
$user_lang = null;
if (isset($_POST["setc"])) {
$expire = time() + 60 * 60 * 24 * 30;
setcookie("mycookie", $_POST["sel"], $expire);
header("location: " . $_SERVER["PHP_SELF"]);
} else if (isset($_COOKIE["mycookie"])) {
$user_lang = $_COOKIE["mycookie"];
}
?>
<meta charset='utf-8'>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<select name="sel" size="1">
<option value="en"<?php echo (!is_null($user_lang) && $user_lang === "en" ? " selected" : ""); ?>>English</option>
<option value="es"<?php echo (!is_null($user_lang) && $user_lang === "es" ? " selected" : ""); ?>>Español</option>
<option value="fr"<?php echo (!is_null($user_lang) && $user_lang === "fr" ? " selected" : ""); ?>>Français</option>
<option value="de"<?php echo (!is_null($user_lang) && $user_lang === "de" ? " selected" : ""); ?>>Deutsch</option>
</select>
<input name="setc" value="save setting" type="submit">
</form>

Change your select tag to:
<select name="sel" size="1" onchange="this.form.submit();">
to make the form submit when users selects a language.
If you wish to do that without JavaScript you can use multiple submit buttons method instead:
<input name="set_language[en]" value="English" type="submit">
<input name="set_language[es]" value="Español" type="submit">
<input name="set_language[fr]" value="Français" type="submit">
<input name="set_language[de]" value="Deutsch" type="submit">
Processing this form is simple as it is:
if (isset($_POST["set_language"])) {
$language = key($_POST["set_language"]);
// $language contains user-selected language code now
}
This can't be done with a select field but without JavaScript or any other client-side scripting language.

You need to do it using JavaScript:
<select name="sel" size="1" onchange="this.form.submit();">
Or if you use jQuery:
$("select[name='sel']").change(function() {
$(this).parent().submit();
});
This will submit the form whenever a user changes value in the dropdown list.

You can add an onchange event to the select:
<select onChange="document.forms[0].submit();">
Remember that it's a good thing to leave the submit button for those users who don't have javascript enabled. You can hide the button using javascript, so it won't clutter the window of those that doe have a regular browser.

I think you have to use javascript like the others said, but you can also use the submit button as a backup if the user doesn't have javascript activated:
<noscript><input value="save setting" type="submit"></noscript>
And then, since the submit button will only be shown when the user has javascript disabled, you will need to add a hidden input to check if the form has been submitted on the server side
<input type="hidden" name="setc" value="true" />

The answer is in JavaScript not PHP. You could do it unobtrusively with JavaScript like this:
<script>
window.onload = function() {
document.getElementById("idOfDropDown").addEventListener("change", function() {
document.forms["formName"].submit();
});
}
</script>

Related

Popup on if statement in php

I have a html form which looks like this:
<form action="submitOrder.php" method="get">
<select name="orderForm">
<?php
echo '<option value=" "> </option>';
while($row = \mssql_fetch_array($employeeOrderResult))
{
echo '<option value="'.$row[EMPLOYEE].'">'.$row[EMPLOYEE].'</option>';
}
?>
<option value="Gæst">Gæst</option>
<option value="Praktikant-01">Praktikant-01</option>
<option value="Praktikant-02">Praktikant-02</option>
<option value="Praktikant-03">Praktikant-03</option>
</select>
<br>
Vare: <input type ="text" name="varenr"><br>
Antal: <input type="text" name="antal"><br>
<input type="submit" value="Bestil">
</form>
It fetches som data from a database and adds some special guests.
Now, when it confirms it redirects to a page which has this code in it:
<?php
$ofAntal = $_GET['antal'];
$ofMedarbejder = $_GET['orderForm'];
$ofDato = date('Y-m-d H:i:s');
$ofVareNr = $_GET['varenr'];
$sql = "INSERT INTO Bestillinger(bestillingsAntal,medarbejder,dato,vareNr) VALUES('$ofAntal','$ofMedarbejder','$ofDato','$ofVareNr')";
$validation = mysql_query($sql, $MySQLcon);
if(!$validation)
{
die('Couldnt enter data ' . mysql_error());
}
echo 'Entered data succesfully';
?>
Now, I need a confirmation popup of some kind, if the amount (ofAntal) is above 1, and Ive looked into several solutions. The problem is i started working with PHP tuesday morning, and i cant find a solution that works for me.
All it has to do, is submit the data is yes is clicked, and cancel it if the user clicks no/cancel. This is ofc done in an IF statement, thats not the issue, the issue is how to implement it properly.
ANY help is highly appreciated :)
Use javascript confirm box on onclick attribute for submit button. It will give you yes and cancel options.
<input type="submit" value="Bestil" onclick="confirm("Are you sure ?");">
Orelse
You can write a function in javascript to check that
<input type="submit" value="Bestil" onclick="myfunct();">
function myfunct(){
if(document.getElementById("antal").value > 1)
confirm("Are you sure");
return true;
}

How to delete from mysql using bootstrap modal?

I want to delete accounts according to the selection of a drop down list.
This is my markup for the form -
<form action="" method="post">
<select class="form-control" size="8" id="userName" name="userName">
<option value="9" data-userId="uid9">dilani</option>
<option value="6" data-userId="uid6">kamala</option>
<option value="12" data-userId="uid12">senudhi</option>
<option value="2" data-userId="uid2">testuser</option>
<option value="4" data-userId="uid4">tharanga</option>
</select>
<br>
<button type="submit" class="btn btn-primary" >Terminate</button>
<br>
</form>
In PHP, I am checking an user is submitting the form and have selected an username from dropdown before delete the account.
My PHP code is something like this -
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Check for username is selected from dropdown list:
if (isset($_POST['userName'])) {
$userid = $_POST['userName'];
//echo $userid;
// my delete query ---
} else {
$error_msg .= ' You didn\' select either username or domain name to Terminate.';
}
}
My problem is, If the form have submitted successfully then I need to display a conformation dialog box before to delete the account.
I tried it javascript onsubmit but its not working for me. As soon as I click on Terminate button the confirmation is display ignoring the selection of dropdown. That mean I don't need to select an item from username list to get this work.
This is how I checked it -
<form action="" method="post" onSubmit="return confirm('are you sure?')">
Can anybody guide me to do this using Bootstrap modal?
Thank You.
Capture the form on submit, toss out a confirm box. Return true if they click Yes, return false if they click No.
$('form').on('submit', function(){
e.preventDefault();
if(confirm('Are you sure you wish to delete this user?')){
return true;
} else{
return false;
}
});
Either you can submit via ajax, or if you need to just confirm that you can use something like
<form id="target" action="destination.html">
<input id="btn" type="button" value="Go"/>
</form>
$(function() {
$("#btn").click(function(){
if (confirm("Click OK to continue?")){
$('form#target').submit();
} else {
//return false;
}
});
});

disabling user input php/html form

I have a HTML form which when the user clicks submit, all information is sent to email via a php script using the POST method. What i want to do is disable all user input after the submit button is clicked or grey out all text box input fields. How can i go about doing this?
the code for the submit button at the moment looks like this:
<input type="submit" value=" Continue " style="width:200px;height:40px">
Add below to each HTML input element you want to disabled. Since you have not mentioned I assume that you can use PHP for this.
<?php if(isset($_POST['submit'])) echo 'disabled="disabled"'; ?>
If you are using AJAX, when the event is fired, inside particular event
$("input").prop('disabled', true);
Onclick of submit button make all input to disabled
$("input").attr('disabled', true);
Since whether mail has been sent is server side processing, its better if you handle this from server end than from client side like jQuery and javascript :
$form_state = ($is_mail_sent)?"":"disabled='disabled'";
<input type="submit" <?php echo $form_state ?> value=" Continue " style="width:200px;height:40px">
without db interaction you can't do this out, have a flag in db table. Set the flag 1 if user submit a form, by default 0. Based on the flag value you can disable the form.
if(mailsent_status_of_the_user == 1){
$status = "disabled='disabled'";
}else{
$status = "";
}
<input type="submit" value=" Continue " <?php echo $status; ?> >
By using jQuery : $("input").prop('disabled', true);
But in pure Html is not possible without refreshing page !
Edit :
Javascript :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(e) {
$("#yourFormID").submit(function() {
$("#theInputToDisable").prop('disabled', true);
//Or to disable all inputs
//$(this).children("input").prop('disabled', true);
//$(this).children("input").attr('disabled', 'disabled');
return false;
})
});
</script>
HTML
<form id="yourFormID">
<input type="text" />
<input type="submit" value="Send"/>
</form>

how to select option to submit different php page

drop down select "sales" go to sales.php, other options selected go to addFund.php...
<form name='searform' method='post' action='<?php echo $home;?>addFund.php'>
Search : <input type='text' id='sear' name='sear'> by
<select id='psel' name='psel' onchange='change()'>
<option value='email'>Email</option>
<option value='name'>Username</option>
<option value='domain'>Domain name</option>
<option value='sales'>Sales</option>
</select>
<input type='submit' name='sub' id='sub' value='Go' onclick='gopage()'>
<input type='submit' name='dir' id='dir' value='Direct'>
</form>
How to submit different pages
You could use some Javascript nastiness to achieve this with the change() function, but the usual way to do this is to route all requests through a controller and include() the appropriate page. For example, point your form to action.php, and in that file, do this:
action.php
<?php
if (isset($_POST['psel']) && $_POST['psel'] == 'sales') {
include 'sales.php';
} else {
include 'addFund.php';
}
...or you could just put roughly that code into addFund.php, since you only seem to have one other script that you would want to send requests to.
You could do this with javascript:
function change(el) {
if(el.value === 'sales') {
el.form.action = 'sales.php';
} else {
el.form.action = 'addFund.php';
}
}
Change the onchange to onchange="change(this)". A better way would be to check the variable on serverside and include the right file.
Change your select to this:
<select name="vote" onChange="document.forms['searForm'].submit()">
And make your form action go to something like pageChange.php where it returns a different page depending on the $_POST value.

PHP - Form: save entries/selections on form submit

I have a PHP form that has some drop down selections and text field entries. If the user selects the wrong item from the dropdown, when they submit the form, I have it so that it will show an error message to the user and force the browser to go back to the previous page. The problem is that the user has to re-enter all of the information.
How do I make the form save the data until the form submit is successful?
EDIT:
Form submit method is $_POST and the form is being submitted to another page.
This would have to be done with strictly PHP as Javascript/Jquery solutions can be script blocked by more secure users.
Here you go. This will work, and is not dependent on Javascript:
form.php //the form page
<?php session_start(); ?>
<form method="post" action="action.php">
<input type="text" id="input1" value="<?php echo (isset($_SESSION['fields']) ? $_SESSION['fields']['input1'] : '') ?>" />
<input type="text" id="input2" value="<?php echo (isset($_SESSION['fields']) ? $_SESSION['fields']['input2'] : '') ?>" />
</form>
action.php //the action page
<?php
session_start();
//do your validation here. If validation fails:
$_SESSION['fields']['input1'] = $_POST['input1'];
$_SESSION['fields']['input2'] = $_POST['input2'];
//redirect back to form.php
?>
Is the form a POST or a GET? Either way, you have access to all the submitted fields in the PHP variables $_POST or $_GET. Within your HTML you can pass those values (if set), to the default value of each HTML input element. This way, if it is a first time, they will be blank, if there was an error, the values will repopulate.
If they're select values, you can do something like this:
<select name="my_select" id="my_select">
<option value="123"<?php if($_REQUEST['my_select'] == 123) echo ' selected="selected"; ?>>123</option>
</select>
If you have regular text inputs, you can simply apply the $_REQUEST variable to the value attribute:
<input type="text" name="my_text" value="<?php echo $_REQUEST['my_text'] ?>" />
I suggest a preventing the page from navigating away from the submission until the data is verified. Enter jQuery :)
<script type="text/javascript" src="jquery-library.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Wait for the user to click on your button
$('#submit_button').click(function(){
// Check each form field for an appropriate value
if ($('#form_field1').val() != 'something I expect')
{
alert('Wrong submission!');
return false;
}
// Forward the user to some url location
window.location = 'url';
return false;
});
});
</script>

Categories