Change PHP variable with HTMLs <select> <option> OnChange and execute mysql query - javascript

Hi I currently have 2 < select>
The first one is filled from a button action from the page before and a database query. Depending on what you choose in the first < select>, the second < select> should get filled from a database query with the value of the first < select>. (I am using PDO prepare so I only need to change the parameter to whatever value the selected has)
I already know how I can get the values into javascript but I don't know how I can then write it into the php variable and execute the mysql query. As javascript is a client-side language, I don't think it's possible to execute the query there so I would need to get it to php somehow?
Select 1:
<select name = "select1" class = "select" size = "10" onChange = "function()">
<?php
while ($result1 = $query1->fetch(PDO::FETCH_OBJ)) {
?>
<option value = "
<?php
echo $result1->id;
?>">
<?php
echo $result1->text;
?>
</option>
<?php } ?>
</select>
Select 2:
<select name = "select2" class = "select" size = "10" onChange = "function(this.options[this.selectedIndex].value)">
<?php
while ($result2 = $query2->fetch(PDO::FETCH_OBJ)) { ?>
<option value = "
<?php
echo $result2->id . ";" . $result2->text . ";" . $result2->text2 . ";" . $result2->text3;
?>">
<?php
echo $result2->text;
?>
</option>
<?php } ?>
</select>
If you are curious, function is just displaying some divs and writing the values into some textboxes:
var str = select.split(";");
document.getElementById("div1").className = "";
document.getElementById("div2").className = "div";
document.getElementById("div3").className = "div";
document.getElementById("div4").className = "div";
document.getElementById("txt1").value = str[0];
document.getElementById("txt2").value = str[1];
document.getElementById("txt3").value = str[2];
document.getElementById("txt4").value = str[3];
php database query to fill select 1:
try {
$query1 = $db->prepare('SELECT id, text FROM tbl1 INNER JOIN tbl0 USING(id) WHERE id = ?');
$query1->execute(array($_POST['id']));
} catch(PDOException $ex) {
log_error($ex);
$arrError[] = "Error SQL 1";
}
php database query to fill select 2:
try {
$query2 = $db->prepare('SELECT id, text, text2, text3 FROM tbl1 INNER JOIN tbl2 USING(id) WHERE id = ?');
$query2->execute(array($IDFROMSELECT1));
} catch(PDOException $ex) {
log_error($ex);
$arrError[] = "Error SQL 2";
}
How can I get the id (option value) from select 1 into the $IDFROMSELECT1 variable in php mysql query 2?
Any tips are much appreciated!

You will have to use AJAX to send the value of the select box to a PHP script which will run the query and send back the result. AJAX is easiest done with the jQuery library.
The javascript to run in onchange() would be something like this:
var selectedValue = $(this).val();
$.ajax({url: "getData.php",
type: "POST",
dataType: "json",
data: {id: selectedValue},
success: function(returnedData) {
//do something here with returned data
}
});
In the PHP script (getData.php), you would execute your select like normal, put the results into an array, then return that array as JSON (Javascript Object Notation). This will put the results of the query into a format that you can work with in javascript (in this case, adding the returned results to another select box)
$json = json_encode($returnArray);
echo $json;

Related

Search form using ajax, php and json

i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>

PHP - When a checkbox gets checked send a request to run a query on the database

So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers

Get value from select box through ajax to mysql

I have a select box where i pass the value through ajax to a mysql statement.
I need to make it a bit more intelligent, so i dont have to hardcode all the values from the select box
The HTML select box is:
<select>
<option value="value1">something</option>
<option value="value2">somethingElse</option>
</select>
I pass the value through ajax with:
var opts = [];
$selectboxes.each(function(){
opts.push($(this).val());
})
In my php file i use the value to filter a SQL select statement:
if (in_array("something", $opts)){
$where .= " AND region = 'something'";
}
If the user selects option 1 with the value value1 the php file should change to something like
if (in_array("VALUE1", $opts)){
$where .= " AND region = 'VALUE1'";
}
Use the IN option of where and array_intersect to select only the values that we find in $isarray
$isarray= array("something","somethingElse",....)
$is = array_intersect($ops,$isarray)
$where .= " AND region IN ".$is
Note: properly sanitize your $opts so you don't have sql injection
If you have multiple values in something variable then you probably store those values in an array and using array_intersect you can achive desired result.
<?php
$opts = Array ('value1','value2','value3','value4'); //select box values which your are passing from ajax call
$somethingArray = Array('something', 'value1','value4'); //value that you need to match / compare
$result = array_intersect($opts, $somethingArray);
$where = '';
foreach ($result as $key => $value) {
$where .= " AND region = '".$value."'";
}
echo $where; //Output=> AND region = 'value1' AND region = 'value4'
?>

PHP, AJAX, and server-client frustrations

I have a table that's generated from php. The way I've done this is probably not the most efficient way to do it since I wrote it all myself and I'm not an expert.
Everything starts when the user pastes part numbers into a search box on a previous page, which is then sent here to return.php under the variable lines.
return.php
$c = $_POST['c'];
if (!$_SESSION['lines']) {
$_SESSION['lines'] = $_POST['lines'];
}
$partNumber = array(); //define $partNumber as array
$x = -1;
$supplierQuery = "SELECT distinct supplier, quotePartNumber FROM allparts WHERE quotePartNumber = '$q'" ;
$supplierResult = mysqli_query($con, $supplierQuery);
foreach ($_SESSION['lines'] as $q) {
$x = $x + 1; // each time we loop through this, x++
while ($row = mysqli_fetch_array($supplierResult)) {
$partNumber[] = $row['quotePartNumber'];
$customerQuery = "SELECT DISTINCT quoteCustomer FROM $supplier where quotePartNumber = '$q'";
if (!$c) { // $c becomes set once a user types in an end customer - without that, we want ALL generic info to be returned.
$costQuery = "SELECT * FROM $supplier where quotePartNumber = '$partNumber[$x]' ORDER BY quoteCost ASC LIMIT 1" ;
} else {
$costQuery = "SELECT * FROM $supplier where quotePartNumber = '$partNumber[$x]' and quoteCustomer = '$c' ORDER BY quoteCost ASC LIMIT 1" ;
}
$getCustomer = mysqli_query($con, $customerQuery);
}
later on in my table, I have this:
<td><?= $partNumber[$x] ?></td>
<td><?= $cost ?></td>
<td>
<select class="btn btn-danger" onChange="selectCustomerCMR(this.value)">
<option value="" disabled selected><?php if($c) { print $c; } else { print "Select Purchasing Customer";} ?></option>
<?php
while ($row = mysqli_fetch_array($getCustomer)) {
$customerName = $row['quoteCustomer'];
?>
<option><?= $customerName ?></option>
<?php
}
?>
</select>
</td>
Any change to the dropdown will launch this script:
<script>
function selectCustomerCMR(str) {
var id = str;
$.ajax({
type: 'POST',
url: 'return.php',
data: {'c':id,'lines':lines},
success:function(data){
$("#info").html(data);
}
});
}
</script>
What I'm trying to do
Let's say my generated table has 3 rows, with part numbers
There is a drop-down to allow the user to select a specific customer. When the user clicks on this, the script takes that value and uses AJAX to send it back to the same page (return.php), which then grabs it using the $c = $_POST['c']; code.
My Issue
When return.php loads a "second time" with a value for $c, I don't know how to make it so that the line that the user selected gets changed. Right now, anytime I select a customer from a line's drop-down, return.php reloads, and it assigns that customer to the FIRST row, ignoring all the other rows.
I specifically created $partNumber as an array and used $x so I could increase the value of x each time the foreach loop iterated. This worked, so of the three lines in the above table, the first one is $partNumber[0] and the second one is $partNumber[1], etc... But I don't know how to get that information into the javascript function and send it back to the page when it reloads, so that I can then change my SQL query to ONLY action when the condition is right for that line...
Thanks for reading, and thanks for any help!
Consider changing your <select> code to this:
<select class="btn btn-danger" data-x="<?= $x ?>" onChange="selectCustomerCMR(this)">
Then, your Ajax code can be changed to this:
function selectCustomerCMR(select) {
var id = select.value, x = select.getAttribute("data-x");
$.ajax({
type: 'POST',
url: 'return.php',
data: { c: id, lines: lines, x: x },
success: function(data){
// Update!
}
});
}
That way, your PHP can get both c and x.

PHP populate drop box with jquery

I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);

Categories