Logic for form post that reset URL query parameter? - php

I'm not getting the results expected when doing an update via onchange="formType.submit()" on a Select List.
I was hoping to have the PHP $_POST value set as a new URL but it looks like the value is not yet present when submitting the form.
Original URL: http://example.com/Select-item.php?type=4
<form action="Select-item.php?type=<?php echo $_POST['selItem']; ?>" method="post" id="formType">
<select name="selItem" id="selItem" onchange="formType.submit()">
<option value="1">change to 1</option>
<option value="2">change to 2</option>
<option value="3">change to 3</option>
</select>
</form>
The error I receive is undefined index (...Select-item.php?type=Notice:%20Undefined%20index:%20...)
Is the correct way to make this page URL update by posting to the same page, reading the $_POST value and then using

PHP generates the HTML code before it is transmitted to the client; after the client receiced the code, it will render it to a website.
The reason your code is not working because when <?php echo $_POST['selItem']; ?> is executed there is no POST-Variable selItem set; it is set after the form was submitted.
If you really want to transmit selItem as GET and as POST-Variable - a possible way of doing this is using this function (untested):
<script>
function onSelectChange() {
// Access the select-field and get it's value
var sel = document.getElementById("selItem");
var selectedValue = sel.options[sel.selectedIndex].value;
// Change the target URL of the form
document.getElementById("formType").action = 'Select-item.php?type='+ selectedValue;
formType.submit()
}
</script>
And edit the onChange-Listener in your select: onchange="onSelectChange"
BUT I would recommend using GET instead - this way selItem will be always in URL, too, and you don't need to check for $_GET and $_POST at the same time

Always check using isset() function before using a $_POST
Example:
if(isset($_POST['selItem'])){
//your code here
}

Related

read all option in another page

I have a form which sends information with post method to another page. In the form I have a select box with three options, for example:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
In another page, I read the selected item with $_POST['slctstate'], but I want to read all options (key & value) in the select tag.
Can I do this?
First use a jquery function which stores all the options in a string
$(document).ready(function()
{
var myoption = '';
$('#drop_down option').each(function()
{
myoption = myoption + ',' + ($(this).val());
});
$('#hidden_text').val(myoption);
}
);
in the html use a hidden field
<input type="hidden" id="hidden_text" name="hidden_text"/>
WHen you will submit the form, catch this value with a list of options separated by (,);
On the action page, you can split the value using php explode() function
Check the fiddle
http://jsfiddle.net/1u9x5nbq/3/
No you can't without a work-around. The only value gets passed is the selected value. If you want to know all values you can use a work-around in javascript e.g.:
<select name="slctstate" id="slctstate">
<option value="0">aaaaa</option>
<option value="1">bbbbb</option>
<option value="2">ccccc</option>
</select>
//Include JQuery
<script>
$(function()
{
$('#slctstate option').each(function()
{
$('#slctstate').after('<input type="text" value="'+$(this).text()+'" name="slctstateOptions['+$(this).val()+']" style="display:none;" />');
//Where val() is the key and text() is the value.
});
});
</script>
Then you can access the values by using $_POST['slctstateOptions'].
No, you can't do that from the form. When you do submit, you send only selected value(s).
No,
The only value that is "selected" will be POSTed on Submit.

send selected values of select box to PHP as string

I'm using Select2 3.4.5 for create select boxes,
I use this code for creatre a Multi-Value Select Boxe and everything is fine.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
...
<script>
$("#e1").select2();
</script>
For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:
<?php
foreach ($_POST['mydata'] as $names) {
print "You are selected $names<br/>";
}
?>
But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.
Edit:
I want to send the data as string, not receive it as an array then
change it as string
Server-side with PHP
Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array
$names=implode(',', $_POST['mydata']);
Where $_POST['mydata'] is an array
[0]=>'D1',
[1]=>'D2',
[2]=>'D3'
implode(',', $_POST['mydata']) would be 'D1,D2,D3'
Client-side with jQuery
Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.
$('#formid').on('submit', function(){
$('#e1').val($('#e1').val().join(','));
});
Your form (not given) would need an id <form id="formid" ...>
If you want a client-side solution, try getting the val() and calling join():
$('#e1').val().join()
http://jsfiddle.net/gwgLV/
You can do it with javascript.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>
javascript code
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function now(){
var el = document.getElementsByTagName('select')[0];
var x = getSelectValues(el);
alert(x);
}
Demo here
Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.

Get JSON specific value using jQuery

I have a json which is generated through php and i assigned it to a JS variable like below,
var jsonObj = {
"ATF":["FLV"],
"Limecase":["FLV"],
"RCF":["FLV","HTTP","PALM","MOBILE","3GP","H263","F263","WMV"],
"Wave":["FLV","IPHONE","MOBILE"]
}
And also i have a selectbox in html as below,
<select id="selectbox" data-rel="chosen">
<option value='ATF'>ATF</option>
<option value='Limespace'>Limespace</option>
<option value='RCF'>RCF</option>
<option value='Wave'>Wave</option>
</select>
On changing, i am getting the selected value and passing it as below,
alert(jsonObj.selVal); but alert throws "undefined"
But if i give direct value jsonObj.ATF, it gives FLV.
Please suggest me on this.
var selVal = 'ATF'; // or from an input
alert(jsonObj[selVal]);

storing select box values into an array

i have two select boxes and a link.i select one value from the first select box and another from the second select box and click on the link.the values have to get stored in an array each time without the previous value getting replaced.how can i do this without using multiple select box?
<select name="sq" id="sq" >
<option value=""></option>
</select>
<select name="as" id="as" >
<option value=""></option>
</select>
sorry forgot to mention..its in codeigniter
You can use change event to store the selected values.
Html
<select name="sq" id="sq" >
<option value="1">1</option>
<option value="2">2</option>
</select>
Javascript
arrSelected = []
$("#sq").change(function(){
arrSelected.push($(this).val());
});
With the added info from the comments, here is my suggestion:
HTML:
<div class="selectLine">
<select name="sq[]" >
<option value=""></option>
</select>
<select name="as[]" >
<option value=""></option>
</select></div>
<a id="addOption">
JavaScript:
$('#addOption').click(function(){
$('.selectLine').last().after($('.selectLine').outerHtml());
$('.selectLine').last().prev().hide();
});
PHP receiving the post:
foreach($_POST['sq'] as $key=>$name){
//Make sure you stay consistent with the keys to make sure the 2 values were entered at the same time.
echo '<p>'.$name.' is a '.$_POST['as'][$key].'</p>';
}
Adding [] to the end of the name of inputs will place them in arrays. But you need more than one if you want more than one value...
You can remove $('.selectLine').last().prev().hide(); to keep the lines displayed to the user so he can change the values if you want.
This would send the data with AJAX without page refresh:
Use for the link Submit data
Then add the following jQuery script: (you need to include jQuery library first)
$('#submitlink').click(function(event) {
event.preventDefault(); // Stops default link behaviour on click
$.ajax({
url: "yourphp.php", // where to send
data: 'sq=' + $('#sq').val() + '&as=' + $('#as').val(), // select values
type: "POST",
success: function(data){
// If you want to confirm
alert('Added');
}
});
});
Then in your php script store the $_POST data in either a database or session...
Session example, storing:
<?php
session_start();
if (!isset($_SESSION['sq']) $_SESSION['sq'] = array();
$_SESSION['sq'][] = $_POST['sq'];
if (!isset($_SESSION['as']) $_SESSION['as'] = array();
$_SESSION['as'][] = $_POST['as'];
?>
To retrieve the results you could use:
<?php
session_start();
if (isset($_SESSION['sq']) print_r($_SESSION['sq']);
if (isset($_SESSION['as']) print_r($_SESSION['as']);
?>
But of course this could be elaborated.
If you wish to have persistence in your website, then I would recommend looking into PHP Cookies.
In your case, you want to store an array, persistently, so you have a few options.
Either implement a HTML Hidden Element or you can use Serialization to store the array inside a cookie.

if specific select option is chosen get the value of input

I have a little knowledge of php, but this is what I'm trying to do. I have a form with select option. If an option is selected with the value "example_5" I want it to get the value of an <input>. Is this done with php or jquery to use the value of input?
For example: someone selects example_5. They can now write something in the <input>. And that value will be used.
<script type="text/javascript">
$(function(){
if($('select').find('option:selected').val() == 'example_5'){
use input??
$_COOKIE['input_example'] = $example_1;
}
else{
$_COOKIE['example_1'] = $example_1;
}
});
</script>
<?php
$_COOKIE['example_1'] = $example_1;
?>
<form method="get" action="page2.php">
<select name="example1">
<option value="example_1">example_1</option>
<option value="example_2">example_2</option>
<option value="example_3">example_3</option>
<option value="example_4">example_4</option>
<option value="example_5">example_5</option>
</select>
<input name="input_example" type="text">
</form>
The way I would do it is to have a onChange listener on the select box and then using javascript get the value of the input box using document.getElementById. You can use any jQuery shortcut you want, but the methodology would be the same.
See this fiddle for a functional example using this technique.
On an unrelated note, be sure to always close your <input /> tags (probably just a typos :)
Edit
As per comment : just set the value of the input from a value from the cookies.
document.getElementById("input_example").value = getCookie("cookie_name");
Where you can write a simple function to get the cookies :
function getCookie(Name) {
var search = Name + “=”
if (document.cookie.length > 0) { // if there are any cookies
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(”;”, offset)
// set index of end of cookie value
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
Tutorial for js cookie function taken here.
See also
JS Cookies
Based on your comment to blo0p3r's answer.
In page2.php, add the following at the very top of the script before any whitespace or HTML is sent:
<?php
if (isset($_GET['example1']) && $_GET['example1'] === "example_5")
setcookie($_GET['input_example'], 'example_5', time()+3600, '/');
First, you want to check if the from is submitted. Afterward $_COOKIE['example_1'] = $example_1; would be something like this:
$_COOKIE['example_1'] = $_GET['example1'];

Categories