How to use the value of input fields in an if statement - php

I have two input fields. One is to search auto suggest product names using jquery.autocomplete, and in my database I have column name product left, and I want to display it in the second input, is that possible?
For example: I have a product called apple with product left of 30. apple will display in the first input field after typing, and at same time 30 must appear in the second field.
<form action="sales.php" method="post">
<input name="productlist" type="text" id="productlist" size="20"/>
<input name="productleft" type="text" value=""/>
</form>
call jquery ui
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#productlist").autocomplete("psuggest.php", {
selectFirst: true
});
});
</script>
inside psuggest.php
<?php
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','root','','saganatracker') or die("Database Error");
$sql="SELECT pdesc FROM products WHERE pdesc LIKE '%$my_data%' ORDER BY pdesc";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['pdesc']."\n";
}
}
?>

Use parameter onselect from .autocomplete() to bring the number of item left :
$(document).ready(function(){
$("#productlist").autocomplete("psuggest.php", {
selectFirst : true,
onselect : function(value, data) {
$.post("myPhPfileWhichBringNumberOfItem.php", { product : value }, function(count) {
$("#productleft").val(count); // Don't forget to mention an id for the input first
}
}
});
});
Use JQuery post at the moment a value is selected, and then use a php script which open your database, go to the table and select number of product left (not sure if you should use value or data, please someone correct if I am wrong).

Related

Populate form based on selected item php

I have a page with a select list (gets successfully populated from mysql) and a text box. The text box has to be populated with a value from mysql based on the item selected in the list. But the ajax call to php is not working and i can not figure out what the issue is. I am just learning ajax and php, so a novice.. Please help. i am stuck with this for a long time.
<script>
$(document).ready(function() {
$('.selectpicker').on("change", function(){
var selected_data = $(this).find("option:selected").val();
alert(selected_data);
$.ajax ({
type: "POST",
data: { selected_data: selected_data },
url: "getoldcharity.php",
dataType: "json",
success: function(res) {
$('#charity_new').val(data.charity_new);
}
});
});
});
</script>
<form id="assign-fundraiser_form" class="form-horizontal" action="" method="post">
<div class="form-group">
<div class="col-md-3">
<select class="selectpicker form-control" id="fundraiser" name="fundraiser" required>
<option value="" selected disabled>Select a Fundraiser</option>
<?php
include('session.php');
$result1 = mysqli_query($db,"select concat(f_firstname,' ',f_lastname) fundraiser from fundraiser where f_company in (select contractor_name from contractor where company_name = '$_SESSION[login_user]') and f_status = 'Active' order by concat(f_firstname,' ',f_lastname)");
while ($rows = mysqli_fetch_array($result1))
{
echo "<option>" .$rows[fundraiser]. "</option>";
}
?>
</select>
</div>
</div>
<input type="text" name="charity" id="charity_new" />
</form>
<?php
include "session.php";
if (ISSET($_POST['.selectpicker'])) {
$ref = $_POST['.selectpicker'];
$query = $db->query("select f_charity charity_new from fundraiser limit 1");
$row = $query->fetch_assoc();
$charity_new = $row['charity_new'];
$json = array('charity_new' => $charity_new);
echo json_encode($json);
}
$db->close();
?>
There are a few problems that I've spotted from quick glance, so I've separated them below.
PHP
In your AJAX request, you are using data: { selected_data: selected_data } which means the PHP code will be expecting a POSTed key named selected_data but you're looking for .selectpicker. You seem to have mixed up a couple of things, so instead of:
$_POST['.selectpicker']
it should be:
$_POST['selected_data']
JavaScript
As Ravi pointed out in his answer, you also need to change your success function. The parameter passed through to this function is res not data, so instead of:
$('#charity_new').val(data.charity_new);
it should be:
$('#charity_new').val(res.charity_new);
MySQL
It also appears as though your query itself is invalid - you seem to be missing a comma in the column selection.
select f_charity charity_new from fundraiser limit 1
should be:
select f_charity, charity_new from fundraiser limit 1
or, seeing as you're not using the f_charity column in the results anyway:
select charity_new from fundraiser limit 1
You aren't using the value that is being POSTed either, meaning that whatever option is selected in the dropdown makes no difference to the query itself - it will always return the first record in the database.
Other
One other thing to be aware of is you're using a class selector on your change function. This means if you have multiple dropdowns with the same class name in your HTML, they will all be calling the same AJAX function and updating the textbox. I don't know if this is what you're aiming for, but from your code posted, you only have one dropdown in the form. If you only want that one dropdown to be calling the AJAX function, you should use an ID selector instead:
$('#fundraiser').on("change", function() {
// ...
}
I think, it should be
$('#charity_new').val(res.charity_new);
instead of
$('#charity_new').val(data.charity_new);

Need PHP dropdown with result shown in text box

I am using php and getting data from mysql. I would like to have a dropdown of countries and then when the country is selected then the prefix must be the result either in a text box on the same line or just below the dropdown box.
so far my code gives me the prefix concatenated with prefix eg
Zimbabwe-263
here is the code
<?php
include 'config.php';
$query="SELECT countryname, countryprefix FROM cc_country";
$result = mysql_query($query);
$options="";
echo "<select name='processor' value=''>
<option>Select A Country</option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value='".$nt['countryprefix']."'>".$nt['countryname']."-".$nt['countryprefix']."</option>";
}
If you want the selected value to display in textbox you can use jquery for that.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<sctipt>
$('select').change(function(){
var value=$(this).val();
$('#text').val(value);
});
</script>
Create a textbox with id text for this
You will need to fire another query that will fetch the country prefix on selection of the country.That is pass the value of your select box to he sql query.You can do this using jquery or javascript by giving an id to the select box you are using .
var countryname = $('#yourId').val();
then do a ajax or jquery post to a PHP file which will have the blow query.
For example:
$query="SELECT countryprefix FROM cc_country where countryname='your post value";
then below your while loop add a text field which will display the value returned by your above query
$('select').change(function(){
var value = $(this).val();
$('.textbox').val(value); // html <input type="text" class="textbox">
});

Autocomplete text input in reference to the value of another text input

I have two fields, one of which has the jQuery autoComplete plugin.
<input type='text' name='primary_diagnosis' id='icd1-diagnosis'/>
<input type='text' name='ICD_No1' id='icd1-num' />
$(document).ready(function(){
$("#icd1-diagnosis").autocomplete("autocomplete-icd.php",
{
selectFirst: true
});
});
Is there a way to automatically fill up the second text input once a value has been selected for the first? For example, selecting "Dengue fever [classical dengue]" for the first text input, then query the database for certain value to yeild "A90" as the value for the second text input.
Here's autocomplete-icd.php
<?php
include('config.php');
$q=$_GET['q'];
$my_data=$q;
$sql=mysql_query("SELECT col9 FROM tb_data_icd WHERE col9 LIKE '%$my_data%' ORDER BY col9",$con);
if($sql)
{
while($row=mysql_fetch_array($sql))
{
$col9=$row['col9'];
echo "$col9"."\n";
}
}
?>
You should be able to use the change event to fire off some javascript to update the second input's value. Something like this:
$("#icd1-diagnosis").change(function(){
//retrieve your value
var val = 'sample';
$('#icd1-num').val(val);
});

query for selected checkboxes

Im having two pages search.php and load.php...in search.php i have checkboxes and im using jquery for passing checkboxes to load.php
<div class="checkBoxes">
<input type="checkbox" name="art[]" value="1" >Digital Art <br />
<input type="checkbox" name="art[]" value="2" >Traditional Art <br />
<input type="checkbox" name="art[]" value="3">Photography <br />
</div>
<script language="javascript">
$(document).ready(function(e) {
$(".btn_advancedsearch").click(function(){
$('#content').fadeIn(1500);
$("#content").load("/search/advancedsearch.php?type="+ $("[name='type']:checked").val()+"&category="+$("input[type='checkbox']").val());
window.scroll(0,0);
});
});
</script>
In load.php im using $category=$_REQUEST['category']; and now i want to write query for getting all selected category from checkboxes but i dont know how...i tryed this query but its not working $sql = "SELECT * FROM art WHERE categoryID IN (implode(',', $category))";
This is because $("[name='type']:checked").val() will return you array object and you cannot pass this directly as a query string parameter. Do the following steps
1. Fetch the selected checkbox values and make them comma separated in a variable (with single quote so use can directly use in the query) _eg. '1','2','3'
2. Pass this value via query string
3. Use this value in your select query -- As you're using in operator so you can directly feed this value as select * from table name where col in (valueYouReceived)
Code:
Somewhere in JS -- When you click on the button $(".btn_advancedsearch").click(function(){
...
...
var selectedValues = "'";
$('input[type=checkbox]').each(function() {
if($(this).prop('checked'))
{
selectedValues += $(this).val()+"',";
}
});
selectedValues = selectedValues.substring(0, selectedValues.length-1); // To remove last comma (,)
Just "alert()" the value and see what you get alert(selectedValues)
Now Pass this variable as a query parameter
$("#content").load("/search/advancedsearch.php?type="+selectedValues+"&category="+$("input[type='checkbox']").val());
At the php part get the value as you're getting it
$category=$_REQUEST['category'];
Use this value in your sql query
"SELECT * FROM art WHERE categoryID IN ($category)";
Hope this helps!!
Ok, found solution. I'm not sure for code but you can change and some put this:
jQuery(document).ready(function($) {
$(":checkbox").bind("click", function(event) {
if ($(this).is(':checked')) {
var checked = $(this).val();
$(".btn_advancedsearch").hide();
$("#content").load('/search/advancedsearch.php?type=' + checked);
$('#content').fadeIn(1500);
window.scroll(0,0);
}
});
});​

Dual select box not POSTing correctly

I'm still trying to learn jquery so bear with me. I have a dual select box that only works if I select all the results of the second select box after I move them there. What I want is when the first box transfers values to the second second select box, it doesn't require highlighting the options, but posts that second select box on form submit. Here is what
I have:
HTML:
<span id="dualselect1" class="dualselect">
<select name="select1[]" multiple="multiple" size="10">
<?php
$c='0';
foreach($lp_name as $lpn){
echo '<option value="'.$lp_id[$c].'">'.$lpn.' ('.$lp_url[$c].')</option>';
$c++;
}
?>
</select>
<span class="ds_arrow">
<span class="arrow ds_prev">«</span>
<span class="arrow ds_next">»</span>
</span>
<select name="select2[]" multiple="multiple" size="10">
<option value=""></option>
</select>
</span>
JQUERY:
<script type="text/javascript">
jQuery(document).ready(function(){
var db = jQuery('#dualselect1').find('.ds_arrow .arrow'); //get arrows of dual select
var sel1 = jQuery('#dualselect1 select:first-child'); //get first select element
var sel2 = jQuery('#dualselect1 select:last-child'); //get second select element
sel2.empty(); //empty it first from dom.
db.click(function(){
var t = (jQuery(this).hasClass('ds_prev'))? 0 : 1; // 0 if arrow prev otherwise arrow next
if(t) {
sel1.find('option').each(function(){
if(jQuery(this).is(':selected')) {
jQuery(this).attr('selected',false);
var op = sel2.find('option:first-child');
sel2.append(jQuery(this));
}
});
} else {
sel2.find('option').each(function(){
if(jQuery(this).is(':selected')) {
jQuery(this).attr('selected',false);
sel1.append(jQuery(this));
}
});
}
});
});
PHP:
if(isset($_POST['submit'])) {
var_dump($_POST['select2']);
}
Like I said, I have this sort of working. But, if I send a value to select2, I have to highlight it before I submit or else it wont POST. Any ideas?
I've come across this before and you have a couple of options. Using JS you can either push all of the values in the second box into a hidden field as well, or also using JS you can select all of the values in the second box as an onsubmit handler on the form.
I've actually done the latter before, and it works just fine.
Ultimately, a select box (multi or single select) only sends the values that are selected -- so that's why it only works if you select them first. It works a lot like checkboxes do, where the unchecked values just don't get posted.
This should "select" all of them:
$('#myform').submit(function() {
var sel2 = $('#dualselect1 select:last-child');
sel2.find('option').each(function(){
$(this).attr('selected',true);
});
});
OR this would put them into a series of hidden fields:
$('#myform').submit(function() {
var sel2 = $('#dualselect1 select:last-child');
sel2.find('option').each(function(){
var hidden = $('<input type="hidden" name="selectedOptions[]"/>');
hidden.val($(this).val());
sel2.after(hidden);
});
});
and then in PHP you'd get these values by using $_POST['selectedOptions'];
You can simply modify this line jQuery(this).attr('selected',false); in sel1.find....block
with jQuery(this).attr('selected',true); .
In this mode al selection moved from first to second box is automatically selected,
so when you submit form, you directly pass this value.
Try it.
this should work:
if(t) {
sel1.find('option').each(function(){
if(jQuery(this).is(':selected')) {
jQuery(this).attr('selected',true);
var op = sel2.find('option:first-child');
sel2.append(jQuery(this));
}
});
}

Categories