fill select box with javascript return array - javascript

I am in a big trouble. It's 2:45am and I have been since 6pm searching for ideas or examples or whatever you wanna name it!
I have this js function called from a but I can get it to work AT ALL.
The idea is type you city name and get suggestion in a select box. Than, from the select box you can click in one of the cities and this information going back to your form field.
There are two files: index.php (js function showhint and a form calling another .php file to load the cities as suggestions)
The code can be see at www.bfamily.net
I will be very great-full for any help.
Regards,

Add an event onchange on your select to set the value
function(inputName, event) {
document.getElementByName(inputName)[0].value = event.target.selectedOptions[0].value;
}
But I recomand you to do something like that on your inputs :
<input type="text" name="zipCode1" onkeyup="showHint(this.value)" size="20" value="" style="text-transform:uppercase" list="suggestion">
<datalist id="suggestion">
<option>Houston, TX 77070</option>
<option>Cypress, TX 77433</option>
<option>Cypress, TX 77429</option>
</datalist>
Of course you can either generate the datalist with PHP on the page load or with an AJAX request.

May be this will be helpfull
if (filter_var($q, FILTER_SANITIZE_STRING) || !filter_var($q, FILTER_SANITIZE_STRING) === false) {
if ($q !== "") {
$str = "<select name='suggestion'>";
$q = strtolower($q);
$len=strlen($q);
foreach($zipArray as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name.'<br/>';
} else {
$hint .= "$name".'<br/>';
}
$suggestion[] = $name;
$str .= "<option value='".$name."'>".$name."</option>";
}
}
$str .= "</select>";
if(count($suggestion) > 0) echo $str
}
}
But I think the better way is to have a hidden selectBox in your html and then send json "suggestions" list from .php to your .js file from Ajax and then there add proper options to your selectBox and make it visible

Related

Hidden div by Country code

I'm not a php-hero so, I try to hidden a section if the user not come from a specific country.
So I did this:
$.get("http://ipinfo.io", function (response) {
$("#country").html(response.country);
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
This work well and show me the country code (eg. IT).
Now I try to get this value and insert in a IF
$country = $_GET['country'];
$it = "IT";
<?php if ($country != $it): ?>
Code to hidden here...
<?php endif; ?>
What is it wrong here?
Change
$("#country").html(response.country);
to
$("#country").val(response.country);
Because php $_GET saves values.
Also I do not see a reason to do this:
$it = "IT";
<?php if ($country != $it): ?>
You can just do
<?php if ($country != "IT"): ?>
And last but not least you should not access $_GET directly. It is better to use function filter_input which in your case would be filter_input(INPUT_GET, 'country')
EDIT
I do not understand what is the hidden input for. But if you want to show or hide content depending on the country, and you get the country using ajax there is absolutely no need for this input.
Instead of making php condition (<?php if ($country != "IT")...) You can do it in js. Let's say that inside your condition there is a div with class content
Solution
Your html would look more or less like this
<div class="content">
<!-- Your content here -->
</div>
instead of php condition.
And in js you can do something like this
$.get("http://ipinfo.io", function (response) {
if (response.country == "IT") {
$(".content").hide();
}
}, "jsonp");
So what do we do here?
We check if country code equals "IT". If it is true we hide the content. And this is the same what you were doing in php (if country different than IT show content).
EDIT 2
Instead of hiding the div you can remove it
$(".content").remove();
Try hiding via javascript, ajax can run PHP scripts and bring it back into the DOM but you're better off using JS if you don't need a backendscript
$.get("http://ipinfo.io", function (response) {
var country = $("#country").html(response.country);
if(country != "IT"){ document.getElementByID("country").display = "none";
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
I use the ProcessWise cms, that have their own API. So this answer work only with the ProcessWise cms. ( the best one ;) )
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
echo "ip: " . $user_ip . "<br />";
$http = new WireHttp();
$url = "http://ipinfo.io/{$user_ip}/country";
$response = $http->get($url, ['country' => '']);
echo "Country: " . $response . "<br />";
echo "Successful response: " . $sanitizer->entities($response) . "<br />";
?>

$_POST isn't pulling value from the form populated by jQuery.post

I've tried researching, but I'm not even sure how to research this question as most of the answers relate to pure jQuery, PHP or HTML, but nobody seems to have the same problem - which probably means I'm missing something blatantly obvious...
I have a form with a select box. On change of the select box, I call a jQuery.post to a functions page with a php/mysql query and html. I pull that information back inside my form and it works beautifully. However, when I post the form, the variable $_POST['subcat'] is empty. Here is the code:
Form:
<li><h3><?php echo 'Market:';?></h3>
<script>
function display_subcat(vals)
{
jQuery.post("<?php bloginfo('siteurl'); ?>/?get_subcats_for_me=1", {queryString: ""+vals+""}, function(data){
if(data.length >0) {
jQuery('#sub_cats').html(data);
}
});
}
</script>
<p><select class="do_input_new" name="market" onchange="display_subcat(this.value)" >
<option value="">Select Market</option>
More Options...
</select>
<br/><span id="sub_cats">
</span>
</p></li>
Functions:
if(isset($_GET['get_subcats_for_me']))
{
$cat_id = $_POST['queryString'];
if(empty($cat_id) ) { echo " "; }
else
{
$args2 = "orderby=name&order=ASC&hide_empty=0&parent=".$cat_id;
$sub_terms2 = get_terms( 'project_cat', $args2 );
if(count($sub_terms2) > 0)
{
$ret = '<select class="do_input_new" name="subcat">';
$ret .= '<option value="">'.__('Select Subcategory','ProjectTheme'). '</option>';
foreach ( $sub_terms2 as $sub_term2 )
{
$sub_id2 = $sub_term2->term_id;
$ret .= '<option '.($selected == $sub_id2 ? "selected='selected'" : " " ).' value="'.$sub_id2.'">'.$sub_term2->name.'</option>';
}
$ret .= "</select>";
echo $ret;
}
}
die();
}
Now, when I submit the form, the variable $submarket = $_POST['subcat']; is empty. Everything else works (the class is what I expect, the data is what I expect), but it seems the name="subcat" isn't coming through to the $_POST. print_r($_POST) doesn't list subcat. Thoughts?
I'm an idiot. The above code worked perfectly. My problem was that the start of my <form> was in a <div> that I closed out before the majority of the form. I suppose since all the other elements were loaded on the same page that they came over in the $_POST, but because "subcat" was new, and after the <div> closed, it didn't get picked up in the $_POST. The form closed long after this particular element, so it must have been because it wasn't original. Thank you for your help #jcaron!!

How can get the refreshed option values from database only when i click on select box?

I want to get the refreshed option values from database only when i click on select box.
Suppose two waiter open the same order panel page at same time. Then table no:2 is shown as free in both of the panel.
Now a waiter booked table no:2. Then another waiter when clicked on the select box, he will not get the table no:2 in the options.
<select name="table_id" class="form-control tablename">
<option disabled="disabled">Select Table</option>
<?php $result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
while ($row=mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['table_id'];?>"><?php echo $row['table_name']; ?></option>
<?php } ?>
</select>
table_status
rtable
Create function in php to generate options ( sending html is not good practice but I am adjusting to this example). In this particular example i suggest to create functions.php file and there add printSelectOptions function declaration:
function printSelectOptions(){
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result)){
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
}
Above function prints all html options for select.
Use it function in generating select ( remember that functions.php should be included in any file with usage of printSelectOptions ):
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
?>
<select name="table_id" class="form-control tablename">
<?php printSelectOptions() ?>
</select>
In frontend bind Your select ( javascript code ):
document.addEventListener("DOMContentLoaded", function(event) {
var select=document.querySelector("select"); //this is pure selector gets first select on page
//function sends ajax and refresh options of select
function refreshOptions(){
//send ajax request
select.innerHTML="<option>Loading..</option>"; //loading info
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", 'yourSecondPHPScript.php');//here example url where we get updated options
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
select.innerHTML = xmlhttp.responseText;//set new options
}else{
console.log('Error: ' + xmlhttp.statusText )
select.innerHTML="<option>Connection problem</option>";
}
}
}
xmlhttp.send();
};
//bind our select
select.addEventListener("focus",function(){
refreshOptions();
});
});
Last create example yourSecondPHPScript.php and in it use function:
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
printSelectOptions();//outputs options
To be sure that users will not take the same table besides checking in focus check it again in some submit of order form. So if table was taken refresh select ( by ajax using refreshOptions() ) and show info that this table was taken.
Last thing is to secure it on server side, create some check function in php ( PHP CODE ):
function tableCanBeTaken($optionId){
//this code adds **and** to query with id to check but optionId should be validate before using in query
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
and ts.table_id=$optionId ")or die(mysql_error());
return mysql_fetch_array($result); //if row exists - will be false if not exists row with table_id==$optionId and not booked
}
}
Then use it (PHP CODE ):
if (tableCanBeTaken($youOptionId)){
//here code for taking option
}else{
//here option is taken
}
Have the ajax call in the focus event of the select box.In the success of the call, append the data(available tables) to the select input.Until then, leave the select box options as 'Loading. Hope this helps!
#Maciej Sikora
problem is fixed. printSelectOptions() function can not be called from another file like yourSecondPHPScript.
And also needs to remove the back-slash from url.
xmlhttp.open("GET", 'yourSecondPHPScript.php');
i just paste the same code in yourSecondPHPScript.php like below
<?php
include("connect.php");
$result = mysql_query("select * from rtable r inner join table_status as ts on ts.status_id=r.status_id where ts.status!='Booked' order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result))
{
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
?>

How can I have a PHP query select a certain table based on a drop down list selection?

I have a web program where the goal is plot data points for a certain Kiln that the user has selected. My problem is when a user wants to select a new Kiln, how can I update all the separate JSON pages to where the data is pulled from the new table they selected?
Here is my drop down list creater code.
<p class="navleft">
Kiln Number:<br>
<select name="kilns" id="kilns">
<?php
$sql = "SHOW TABLES FROM history";
$result = mysqli_query($con,$sql);
while($table = mysqli_fetch_array($result)) { // go through each row that was returned in $result
echo ("<option value='". $table[0] . "'>" . $table[0] . "</option>");
}
?>
</select>
</p>
And here is one of the php pages where I select all the data from a value in a table and turn it into a JSON file.
<?php
$con = mysqli_connect("localhost","KilnAdmin","KilnAdmin","history");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"history") or die ("no database");
//Fetch Data
$query = "SELECT * FROM k1_history LIMIT 1000";
$result = mysqli_query($con,$query);
if ($result) {
$data = array();
while($row = mysqli_fetch_assoc($result)) {
//$data[] = $row;
$data[] = array(
"date" => $row[ 'Timestamp' ],
"value" => $row[ 'DryBulbFront' ]
);
}
echo json_encode($data);
}
else {
echo "Error";
}
?>
Where is says k1_history, how can I get that to be the selection from the user in the dropbox menu from the other page?
In this kind of scenario you have to strongly pay attention to avoid SQL injection. Use a whitelist approach as mentioned by Konstantinos Vytiniotis and check this out How can I prevent SQL injection in PHP?
If I understand correctly what you want, then what you need is Ajax.
You have to populate the select like you do and on each select, make an Ajax call to a .php where you will handle what the user has chosen. In your case this .php file is going to take the table name the user chose, run a query and return some results back to the html. For demonstration purposes, I'll explain with an example.
Let's say in your .html you have a select like this:
Select Value:
<select name="kilns" id="kilns">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
What defined in the value property of the option is what you are gonna pass to the .php file I mentioned. To do that, you use Ajax, so inside some script tags you have:
$('#kilns').on('change', function(e) {
var data = {'kilns': this.value};
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
dataType: 'json'
}).done(function(msg) {
alert(msg);
});
});
What this does is that every time a user selects something from the select, then this function is called, where the select's value (var data = {'kilns': this.value};) is being sent to a file named submit.php, via POST. The submit.php could look like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$kilns_error = 0;
if (isset($_POST['kilns']) && !empty($_POST['kilns'])) {
$kilns = $_POST['kilns'];
} else {
$kilns = null;
$kilns_error = 1;
}
if ($kilns_error != 1) {
echo json_encode($kilns);
}
}
What happens here is after we check we have indeed a POST REQUEST, we check whether the value is undefined or empty. After this simple check, we proceed to echo json_encode($kilns); where we return the value that we initially sent to the .php script, which in fact is the value the user selected.
In your case, what you have to do it to actually do some things in the .php script and not just return the value that you called it with. Also, make sure to pass the value you take through a whitelist to ensure that the user selects an actual table and is not trying to create problems for your database, cause it would be really easy to just change the value of what he is going to select before actually selecting it. Have a look at the prepared statements of the mysqli and PDO.

Getting form data from both dependent drop down lists to php

I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.

Categories

Resources