Passing value from HTML form to php variable - php

I'm trying to pass a value from an HTML form and store it to a php variable so i can use this variable into a query to determine what row to get from database. I'm using _post['category'] to get the selected value and I'm passing the variable to the query to get the desired row but I'm not getting anything so far any help will be appreciated. Here is what I wrote so far:
<form method="post" action="a34.php">
<select name="category">
<option value="6008">15</option>
<option value="6018">25</option>
<option value="6034">30</option>
<option value="6038">40</option>
$V=$_POST['category'];
$getrow= "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID = '$V'";

I recommend you to use strip_tags function. Never put raw data into sql.
So
If(isset($_POST['category']) {
$data = strip_tags ($_POST['category']);
$getrow= "SELECT ProdID, ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable, cart_thumb
FROM accessories
WHERE ProdID = '. $data .'";
}

Okay, try the following.
The JS file detects when the user clicks an option and sends out an ajax request to the updateRow.php file with the $_POST variable of val.
updateRow.php takes the $_POST variable and casts it into an integer. The query is then updated with that variable. Process the query, then echo, print, etc. the data in the desired HTML format. Otherwise, the data echo 'failure'.
The output that is echoed, printed, etc is then sent back to the JS file under the variable data. If the data equals 'failure', then an error message is outputted. Otherwise, it inserts the HTML in the #row element.
// ------ Your JS file ---------
$(function() {
$row = $("#row");
$("#update-row").on("change", function() {
var val = $("select option:selected", this).val();
$.post('updateRow.php', {
val: val
}, function(data) {
if (data == 'failure') {
$row.text("Sorry, the row does not exist");
} else {
$row.html(data);
}
});
});
});
//------- updateRow.php ---------
//Make sure path/to/updateRow.php in the JS file is updated to here
$V = (int) $_POST['val'];
$getrow = "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID =" . $V;
if ( QUERY_IS_SUCCESSFUL() ) {
echo 'The <b>HTML</b> you want to display the data in';
} else {
echo 'failure';
}
<!----- HTML file ---->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="path/to/js/file.js"></script>
<form method="post" action="a34.php" id="update-row">
<select name="category">
<option value="6008">15</option>
<option value="6018">25</option>
<option value="6034">30</option>
<option value="6038">40</option>
</select>
</form>
<div id="row"></div>

Related

php how to used select box for search data in list view (table)

I have a query to select data from table(database) to show in List-view (table), than I want make code search data in list-view(table) by select-box without button submit.
this is my code in select box
<select onchange="selectrun(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
And this is my scrip
function selectrun(sel){
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
//what I return in response is a query because I want it's execute at my main page,that why I want pass it to $querr_select in php code but I don know my solution is good or not because I never do with ajax
}
});
}
This is my code in main page
$query_select = "SELECT * FROM `table`";
$result=pg_query($query_select ) or die(pg_last_error());
while($row_info=pg_fetch_array($result)){
//code for display view
}
*Note: in tab.php,I just pass id from main page to page tab.php for write a query to select in condition in where; when I alert response I get SELECT * FROM table WHERE ID ='1' And I want pass it to $query_select, is my idea but not work yet :(
I think what you are asking is how to display the result of an Ajax query. Is that correct?
<select onchange="selectrun(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<!-- A new HTML div for displaying Ajax call response: -->
<div id="response-area"></div>
<script>
function selectrun(sel){
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//Jquery sends response to browser div by setting html.
$('#response-area').html(response);
}
});
}
</script>
tab.php:
A basic concept of how you might return HTML via Ajax. This isn't great programming in terms of mixing HTML and PHP, but it it probably does what you want.
Assuming that your database table contains fields called 'field1' and 'field2', you can iterate through the array using the field names as array keys. Note that pg_fetch_array has additional parameters to select an associative array rather than a numerically indexed one.
<?php
$query_select = "SELECT * FROM `table`";
$result=pg_query($query_select ) or die(pg_last_error());
echo "<table>";
while($row_info=pg_fetch_array($result, NULL, PGSQL_ASSOC)){
echo "<tr>
<td>
$row_info[field1]
</td>
<td>
$row_info[field2]
</td>
</tr>";
}
echo "</table>";
?>
The modified code above should show you the response returned from tab.php when you change the option selected.

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 selected select value from a listbox with mysql data to open another listbox and fetch mysql data using this value

Im starting in javascript so, I need to do this : From a list box(already has mysql data using php) I want to get the current selection id (select,selected I think in Java) and fill a listbox with data using the id of the first listbox.But this must happens on onChange property of the listbox1 but on selection.
Here is what I have so far
Html code
Select a Region
$result_disp = mysql_query($query_disp, $cn);
$res=mysql_select_db("xxxx",$cn) or die("Note: " . mysql_error());
$res=mysql_query("select Region_ID, Region_Description from regions");
while($query_data = mysql_fetch_array($res))
{
?>
<option value="<? echo $query_data["Region_ID"]; ?>"
<?php if ($query_data["Region_ID"]==$_post['Region_ID']) ?>>
<? echo $query_data["Region_Description"]; ?></option>
<? } ?>
<select name="Dep" id="Items">
<option>Département</option>
</select>
javascript
function setSelect(id,value) {
var sel = document.getElementById(id);
var option, options = sel.options;
var i = options.length;
while (i--) {
option = options[i];
option.selected = (option.value == value)? true : false;
}
}
thanks in advance!
If you want to manipulate and query the DOM, use the great javascript library jQuery.
Once you have jQuery downloaded and included in your page, you can then do things like this:
<select id='myFirstSelect'>
<option value="1"/>
<option value="2"/>
</select>
javascript: (Bind a function to the 'changed'-event)
$('#myFirstSelect').changed(function(){
var selectedValue = $(this).val();
//do something with selectedValue, e.g. $('#someOtherSelect').val(selectedValue);
});
I haven't tested this code, it's just to give you an idea how much faster and more elegant you get ahead, once you get into jQuery (keywords: Selectors and Events)

One dropdownlist depending on the other

I develop a php web page that contains two dropdownlists (select tags) as one of them used to display the car types like Toyota, Nissan, Chevrolet and so on.
Toyota
Nissan
Chevrolet
The other should be used to display the car models like Toyota Camry, Toyota Corrolla, Toyota Cressida, Toyota Eco and son on depeding on the Car Type selected from the first dropdownlist.
I use PHP as a development language plus Sybase as database and I connect to it using ODBC.
I use Windows-1256 as Character Encoding as my displayed data is Arabic.
I try to use Ajax to implement that but I do not know how as I used Ajax before to return one value only but in this case I need to reply with some database records in the following format:-
15 "Toyota Camry"
16 "Toyota Corrolla"
17 "Toyota Cressida"
18 "Toyota Eco"
plus that the data is sent in arabic not in English as listed above so the list may be as the following:-
15 "تويوتا كامري"
16 "تويوتا كرولا"
17 "تويوتا كرسيدا"
18 "تويوتا إيكو"
how I can do that using Ajax and make sure that the Arabic text will be displayed well?
I wait your answer and help and Thanks in advance .....
My Code is written in the following to make things more clear and be useful for others and to get the right answer:
The first file
showCarData.php File (Saved as ANSI PHP File)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript" /></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCarType').change(function ()
{
$('#selectCarModel option').remove();
$.ajax(
{
url: "getCarModels.php",
dataType: 'json',
data: { CarType: $('#selectCarType').val() },
async: true,
success: function(result)
{
//var x = eval(result);
$.each(result, function(key, value) { $('#selectCarModel').append('<option value="' + key + '">' + value + '</option>'); } );
}
});
$('#selectCarModel').show();
});
});
</script>
</head>
<body>
<select id="selectCarType">
<option value="0" selected="selected">select car type</option>
<?php
//Connecting To The Database and getting $conn Variable
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarTypes = "SELECT DISTINCT CarTypeID AS CarTypeCode, CarTypeDesc AS CarTypeName FROM tableCarTypes ORDER BY CarTypeDesc ASC";
$rsCarTypes = odbc_exec($conn,$sqlCarTypes);
if (!$rsCarTypes)
{
echo "<option class='CarType' value='n' >Not Available</option>";
}
else
{
while ( odbc_fetch_row($rsCarTypes) )
{
//Assigning The Database Result Set Rows To User-Defined Varaiables
$CarTypeCode = odbc_result($rsCarTypes,"CarTypeCode");
$CarTypeName = odbc_result($rsCarTypes,"CarTypeName");
//Creating the options
echo '<option class="CarType" style="color:#060;" value="'. $CarTypeCode . '"';
echo '>' . $CarTypeName . '</option>' . "\n";
}
}
odbc_close($conn);
?>
</select>
<select id="selectCarModel">
<option value="0" selected="selected">select car model</option>
</select>
</body>
</html>
and the other file is
getCarModels.php File (Saved as ANSI PHP File)
<?PHP
//determine the Characterset
header('Content-Type: text/html; charset=windows-1256');
//Recieve CarType variable
$CarType = $_GET['CarType'];
// initialize an array that will hold the rows
$result = array();
if ($CarType != Null)
{
//Connecting To The Database and getting $conn Variable
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarModels = "SELECT DISTINCT CarModelID AS CarModelCode, CarModelDesc AS CarModelName FROM tableCarTypes WHERE CarTypeID='$CarType' ORDER BY CarModelDesc ASC ";
$rsCarModels = odbc_exec($conn,$sqlCarModels);
if ( $rsCarModels )
{
while ( odbc_fetch_row($rsCarModels) )
{
$CarModelCode = odbc_result($rsCarModels,"CarModelCode");
$CarModelName = odbc_result($rsCarModels,"CarModelName");
$CarModelName = utf8_encode($CarModelName);
$result [$CarModelCode] = $CarModelName;
}
}
else
{
echo "No Data";
}
odbc_close($conn);
}
//send the result in json encoding
echo json_encode($result);
?>
I hope this clear what I asked about and that any one could help me finding where is the error or the thing I miss to get the output in a proper format instead of the strange symbols and characters that could not be read as it shows in the second dropdown list.
Thanks in advance
What I do in such scenario is the following:
I construct the first dropdownlist on the server, with PHP while over the car categories from the database, for example. I place the id of the category as a value of the option. The resulting HTML should look something like this:
<select id="cars-categories">
<option value="1">Toyota</option>
<option value="2">Nissan</option>
<option value="3">Chevrolet</option>
...
</select>
Then on the page, with JavaScript, I listen for onchange event of the select and when occurs send the category id to the server
PHP code on the server picks the category id and makes a SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']. Send the result as JSON with json_encode
Finally, parse the returned data with JavaScritp and fill the model dropdownlist.
Here is what the client script basically can look like:
<script type="text/javascript">
$(document).ready(function() {
$('#cars-categories').change(function () {
$('#car-models option').remove();
$.ajax({
url: "get_data.php",
dataType: 'json',
data: { category: $('#cars-categories').val() },
async: true,
success: function(json){
$.each(json, function(key, value){
$('#car-models').append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
$('#car-models').show();
});
});
</script>
Encoding shouldn't be an issue.
EDIT: As requested by the author of the question, here is a simple way to get all the rows from the DB query and to send them back to the page as JSON encoded string.
<?php
// connect to DB
...
// initialize an array that will hold the rows
$rows = array();
// sanitize the category id. since it is an int, it is safest just to cast it to an integer
$cat_id = (int)$_GET['category'];
$result = mysql_query("SELECT id, name FROM `models` WHERE cat_id = $cat_id");
while($row = mysql_fetch_assoc()){
$rows[] = $row;
}
// do a regular print out. It is not going to the screen but will be returned as JavaScript object
echo json_encode($rows);
// you have to exit the script (or at least should not print anything else)
exit;
?>

Changing contents of HTML select based on dropdown

I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.

Categories