PHP to show div info based on selected option in form - php

I want to use PHP to change a div's information based on what option is selected. Below is my HTML & PHP. I don't think I'm using the right operator or syntax in the if statement. I basically want to pull information from a table in my database based on the option selected. Right now I do not have that in my code because it is irrelevant at this point. Any help is appreciated.
<select id=\"numberofstaff\">
<option class=\"staffselection\" value=\"\">--Select--</option>
<option class=\"staffselection\" value=\"smalljobsite\">1-3 staff</option>
<option class=\"staffselection\" value=\"mediumjobsite\">4-7 staff</option>
<option class=\"staffselection\" value=\"largejobsite\">8+ staff</option>
</select>
<?php
$selectOption = $_POST['numberofstaff'];
echo "<div id='jobsite_price'><p>";
if ($selectOption == 'smalljobsite'){
echo "smalljobsite";
};
if ($selectOption == 'mediumjobsite'){
echo "mediumjobsite";
};
if ($selectOption == 'largejobsite'){
echo "largejobsite";
};
echo "</p></div>";
?>

You need form tags and a POST method, while giving the select a name attribute. You can't rely on an id alone, not without JS/Ajax anyway.
Sidenote: I removed the \ from the escaped quotes, since they're not in an echo statement/PHP in your posted code. This would throw an error/warning such as "unquoted attribute". If you are using it inside an echo'd statement, then you'll need to add those back in.
FYI: Escaping quotes \" is only done when inside an echo/PHP.
Additional note:
If you want to run seperate SQL statements, it's rather simple. Where the echos are and where I have in a comment form // RUN SQL HERE, you can simply include a file in there with your SQL query. I do it myself and it cuts down on a lot of code and is more manageable that way.
HTML/PHP:
<form method="post" action="">
<select id="numberofstaff" name="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
$selectOption = $_POST['numberofstaff'];
echo "<div id='jobsite_price'><p>";
if ($selectOption == 'smalljobsite'){
// RUN SQL HERE
echo "smalljobsite";
}
if ($selectOption == 'mediumjobsite'){
// RUN SQL HERE
echo "mediumjobsite";
}
if ($selectOption == 'largejobsite'){
// RUN SQL HERE
echo "largejobsite";
}
echo "</p></div>";
} // brace for if(isset($_POST['submit']))
?>
Foonotes:
To include files, you can use include():
// Include your SQL query
include('query_file.php');
where you see // RUN SQL HERE in commented code.
Another option is to use Ajax.
Here are a few links:
http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php
http://www.tutorialspoint.com/php/php_and_ajax.htm
How to use AJAX to perform a MYSQLI query (prepared statement)

If you're just using php to check the selected value, you can use jquery for that, i.e.:
$("select").on('change', function() {
$("#jobsite_price").html("<p>"+$(this).val()+"</p>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
<div id='jobsite_price'></div>

You can use pure javascript to do this.
window.addEventListener('load', function(){
var el = document.querySelector("#numberofstaff");
el.addEventListener('change', function(){
var data = { numberofstaff : el.value };
var request = new XMLHttpRequest();
request.open('POST', 'YourUrl.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
request.onload = function(result){
document.querySelector("#jobsite_price").innerHTML = result.responseText;
}
});
});

Related

Get select option value from HTML with php to disable input field

I use select as below:
<select name="account_type" required>
<option value="">Choose Account Type</option>
<option value="1">Asset</option>
<option value="2">Bank</option>
<option value="3">Capital</option>
<option value="4">Cash</option>
<option value="5">Expense</option>
<option value="6">Income</option>
<option value="7">Liability</option>
</select>
Now I want to catch those option values using php variable, and here is the important part: I will have an input field, and based on the values I want to enable/disable that input filed.
How can I do that?
Using jQuery give your select an id like below
<select name="account_type" id="account" required>
<option value="">Choose Account Type</option>
<option value="1">Asset</option>
<option value="2">Bank</option>
<option value="3">Capital</option>
<option value="4">Cash</option>
<option value="5">Expense</option>
<option value="6">Income</option>
<option value="7">Liability</option>
</select>
<!--input to be disabled -->
<input type="text" id="disable">
jQuery
$('#account').on('change', function(){
if($(this).val() === '1') {
$("#disable").prop('disabled', true);
//you can also send data to PHP here using AJAX
//var data = {one: $(this).val()};
//$.post( "test.php", data, function( data ) {
//$( ".result" ).html( data );
//});
}else if($(this).val() === '2') {
//code here
}
//check for other values
});
example
You could do this with jQuery. If you don't know jQuery, check this out: jQuery.com
After you "installed" jQuery, you can use this in your js-File. I hope that you know how to create and use a js-File.
The next thing is to implement a good method for your select-button.
This could look like this in your js-File:
$('#my-select').change(function(){ // "#my-select" is the ID of your select. You need to implement a ID.
//do stuff here, eg.
if ($(this).val() == '5') { //check the selected option etc.
$("input").prop('disabled', true);
} else {
$("input").prop('disabled', false);
}
});
Here's a jsFiddle.
Hope this helps you.
html code
<select>
<option data-id="1">1</option>
<option data-id="2">2</option>
</select>
JQuery code
$(document).ready(function(){
$("select").change(function(){
var display= $("select").val();
if(display == 1){
$("select").attr("disabled", 'disabled');
}
});
});
I am not sure what you want exactly.check out this may be it will be helpful for you JSFiddle

Selected option does not get put into post variable

Edit: Thanks for the help everyone, I've changed the topic since I
discovered that the problem was more specific to PHP.
I'm new to jQuery and Javascript and I'm creating a page with a search function that requires the user to enter a region to retrieve information that is region-specific. Within a form, I have included a drop-down menu:
<select name="region" id="region">
<option selected="selected" value="na">NA</option>
<option value="euw">EUW</option>
<option value="eune">EUNE</option>
<option value="tr">TR</option>
<option value="lan">LAN</option>
<option value="las">LAS</option>
<option value="br">BR</option>
<option value="ru">RU</option>
<option value="oce">OCE</option>
<option value="kr">KR</option>
</select>
Even if I try to select another region other than the default (NA), when the form is submitted, the value for the $_POST region variable always remains as 'na'.
Also, I have a script on form submit:
<script>
$(function () {
$('#myForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'redirect.php',
data: $('form').serialize(),
success: function () {
location.reload();
}
});
});
});
</script>
My form:
<form id="myForm">
<li id="search">
<input type="text" name="name" id="name" placeholder="Search Word"/>
<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1" />
<select name="region" id="region">
<option selected="selected" value="na">NA</option>
<option value="euw">EUW</option>
<option value="eune">EUNE</option>
<option value="tr">TR</option>
<option value="lan">LAN</option>
<option value="las">LAS</option>
<option value="br">BR</option>
<option value="ru">RU</option>
<option value="oce">OCE</option>
<option value="kr">KR</option>
</select>
</li>
</form>
redirect.php
<?php
session_start();
if (isset($_POST['name']) && isset($_POST['region'])) {
$_SESSION['name'] = $_POST['name'];
$_SESSION['region'] = $_POST['region'];
}
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
$_POST['region'] = 'na'; // I think this is where the problem persists
$_SESSION['region'] = $_POST['region'];
}
?>
It seems like $_POST['region'] is not set.
I've included session_start in both files.
Any help would be appreciated. Thank you.
what I usually do is this:
$(document).on("change",function(){
if($("#region").val()!="na"){
var region=$("#region").val();
alert(region);
}
});
with this you will be able to check if the value is actually changing, and now you can use that variable wherever you want.
And it will work for everytime the value changes until you submit
Hope this helps!
Try this:
var $region = $('#region');
$region.val([]);//now $('#region').val() return undefined
//exacttext version
region.find('option').filter(function (index, elem) { return $(this).html() === textSearchValue; }).prop("selected",true);
//containstext version
region.find('option').filter(function (index, elem) { return $(this).html().indexOf(textSearchValue)>0; }).prop("selected",true);
PS: always cache the elements in a $variable
OP changed the topic of the question, going to leave my code here just for reference, but I'm fully aware it's not an answer anymore.
I wrote a quick CodePen to test what was going on in your problem, I didn't check with a POST request because I don't have your code, but with jQuery all I had to do was remove the selected atribute from NA:
http://codepen.io/leofontes/pen/ZBGZZZ
<select name="region" id="region">
<option value="na">NA</option>
<option value="euw">EUW</option>
<option value="eune">EUNE</option>
<option value="tr">TR</option>
<option value="lan">LAN</option>
<option value="las">LAS</option>
<option value="br">BR</option>
<option value="ru">RU</option>
<option value="oce">OCE</option>
<option value="kr">KR</option>
</select>
<button id="button">Something</button>
And JS:
$(document).ready(function() {
$("#button").click(function() {
alert($('#region').val());
});
});
Just click the button to see which option was selected, it works.. Not 100% sure if this is what your problem revolved around but I'm pretty sure it was that simple.
Hope this is what you were looking for, if not let me know so that I can help you out some more ;)
Ok so I found out what I had done wrong...
It was because of a small error in ordering of conditionals in redirect.php
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
$_POST['region'] = 'na'; // Where I thought the problem persisted
$_SESSION['region'] = $_POST['region'];
}
This part of the code will always run even after the $_POST variables are set.
My intention was for it to run when $_POST for region was not set.
As a result, I changed it to the following and it worked.
if (!isset($_POST['region'])) {
$_SESSION['name'] = $_POST['name'];
$_POST['region'] = 'na';
$_SESSION['region'] = $_POST['region'];
}
Thanks again everyone!

input a form option into databse mySQL and php

<select name="direction">
<option value="<a href='1.php'>1</a>">1</option>
<option value="<a href='2.php'>2</a>">2</option>
</select>
I'm trying to insert a href into a database but the double quotes are messing it up how do I properly use double or single quotes in this situation?
Can you try this,
<select name="direction">
<option value='<a href=1.php>1</a>'>1</option>
<option value='<a href=2.php>2</a>'>2</option>
</select>
You can not do like that. Just try like below:
Your html will be like this;
<select name="direction" onchange="onSelect()">
<option value="1">1</option>
<option value="2">2</option>
</select>
And Javascript will be like this-
function onSelect() {
if (document.getElementById("direction").value == "1"){
window.location.href = "1.php";
}
elseif (document.getElementById("direction").value == "2"){
window.location.href = "2.php";
}
}
You should escape your html before inserting it into database. You can use addslashes(string $str) to escape values which contains HTML content.
on server side
$myvalue = "<a href='1.php'>1</a>"; // value from selected option
$escaped_myvalue = addslashes($myvalue); // $myvalye becomes "<a href=/'1.php/'>1</a>"
inser_into_table($escaped_myvalue);
http://php.net/manual/en/function.addslashes.php

Get value from select with JavaScript for use in PHP

I have this select:
<select id="mymenu" name="id" onchange="getID()">
<option></option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I want to get the value from mymenu to use it in another select in the same form. I searched the 'net and found that I should use onchange.
<select name="uid">
<option></option>
<?
$sql = mysql_query("Select * from $table WHERE id = '$ch_id'");
while ($row = mysql_fetch_array($sql)) {
?>
<option value="<? echo $row['unit_id']; ?>"><? echo $row['unit_name'];?></option>
<?
}
?>
</select>
This is the getID() function:
<script type="text/javascript">
function getChapterID(){ //run some code when "onchange" event fires
var selectmenu=document.getElementById("mymenu")
<?$ch_id?> = this.options[this.selectedIndex].value
}
</script>
You can't redefine a PHP value thru JS, it would be very unsafe. I suggest you to use kind of form that when you change it, it submits, posts into a php self and redefines it. I won't write that code for you, but this is what you need.
Good luck
google "ajax php select menu", the first example here: http://www.w3schools.com/php/php_ajax_database.asp
explains the process...
Beware the w3 demo though, it does not sanitize $_GET[] variable, and is wide open to a sql injection.

populating different data with select onChange in php

i need some clarification on how to populate select(s) with data from mysql. Basically what I am trying to do is:
There will be a first select box with some data in it.
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
when the user selects a option in the first select,
there is a second select below that, which should reflect the values according to the selection made in the first select.
<select>
<option>1.1</option>
<option>1.2</option>
<option>1.3</option>
</select>
The data is commin from MySQL. I am not sure if need to post to same page, but if I do, how to retain the values alredy selected in the previous select boxes? do i need to use javascript?
any help?
Thanks.
You should use javascript so you don't need a page refresh. I just re-read your question and I'll have a solution involving an AJAX request in a second to pull dynamic data:
HTML
<select name="select1" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select2" id="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
jQuery
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
});
function getDropdownOptions() {
var val = $(this).val();
// fire a POST request to populate.php
$.post('populate.php', { value : val }, populateDropdown, 'html');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
populate.php
<?php
if (!empty($_POST['value'])) {
// query for options based on value
$sql = 'SELECT * FROM table WHERE value = ' . mysql_real_escape_string($_POST['value']);
// iterate over your results and create HTML output here
....
// return HTML option output
$html = '<option value="1">1</option>';
$html .= '<option value="b">B</option';
die($html);
}
die('error');
?>

Categories