execute a php file on selection of dropdown value - php

i have been searching a solution for days and i have tried ajax/jquery methods posted online but it just wouldnt work. I have a drop down list which gets its value from the database. On selecting any value apart from "Select", i want to display a value which is called upon by a php file:
here's my code for the form:
<tr>
<fieldset id="Date">
<td class="select"><label><span class="text_9">Date:</span></label></td>
<td><select name="date" id="date">
<option value="">Select</option>
<?php include_once "selectdate.php"?></td>
</select>
</tr>
</fieldset>
</table>
and here's the php to run on selection of the drop down (called retrieve.php)
<?php
include_once "connect.php";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$form=$_GET;
$trade=$form['tradetype'];
$metal=$form['metal'];
$amount=$form['amount'];
$date=$form['date'];
$stmt = $conn->query("SELECT Discount FROM Contracts WHERE Trade='$trade' AND Metal='$metal' AND Amount='$amount' AND ExpiryDate='$date'");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo ($row['Discount']);
}
?>
As you can see, the php to be run uses the value from multiple form elements...
I am very new to jquery/ajax... any help is appreciated as i want the result to be displayed on the same page as the form is. Thank you!

If you want to get data from another file to a select, you should add as option. Plain text inside select will not help you out. So wrap the vales with <option></option>
So change this line,
echo "<option>{$row['Discount']}</option>";
If you want to give values,
echo "<option value='{$row['Discount']}'>{$row['Discount']}</option>";
EDIT
Now onchange of deopdown, date call ajax to do next stuff.
$(document).on("change","#date",function() {
var tradetype = //capture the value here;
var metal = //capture the value here;
var amount = //capture the value here;
$.ajax({
url:"path/filename.php",
data:{date:$(this).val(),"tradetype":tradetype,"metal":metal,"amount":amount},
type: "POST",
success: function(data){
alert(data);//this will alert what you have echoed on php file
}
});
});

Related

Get database value based on another input field

I've been searching for this kind of problem and I couldn't find one. I am using ajax to solve this problem but it didn't work out. I really want to have this scenario where after the user scanned his/her QR code, its data (account ID) will be in the input field. Then the other input field will automatically show its corresponding data from the database based on the data from QR code. This is so far my code.
This is from the main page:
<label id="acc">Account ID
<input type="text" name="accId" id="accID" class="idnum" required="" value="">
</label>
<label id="label">QR ID
<input type="text" readonly=" " name="qrId" id="qrId" style="width: 108px;margin-right: 15px;" value="" >
</label>
Ajax:
<script>
$("#accID").change(function() {
var accID = $(this).val();
$.ajax({
url: 'loadata.php',
type: 'POST',
data: 'accID='+accID,
success: function(html) {
$("#qrId").html(html);
}
});
});
</script>
this is the loadata.php:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
while($rows = $sel_run->fetch_assoc())
{
?>
<input type="text" readonly=" "id="qrId" name="qrId" style="width: 108px;margin-right: 15px;" value="" >
<?php
}
}
}
?>
Thank you very much for your time! :)
Are you getting any data to return? Have you tried changing your input field in loadata.php to a div with the same ID? Right now you're trying to place an input within an input.
Also, you don't need to wrap your inputs within the label. As long as the label and input share the same ID, they will always be together. Currently, you are not doing that.
Setting $("#qrId").html(html); will do nothing, as #qrId is an input field. I think, what you want to do is to set the value of the input field.
This should work like this: $("#qrId").val(html);
Then, there is a second problem as your PHP script returns HTML of an input field rather than just the value to set. Also, it may return multiple values as you loop through the database results.
You could try to change your script to something like this to just return the value of the first selected database record. Replace qrCodeValue with the real column name to use:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
$row = $sel_run->fetch_assoc();
print $row['qrCodeValue'];
exit;
}
}
?>

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);

Using jquery how do I pass a url query string to another php file?

I'm trying to pass the selected value of a autocomplete combobox uisng jquery-ui, now what I want to do is on the selection change event of the combobox I want to pass the selected value to a query string so that I could have a php file that will have something like this $_SESSION['mysession'] = $_GET['TheValue'];
Here's my current code:
change: function( event, ui ) {
//$.get('save_session_var.php', {supplier_id: $(this).val});
//document.location.href("localhost:90/PurchaseOrder3/save_session_var.php");
//alert($("#combobox").attr("value"));
if($("#combobox").attr("value") !== "")
{
$("#SupplierId").val($("#combobox").attr("value"));
alert($("#combobox").attr("value"));
$("#items").empty();
$("#items").append('<a id="AddLink" href="#">Add Item</a>');
if(!$("#items").has('a #AddLink'))
{
$("#items").append('<a id="AddLink" href="#">Add Item</a>');
}
}
<body>
<form method="post">
<p>Choose Supplier:<select name="SupplierDDL" id="combobox">
<option value=""></option>
<?php include 'loadSuppliers.php'; ?>
</select><p>
<input name="" type="hidden" value="" id="SupplierId">
<div id="items"><p>asdasd</p></div>
<input name="id" type="submit">
</form>
I tried using the ff but it didn't work:
$.get('save_session_var.php', {supplier_id: $(this).val});
$.get('save_session_var.php', {supplier_id: $("#combobox").attr("value"));
Here's also my code for the php file I created 'save_session_var.php':
session_start();
$_SESSION['supplier_id'] = $_GET['supplier_id'];
I've been stuck with this problem for almost the whole day. My only goal is just to be able pass the selected value and create a session variable.
Sir/Ma'am your answers would be of great help and be very much appreciated.
Use ui.item.option to get the underlying <option> element.
$.get('save_session_var.php', {
supplier_id: ui.item.option.value
});
Or use ui.item.value to get the selected option's text.
Would this work?
Edit: this works for me.
var yourVar = "I saved it again!";
$.ajax({
type: "GET",
url: "save_session_var.php",
data: 'suplier_id=' + yourVar,
cache: false,
success: function(text){
alert(text);
}
});
PHP FILE:
<?php
session_start();
$_SESSION['test'] = $_REQUEST['suplier_id'];
echo "THIS IS WHAT YOU GET: " . $_SESSION['test'];
?>
I was able to make it work by using the following code:
var selectedId = $("#combobox").val().toString();
$.get("save_session_var.php", {supplier: selectedId} )

Search and Insert multiple values selected in textbox into MySQL

I'm doing something in PHP which displays all the data let's say animals table for easier understanding. Now I have a kingdom table where all of the animals that falls into their respective kingdoms. Now In my Page I displayed two tables: Those animals who falls into the Kingdom I logged in (given Animalia) and Those who dont.
In those animals who are not part of the Kingdom Animalia there is a checkbox besided each names where I can select one or more names. Now I have an add button to serve as the trigger to add those animals I selected to be assigned in Kingdom Animalia.
Now it becomes a zoology class, sorry for the sample but I think I can explain in much better this way.
To add, as much as possible I wanted my code to be limited in using javascript and php codes only since I'm not used in working with jQuery.
From what i understand....
Post a checkbox with each of your table records along with your form
<!--non assigned table-->
<table id="non-table">
<tr id="nonassignedid">
<?php foreach($nonassigneddata as $data){ ?>
<td>....</td>
<?php } ?>
<tr>
</table>
<!--assigned table-->
<table>
<tr id="assignedid">
foreach($yourresults as $result){
<td>...</td>
<?php
$check = someFunctionToCheckAssigned($result,$youruserId);
if($check){
$checked = "checked='checked'";
}else{
$checked = "";
}
?>
<td><input type="checkbox" userid="<?php echo $userid; ?>" assigningproperyid="<?php echo $assignid; ?>" name="both" class="updateuser" <?php echo $checked ?> /></td>
}
</tr>
</table>
Using Jquery Ajax method
$(".updateuser").click(function(){
var userid = $(this).attr('userid);
var propertyid = $(this).attr('assigningproperyid'); //what ever thing you want to assign
$.ajax({
url: 'updateuser.php,
type : "POST",
data : {'userid':userid ,'propid':propertyid },
success: function( data ) { //return the data as assigned element id
$('#non-table #data).remove(); //removing that tr from non -assinged
}
}
});
})
According to my understanding of the question...in the not assigned table i'm presuming that you have a checkbox besides a user name who is not assigned(linked) to our current user..
Now, add a button next to that new user's name to be assigned to our user.
Trigger the onclick event on that button using jquery on just javascript.
function adduser(){
var elems = $(".Checkbox");
for(var i=0;i<elems.length;i++)
{
if(elems[i].checked){
var userId = elems[i].id;
$("#dummy").load("adduser.php?user_id="+userId,function(){
$("#"+userId).parent().remove();
});
}
}
$("#dummy").html("succesfully Added selectd users to your account.");
}
In the file adduser.php write the code for adding a user to the current user.

jquery add table row with json data in dropdowns

I have a web form with a table that the user can add additional rows to. The first row of the table consists of dependent dropdowns. The dropdowns are populated with json data from a referenced file. The code that I am using for it is as follows:
//the add row function
$(function(){
var newgroup = $('<tr>').addClass('rec-rows');
$('#addRow').click(function(e){
e.preventDefault();
$('.rec-rows').first().clone().appendTo(newgroup).appendTo('#details'); });
});
//onChange function
$(".rec-rows #section").live('change',function(){
var sSec =$(this).parent().find('#section').val();
$("#divParts").hide();
$("#divDesc").hide();
$("#divGroup").hide();
if(sSec=="select") {
$("#divCategory").hide();
} else {
$.getJSON("static/site_category.json", function(json) {
var catJson = json[sSec];
var options = "<option value=\"select\">Select Area Type</option>";
for(i=0;i<catJson.length;i++) {
options +="<option value=\""+catJson[i].ky+"\">"+catJson[i].val+"</option>"
}
Theoretically, a new row is added and the onChange code I pasted will work for each additional row. However, the results are not like that at all. Instead, when the row is added and the user makes a selection on the new row, the values are updated in the first row.The first part of the table looks like this:
<td width="" align="left">
<div>
<select id="section" name="section" style="margin-top:15px;">
<option value="select">Select Area</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</div>
</td>
I appreciate any help to get this code working as desired - which would be a simple added row where the dropdown selections only update on the row that they are found on. Thank you.
you can look at my answer here of how to add a row dynamically to the start of a table:
How can I dynamically generate a table row with it's tds?
It might help you here.
or i also i see a problem.
change $("#section").change(
to:
$("#section").live('change',...
that could be why the new dropdowns are not working
Got the solution! I was advised to declare the parent such as in the following context:
$(".section").change( function () {
var sSec =$(this).val();
context = $(this).parents("tr");
if(sSec=="select") {
$("#divCategory", context).hide();
} else {
$.getJSON("static/site_category.json", function(json) {
var catJson = json[sSec];
var options = "<option value=\"select\">Select Area Type</option>";
for(i=0;i<catJson.length;i++) {
options +="<option value=\""+catJson[i].ky+"\">"+catJson[i].val+"</option>"
Now for every "add row" click, a row gets added and the dropdowns are changed upon user selection for that row and only that row.

Categories