Get value from select box through ajax to mysql - javascript

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'
?>

Related

how I can get the ID of the selected option from a dynamically created dropdown using PHP, or Jquery?

I use this code in fetching the data from the database.
$result = $con->query("SELECT firstname,lastname FROM employee");
And then render like bellow:
<select name="employees">
<option value="">Select Employee</option>
<?php while ($rows = $result->fetch_assoc()) {
$employee_name = $rows['firstname'] . " " . $rows['lastname'];
echo "<option id = emprecord_id value = '$employee_name'>$employee_name</option>";
}
?>
</select>
I need to know how can I get the ID (or if there is anyway) of the selected value because I will insert values for the selected option in another table.
Like i get the data from the employee table and If the Name of the employee was selected, it will proceed to another page we're I will insert new data for its payroll.
You could access the selected option with selectedIndex :
let tSelectedIndex = document.querySelector('select[name=languages]').selectedIndex;
let tID = document.querySelectorAll('select[name=languages] option')[tSelectedIndex].id;

How to create an optimized sql query for multiple dropdown filtering in php?

Am new to php and working on a project. At the beginning there was 2 filters for which I didn't worry much in writing the sql query with 4 conditions. But now I've 8 different dropdowns and I need to write an optimized sql for filter functionality. As per conditions to be written counted, I need to write 256 conditions which is the worst idea at all.
Here the problem is, there is no mandatory filed to choose for filtering. This giving me the more problem in applying different approaches.
Is there any other alternative to achieve this issue? what would be the best idea for optimized query.
Example Code
if($_REQUEST['action']=='action_report'){
$v1 = $_POST['v1'];
$v2 = $_POST['v2'];
if(!empty($v1) && !empty ($v2)){
$sql = "SELECT * FROM TABLE WHERE v1=$v1 AND v2=$v2 AND action='action_report'";
}elseif(!empty($v1) && empty($v2)){
$sql = "SELECT * FROM TABLE WHERE v1=$v1 AND action='action_report'";
}elseif(empty($v1) && !empty($v2)){
$sql = "SELECT * FROM TABLE WHERE v2=$v2 AND action='action_report'";
}elseif(empty($v1) && empty($v2)){
$sql = "SELECT * FROM TABLE WHEREAND action='action_report'";
}
}
The code would look like this:
$sql = 'SELECT * FROM TABLE WHERE ';
$first = true;
foreach($_POST as $paramName => $value) {
if ($first) {
$sql .= "{$paramName}='{$value}'";
$first = false;
continue;
}
$sql .= " AND {$paramName}='{$value}'";
}
Since the $_POST is an array of the incoming variables you can go through on it with a simple foreach cycle and attach it to the SQL query string. The first possible parameter wont need an AND operator, so you have to handle it differently, that's why the $first variable is for.
However this code is has SQL injection vulnerabilities, so it's better to attach the parameter name and the value to the SQL string like this:
$sql .= ' AND ' . mysqli_real_escape_string($connection, htmlspecialchars($paramName)) . "='" . mysqli_real_escape_string($connection, htmlspecialchars($value)) . "'";
You will also receive empty values, you wouldn't like to attach to the SQL query string. So the final code needs to handle that too, and after a bit of formatting it would look like this:
$sql = 'SELECT * FROM TABLE WHERE ';
$first = true;
foreach($_POST as $paramName => $value) {
$protectedParamName = mysqli_real_escape_string($connection, htmlspecialchars($paramName));
$protectedValue = mysqli_real_escape_string($connection, htmlspecialchars($value));
if (empty($value)) {
continue;
}
if ($first) {
$sql .= "{$protectedParamName}='{$protectedValue}'";
$first = false;
continue;
}
$sql .= " AND {$protectedParamName}='{$protectedValue}'";
}
In the example the $connection variable is a mysqli object:
$connection = new mysqli(
$dbConfig['host'],
$dbConfig['user'],
$dbConfig['password'],
$dbConfig['databaseName'],
$dbConfig['port']
);
The foreach($_POST as $paramName => $value) goes through on each $_POST array values, so if you would you don't want some fields to be used in the SQL query, then you can use blacklist filtering, where you specify if the $paramName is in the blacklist, then you wont attach it to the SQL query.
For example:
$blackList = [
'action'
];
foreach($_POST as $paramName => $value) {
if (in_array($paramName, $blackList)) {
continue;
}
}

How to send a variable to a parameter variable in a PHP function and return its value to javascript using AJAX

I know you cant just send information over to as one is client side and the other server side, but im asking how would I go about to do this.
I have a two dynamic select/option drop down which is echoed from PHP with HTML tags.
If first drop box is selected the second drop box will contain information relevant to the first drop box, for example first drop box (console) second drop box (ps4/xbox one) etc. All this information is stored to a database.
At the moment Im only using javascript to do all this as I manually enter the value to a script as below:
case "Christmas":
var opt = document.createElement("option")
opt.value = "Lanterns";
opt.innerHTML = "Lanterns";
sub.appendChild(opt);
var opt = document.createElement("option");
opt.value = "Hanging Decorations";
opt.innerHTML = "Hanging Decorations";
sub.appendChild(opt);
break;
PHP for gathering all the option for first drop box
while($row = $getQuery->fetch_array()){
$catName = $row['CAT'];
$option .= "<option value='$catName'>$catName</option>";
}
Echoing information to HTML
<select name="Cat" id="Cat" onchange="subCatActivation('')" onclick="realTimeChange(this.id)">
<option value="title">Main Category</option>
<?php echo $option?>
</select>
I have created a PHP function with a parameter that will have the values of the first drop box:
function getSubCat($mainCat){
$subOption = '';
$subName = [];
include"../storeSQL/sql_Connection.php";
$sql = "SELECT SUB_CAT FROM CATEGORIES WHERE CAT = '$mainCat' GROUP BY SUB_CAT";
$getQuery = $connection->query($sql);
$i = 0;
while($row = $getQuery->fetch_array()){
$subName[$i] = $row['SUB_CAT'];
$subOption .= "<option value='$subName[$i]'>$subName[$i]</option>";
echo " " . $subName[$i];
$i++;
}
return $subName;
}
I need now to call this function inside my javascript to do the similar validation as the above switch case. But im having trouble sending the information over and then receive return value of that function back.

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

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;

Populating a select box with JSON array results

So I'm trying to populate a select box within my html with array objects using JSON results, I've been looking at all this code so long I don't think I'm seeing the simple solution to my problem. This is my callback function where I'm populating the select box. The JSON request has went through fine but I am stuck with a blank select box everytime.
function getArtistsCallBack()
{
if (req.readyState == 4) {
if (req.status == 200) {
// TO DO: populate artistlist select box using JSON
var response = req.responseText.parseJSON();
var artistSelect = document.getElementById("artistlist");
for (i=0;i<response.artistsarray.length;i++){
var artist_id = response.artistsarray[i].artist;
var artist = response.artistsarray[i].artist;
artistSelect.options[artistSelect.options.length] = new Option(artist, artist_id, false, true);
}
}
}
}
Here is the select box within the HTML for reference just in case;
<div id="artistscontent">
<select id="artistlist"></select>
</div>
This is artists.php where a database is queried for an array of objects, the array that is used previously;
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
$artistsarray = Collection::GetArtists();
print json_encode($artistsarray);
$jsonresponse='{"artistsarray":[';
foreach($artistsarray as $artist => $row)
{
$artist_id=$artist+1;
$artist=$row['artist'];
$jsonresponse .= '"artist_id":"' . $artist_id . '"},';
$jsonresponse .= '"artist:"' . $artist . '"},';
}
$jsonresponse .= ']}';
echo $jsonresponse;
?>
Any help would be much appreciated! Thanks!
You need to use the json length for the options array and do it outside of the for loop. Then use options.add
var json = [{key:'1', value:'value1'},{key:'2', value:'value2'}]
var artistSelect = document.getElementById("artistlist");
artistSelect.options[json.length];
$.each(json, function(key, value){
console.debug(value);
artistSelect.options.add(new Option(value.key, value.value));
});
Check out this plunker:
http://plnkr.co/edit/i3A6mo672CskXvbstWsu?p=preview
The artistSelect.options is not an array, you need to use the add method:
var opt = new Option(artist, artist_id);
artistSelect.options.add(opt);

Categories