Передача значения из select в php
без всяких там кнопок и т.п. выбираем значение, передаём его в переменную в php, как это реализовать?
Буду благодарен за любую помощь.
Как при выборе значения в select выполнить функцию php и передать в ей аргумент (значение select)
Вообще, я хочу сделать выборку в таблице. После выбора в <select>, в таблице должны остаться запись.
Передача значения в select
Возможно не совсем корректно сформировал тему сообщения, но в общем суть такова. — имеем.
Передача пункта select в php
Добрый день! Подскажите пожалуйста можно ли как-то передать в php, то что написано между тегами.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$oper = $_POST['lang']; switch ($oper){ case '0': $lang='All'; break; case '1': $lang='BY'; break; case '2': $lang='RU'; break; case '3': $lang='KZ'; break; case '4': $lang='UA'; break;} echo $lang; ?>
form action="" method="post" id="myForm"> select name='lang' onchange="document.getElementById('myForm').submit()"> option value='0'>ALL/option> option value='1'>BY/option> option value='2'>RU/option> option value='3'>KZ/option> option value='4'>UA/option> /select> /form>
Сообщение от CloudS
Возможно я не в тот раздел написал..
Пишу на Kohana и как бы проблема такая, может объяснишь.
Когда открываю страницу обработчик пишет следующее.
22 $oper = $_POST['lang']; //Undefined index: lang
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Это всё написано в виде, запросы берутся из контроллера. Почему он не может взять значение? Я новичок просто в этом деле.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
if (!isset($_POST['lang'])){ $oper = $_POST['lang']; switch ($oper){ case '0': $lang='All'; break; case '1': $lang='BY'; break; case '2': $lang='RU'; break; case '3': $lang='KZ'; break; case '4': $lang='UA'; break;} echo $lang; }}
form action=" " method="post" select name='lang' onchange="document.getElementById('myForm').submit()"> option value='0'>ALL/option> option value='1'>BY/option> option value='2'>RU/option> option value='3'>KZ/option> option value='4'>UA/option> /select> /form>
if (!isset($_POST['lang']) $oper = $_POST['lang']; //syntax error, unexpected T_VARIABLE
Сообщение от Feel Good
if (!isset($_POST['lang']) $oper = $_POST['lang']; //syntax error, unexpected T_VARIABLE
скобку в конце строки пропустил
Пожалуйста, не мешайте, товарищ pav1uxa. Я стараюсь помочь человеку. ведь в этом коде есть и другие ошибки, на которые он не обратив внимания, а вы, как незваный гость, мешаете решению проблемы. Если хотите выразиться — предлагайте свои идеи, но не мешайте другим доводить свои до конца.
Спасибо большое!
Сообщение от CloudS
Сообщение от Feel Good
Сообщение от CloudS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
Список всех новостей if (!isset($_POST['lang'])) $oper = $_POST['lang']; switch ($oper){ case '0': $lang='All'; break; case '1': $lang='BY'; break; case '2': $lang='RU'; break; case '3': $lang='KZ'; break; case '4': $lang='UA'; break;} echo $lang; ?>
Сообщение было отмечено Feel Good как решение
Решение
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
Список всех новостей if (isset($_POST['lang'])){ $oper = $_POST['lang']; switch ($oper){ case '0': $lang='All'; break; case '1': $lang='BY'; break; case '2': $lang='RU'; break; case '3': $lang='KZ'; break; case '4': $lang='UA'; break;} echo $lang; } ?>
Сообщение от CloudS
Нашёл из-за чего било ошибку, невнимательный просто.
Да теперь всё отлично)
Только вот что-то странно работает
по идеи должно имя файла скрипта, который сейчас выполняется, относительно корня документов, но происходит совсем другое.
Unable to find a route to match the URI: index.php
Добавлено через 11 часов 42 минуты
Всё же видимо оно не передаёт значение с select. Вместо case сделал if. Пусто.
Добавлено через 49 минут
Вместо этого
Теперь работает, забирает значение с lang, но, select сбрасывается всегда на первое значение, т.е. к примеру выбрал значение 2, после отправки, информация меняется на странице, а select остается со значением 1.
Добавлено через 6 часов 3 минуты
Всё CloudS, спасибо за вашу помощь
Все проблемы на данный момент решены. Всем спасибо ещё раз.
Передача значения select методом Ajax
Доброго времени суток. Есть форма: <form method="POST" name="bs" > <select.
Передача значения select через onclick
Добрый день. Имеется выпадающий список, заключенный в select. Значение, которое будет выбрано.
PHP & MySQL передача в запрос SQL значения переменной из PHP
Здравствуйте. Мне необходимо передать в SQL-запрос значение любой переменной. Например, мне.
Вызов функции js в php скрипте и передача значения js в php скрипт
Доброе время суток.! Подскажите пожалуйста как можно (и можно ли вообще) вызвать функцию js .
Select передача выбранного значения на сервер без перезагрузки страницы
Доброго времени суток всем! Гуру помогите разобраться с основами ajax. задача наверное для многих.
PHP Select Option
Summary: in this tutorial, you will learn how to use the element to create a drop-down list and a list box and how to get the selected values from the element in PHP.
A quick introduction to the element
The is an HTML element that provides a list of options. The following shows how to define a element in HTML:
label for="color">
Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)
The element has two important attributes:
- id – the id associates the element with a element
- name – the name attribute associates with the value for a form submission.
The element nested inside the element defines an option in the menu. Each option has a value attribute. The value attribute stores data submitted to the server when it is selected.
If an option doesn’t have the value attribute, the value attribute defaults to the text inside the element.
To select an option when the page loads for the first time, you can add the selected attribute to the element.
The following example selects the Green option when the page first loads:
label for="color">
Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)
Getting the selected value from a element
We’ll create a form that uses a element.
First, create the following folders and files:
├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: JavaScript (javascript)
Second, place the following code in the header.php file:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="css/style.css"> title>PHP select option title> head> body class="center"> main>Code language: HTML, XML (xml)
Third, place the following code in the footer.php file:
main
> body> html>Code language: HTML, XML (xml)
Fourth, add the following code to the get.php file to create a form that has one element with a submit button:
form action="" method="post">
div> label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select> div> div> button type="submit">Select button> div> form>Code language: HTML, XML (xml)
The form uses the POST method to submit data to the webserver.
Finally, add the following code to the post.php file:
$color = filter_input(INPUT_POST, 'color', FILTER_SANITIZE_STRING); ?> if ($color) : ?> p>You selected span style="color:"> echo $color ?> span>
p> p>a href="index.php">Back to the form a> p> else : ?> p>You did not select any color p> endif ?>Code language: HTML, XML (xml)
To get the selected value of the element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET .
Alternatively, you can use the filter_input() function to sanitize the selected value.
If you select the first option of the element, the selected value will be empty. Otherwise, the selected value is red, green, or blue.
Select with multiple options
To enable multiple selections, you add the multiple attribute to the element:
select name="colors[]" id="colors" multiple>
. select>Code language: HTML, XML (xml)
When you select multiple options of a element and submit the form, the name will contain multiple values rather than a single value. To get multiple selected values, you add the square brackets ( []) after the name of element.
Let’s take a look at an example of using a element with multiple selections.
First, create the following folders and files:
. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: JavaScript (javascript)
Second, place the following code into the header.php file:
html>
html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP Listbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)
Third, add the following code to the footer.php file:
main
> body> html>Code language: HTML, XML (xml)
Fourth, include the header.php and footer.php files in the index.php :
require __DIR__ . '/inc/header.php'; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > require __DIR__ . '/inc/footer.php';
Code language: HTML, XML (xml)
If the HTTP request is GET, the index.php file will show a form from the get.php file. When the form is submitted, the post.php file will handle the form submission.
Fifth, create a form that contains a element with the multiple attribute in the get.php file. The name of the element has an opening and closing square bracket [] so that PHP can create an array that holds the select values.
form action="" method="post">
div> label for="colors">Background Color: label> select name="colors[]" id="colors" multiple> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> option value="purple">Purple option> option value="magenta">Magenta option> option value="cyan">Cyan option> select> div> div> button type="submit">Submit button> div> form>Code language: HTML, XML (xml)
Finally, handle the form submission in the post.php file:
$selected_colors = filter_input( INPUT_POST, 'colors', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ); ?> if ($selected_colors) : ?> p>You selected the following colors: p>
ul> foreach ($selected_colors as $color) : ?> li style="color:"> echo $color ?> li> endforeach ?> ul> p> p> else : ?> p>You did not select any color. p> endif ?> a href="index.php">Back to the form a>Code language: HTML, XML (xml)
The post.php file uses the filter_input() function to get the selected colors as an array. If you select one or more colors, the post.php file will display them.
Summary
- Use the element to create a dropdown list.
- Use the multiple attribute to create a list that allows multiple selections.
- Use $_POST to get the selected value of the select element if the form method is POST (or $_GET if the form method is GET ).
- Add square brackets( [] ) after the name of the element to get multiple selected values.