Populate a text box based on a dynamic drop down box - php

I am trying to populate a text box based on a dynamic dropbox that is populated from the database.
My Code is as Below :
index.php
<?php
include "../conn.php";
?>
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL){
var req = getXMLHTTP();
if (req){
//function to be called when state is changed
req.onreadystatechange = function(){
//when state is completed i.e 4
if (req.readyState == 4) {
// only if http status is "OK"
if (req.status == 200){
document.getElementById('cur_code').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p style="color:#000099 ">When you change the dropdown list, the respective currency code of the country will be displayed in the textbox which is fetched from PHP using Ajax. </p>
<p>Department : <?PHP
echo "<select name= 'Department' class='form-control selectpicker' onChange='getCurrencyCode('find_ccode.php?country='+this.value)' Required>";
echo '<option value="">'.'--Please Select Department--'.'</option>';
$sql = "SELECT ID,Name FROM Departments";
$query = sqlsrv_query($conn,$sql);
$query_display = sqlsrv_query($conn,$sql);
while($row=sqlsrv_fetch_array($query_display,SQLSRV_FETCH_ASSOC)){
echo "<option value='". $row['Name']."'>".$row['Name']. '</option>';
}
echo "</select>";
?>
ID : <input type="text" name="cur_code" id="cur_code" ></p>
</form>
</body>
</html>
find_ccode.php
<?php
$country=$_REQUEST['country'];
include '../conn.php';
$sql = "SELECT ID,Name FROM Departments Name='$country'";
$fetched=sqlsrv_query($conn,$sql) ;
if( $fetched === false ) { die( print_r( sqlsrv_errors(), true ));}
while($sno=sqlsrv_fetch_array($fetched,SQLSRV_FETCH_ASSOC))
{
echo $formno=$sno['ID'];
}
}
?>
What I have
What I want :
The ID number of that particular department that is selected in the drop down should display in the text box. I have also attached an extract of what I am trying to do
But it doesn't seem to work. Where do you think I have gone wrong? Appreciate any help :)

FIDDLE
$('#sel').change(function() {
$('#qwe1').val($('#sel option:selected').val());
})
for dynamic value
FIDDLE
Use .change to select and get its value then put it to input box.
UPDATE
FIDDLE
var data = var data = [{
"id": "342-432-423-000","name": "name1"
}, {
"id": "342-432-423-001","name": "name2"
}, {
"id": "342-432-423-002","name": "name3"
}, {
"id": "342-432-423-003","name": "name4"
}, {
"id": "342-432-423-004","name": "name5"
}, {
"id": "342-432-423-005","name": "name6"
}, {
"id": "342-432-423-006","name": "name7"
}, {
"id": "342-432-423-007","name": "name8"
}]
for (var i = 0; i < data.length; i++) {
$('#sel').append('<option id=' + data[i].id + ' data-id="' + data[i].id + '">' + data[i].name + '</option>');
}
$('#sel').change(function () {
$('#qwe1').val($('#sel option:selected').data('id'));
})
Assuming I have the data from php I set the department name as option name and I set the department id asdata-id. Then from select change event i will get the value of data-id and set it as value of the input.

Related

My ajax code doesnt output JSON file

So ive been trying to get this to work for hours now but im just stuck.
I have a simple guestbook page setup and I have this code creating a JSON file:
<?php
/* Konstanter för db-inställningar */
define("DBHOST", "localhost");
define("DBUSER", "guestbook");
define("DBPASS", "password");
define("DBDATABASE", "guestbook");
/* DB-anslutning */
$db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBDATABASE) or die('Fel vid anslutning');
$numrows = 999; // Maxvärde
if(isset($_GET['numrows'])) {
$numrows = intval($_GET['numrows']);
}
/* SQL-fråga */
$sql = "SELECT * FROM users LIMIT $numrows";
$result = mysqli_query($db, $sql) or die('Fel vid SQL-fråga');
/* Loopa genom resultet och spara till ny array */
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$json = json_encode($rows, JSON_PRETTY_PRINT);
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
echo $json;
This outputs it in JSON format and then I have this code trying to read the file and output the content of the JSON to this page:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title>Guestbook</title>
</head>
<link rel="stylesheet" href="css/stilmall.css?<?php echo time(); ?>" type="text/css">
<body>
<nav id="mainmenu">
<ul>
<li>Home</li>
<li>Administration</li>
<li>JSON</li>
<li>Webbservice</li>
</ul>
</nav>
<div class="posts">
<h2>WebService</h2>
<div id="info"></div>
<script>
var xhr = new XMLHttpRequest();
// läs ut svar
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
var jsonStr = JSON.parse(xhr.responseText);
var users= jsonStr.posts;
for(var i=0; i<users.lenght; i++) {
document.getElementById("info").innerHTML = xhr.responseText;
}
}
};
xhr.open("GET","http://localhost/webbutveckling2/moment3/webservice.php",true);
xhr.send(null);
</script>
</p>
</div>
</body>
</html>
I cannot for the love of good see what im doing wrong.
I need this to output the JSON content, also I would like to just output the 3 latest entried from the JSON file only.
What im doing wrong?
Edit:
Here is the JSON output:
[
{
"id": "2",
"name": "Emil1234",
"post": "My name is Emil and this is a test for a post on the guestbook wall",
"postdate": "2018-03-15 16:41:10"
},
{
"id": "22",
"name": "golddigger",
"post": "Hi! This is my first visit to this epic guestbook",
"postdate": "2018-03-25 14:52:11"
},
{
"id": "23",
"name": "Tester123",
"post": "Im just doing another test dont mind me",
"postdate": "2018-03-25 14:52:31"
},
{
"id": "24",
"name": "the bluff",
"post": "Whatsup all",
"postdate": "2018-03-25 15:17:17"
}
]
When I update my code in the js to the following:
<script>
var xhr = new XMLHttpRequest();
// läs ut svar
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
document.getElementById("info").innerHTML = xhr.responseText;
</script>
It does put out the raw information in the following way:
How do I output this to be show just the latest 3 posts?
Edit 2:
<script>
var xhr = new XMLHttpRequest();
// läs ut svar
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
document.getElementById("info").innerHTML = xhr.responseText;
//var jsonStr = JSON.parse(xhr.responseText);
var users = JSON.parse(xhr.responseText);
for(var i=0; i < users.length; i++) {
document.getElementById("info").innerHTML = users[i].name + " - " + users[i].post + " - " + users[i].postdate ; }
}
};
xhr.open("GET","http://localhost/webbutveckling2/moment3/webservice.php?numrows=3",true);
xhr.send(null);
</script>
This outputs just one, is my url wrong?
Outputs the following:
There is not " numrows " is going as a get request in the ajax call thatsand just try putting the fetch function in a while loop and concatenate in the output variable

I am trying to make 2 filters work together. I want the already selected option's value to go on getdata1.php page without selecting the category

Please help I am stuck in this for a long time.
I have given all the necessary code.
There are three parts in it .
I am trying to make 2 filters work together. I want the already selected option's value to go on getdata1.php page without selecting the category.
Here is the script for filtering category.
<script>
function showUser(str) {
if (str=="" ) {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getdata1.php?q="+str,true);
xmlhttp.send();
}
</script>
Here is the Code for range slider from price
<script>
$(document).ready(function(){
// Initializing slider
$( "#slider" ).slider({
range: true,
min: 0,
max: 500000,
values: [ 0, 500000 ],
step:1000,
slide: function( event, ui ) {
// Get values
var min = ui.values[0];
var max = ui.values[1];
$('#range').text(min+' - ' + max);
// AJAX request
$.ajax({
url: 'getData1.php',
type: 'post',
data: {min:min,max:max},
success: function(response){
// Updating table data
$('#emp_table tr').remove();
$('#emp_table').append(response);
}
});
}
});
});
</script>
Here is the html part
<div id="slider"></div><br/>
Range: <span id='range'></span>
<form><p class="filter_heading"><b>Category</b>
</p>
<select name="users" onchange="showUser(this.value)">
<option value="all">All</option>
<option value="nul" selected ></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
</select>
</form>
Here is my getdata1.php
<?php
$q = strval($_GET['q']);
include 'connection.php';
/* Range */
echo "$q";
$min = $_POST['min'];
$max = $_POST['max'];
/* Query */
if (strpos($q,'nul') !== false)
{
$query=mysqli_query($con," SELECT * FROM adv_fb_price_photo WHERE
photo_min>=$min AND photo_max<=$max");
$html = '';
while($row=mysqli_fetch_array($query))
{
$brand=$row['brand'];
$category=$row['category'];
$photo_min=$row['photo_min'];
$photo_max=$row['photo_max'];
$html .='<tr>';
$html .='<td>'.'Brand: '.$brand.'<br>Category: '.$category.'<br>
Minimum price:
'.$photo_min.'<br>Maximum price: '.$photo_max.'</td>';
$html .='</tr>';
}
}
else
{
$query1=mysqli_query($con," SELECT* FROM adv_fb_price_photo WHERE (photo_min>=$min AND photo_max<=$max) AND (category='$q')");
$html = '';
while($row1=mysqli_fetch_array($query1))
{
$brand=$row1['brand'];
$category=$row1['category'];
$photo_min=$row1['photo_min'];
$photo_max=$row1['photo_max'];
$html .='<tr>';
$html .='<td>'.'Brand: '.$brand.'<br>Category: '.$category.'<br>Minimum price: '.$photo_min.'<br>Maximum price: '.$photo_max.'</td>';
$html .='</tr>';
}
}
echo $html;
?>

Google maps & how pass variable from php page to another, when that php page is not included

I’m working on the example: “Using PHP/MySQL with Google Maps”
https://developers.google.com/maps/articles/phpsqlajax_v3
I know this tutorial has been covered a lot before but I can’t find the answer I’m looking for, and hope someone can help.
I’m trying to show a Google Map with markers. Each marker is a book icon. Books are organised by category (I’ve called it “type” in my database). The idea is that users can select which category of book they want, and then only these books will be shown on the map.
My problem is I can’t get the FORM select to work, the “type” variable needs to be passed from the index.php to the page phpsqlajax_genxml2.php, in order for the database to be interrogated.
My question is - how do i get the php variable $type to the phpsqlajax_genxml2.php page?
The phpsqlajax_genxml2.php page is not included in the index.php page, but there is a downloadUrl function:
downloadUrl("phpsqlajax_genxml2.php", function(data)
Here are my files in full. Thanks in advance
index.php
<?php
// Get parameters from URL
$type = $_GET["type"];
?>
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
'Murder Mystery': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png'
},
'Travel Guide': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_gray.png'
},
'Romance': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_purple.png'
},
'Short Story': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
},
'Thriller': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
},
'Comedy': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
},
'Graphic Novel': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_white.png'
},
'Satire': {
icon: 'http://labs.google.com/ridefinder/images/mm_20_brown.png'
}
};
</script>
<script type="text/javascript">
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
alert('Geolocation is required for this page, but your browser doesn&apos;t support it. Try it with a browser that does, such as Opera 10.60.');
}
function errorFunction(position) {
alert('Error!');
}
//If successful geolocation then draw the map, show my coords on the map, and pull in the icons
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var map = new google.maps.Map(document.getElementById("map"),
{
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// SQL to XML file
//downloadUrl("phpsqlajax_genxml2.php?type=" + type, function(data) {
downloadUrl("phpsqlajax_genxml2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + "<i>" + type + "</i>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="successFunction(position)">
<div id="map" style="width: 500px; height: 400px"></div>
<form action="<?php $_PHP_SELF ?>" method="GET">
<select name="type">
<option value="Murder Mystery">Murder Mystery</option>
<option value="Travel Guide">Travel Guide</option>
<option value="Romance">Romance</option>
<option value="Short Story">Short Story</option>
<option value="Thriller">Thriller</option>
<option value="Comedy">Comedy</option>
<option value="Graphic Novel">Graphic Novel</option>
<option value="Satire">Satire</option>
</select>
<input type="submit" value="Submit" />
</form>
</body>
</html>
phpsqlajax_genxml2.php
<?php
// Get parameters from URL
$type = $_GET["type"];
include ("inc/DB_connect.php");
//Using PHP's echo to Output XML
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected)
{
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
//$query = "SELECT * FROM `markers` WHERE 1";
$query = "SELECT * FROM `markers` WHERE `type` = '$type'";
$result = mysql_query($query) or die(mysql_error());
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result))
{
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
So if you want to pass data from one PHP file to another, You have two options in this case, Cookies and Sessions:
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
EDIT
There is one more method supported where you can pass that variable in your JQuery call like this:
In your first file:
jQuery('#map').load('Firstfile.php?type=<?php echo($type);?>');
In your second file
$type = $_GET['type'];
Give this one a shot!!
Referred from Passing php variable from one file to another?

Retrieve HTML drop down list value with AJAX

I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];

How to make second autocomplete options dependent on first autocomplete selection using jQuery?

I have a form with a text input and select option box. The text field uses an autosuggest to allow users to pick options from a list. Once a a value is selected from the autosuggest, the select option box is populated with options dependent on the selection.
I am working to change the code over so that the second box is a text input as well, so as not to limit the users choices (i.e. both fields should allow free text entries if the user does not want to select from the available choices).
I think I've stared at this code too long, and would love some help. Clearly the changes need to come in the loadCountry, populateSelect and loadcountrySelect functions.
I am using PHP, jQuery and jQuery UI Autocomplete.
Any help you could provide would be very much appreciated!
Scripts:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function guess(value){
var oldValue = $('.continent_autocomplete').val();
if (oldValue == value)
return;
$('.continent_autocomplete').val(value);
$('.continent_autocomplete').caret(oldValue.length, value.length);
}
function clearGuess(){
var field = $('.continent_autocomplete');
field.val(field.val().substring(0, field.caret().start));
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(handler) {
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
handler(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
function populateSelect(select, options) {
select.html('');
if (options.length) {
enableSelect();
for (i in options){
var option = options[i];
select.append($('<option></option>').val(option).html(option));
}
} else {
disableSelect('Country');
}
}
function loadcountrySelect(continentObj){
disableSelect('Loading...');
loadcountry(function(options){
populateSelect($('.country_autocomplete'), options);
});
}
function disableSelect(message){
var select = $('.country_autocomplete');
select.html("<option>" + message + "</option>");
select.attr('disabled', true);
}
function enableSelect(){
var select = $('.country_autocomplete');
select.attr('disabled', false);
}
populateSelect($(".country_autocomplete"), []);
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
loadcountrySelect(event.target);
}
});
$("input.continent_autocomplete").keyup(function (event){
var code = (event.keyCode ? event.keyCode : event.which);
if (code == 8) { // Backspace
clearGuess();
}
event.target.value = event.target.value.titleCase();
loadcountrySelect(event.target);
});
});
</script>
HTML:
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name" name="continent_name" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete" name="country_autocomplete" class="country_autocomplete" />
</div>
continent.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['startkey'])) {
$mysearchString = $db->real_escape_string($_GET['startkey']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT DISTINCTROW Continent
FROM locations
WHERE Continent
LIKE '$mysearchString%'
LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Continent))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
country.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['key'])) {
$mysearchString = $db->real_escape_string($_GET['key']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent
LIKE '$mysearchString%'
ORDER BY Country
LIMIT 20");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Country))."/".
ucwords(strtolower(strtok($result->Abbrev,";")))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
You're going to need to modify your PHP to get this to work optimally (filtering occurring on the server). I would update your PHP so that it queries your database with two parameters (one for country, one for continent):
$continent = $db->real_escape_string($_GET['continent']);
$country = $db->real_escape_string($_GET['country']);
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent ='$continent' and Country like '$country%'
ORDER BY Country
LIMIT 20");
(Please take with a grain of salt; I don't know PHP)
Basically, pass a continent (which was selected in the first input) along with the country search string (which was typed in the second input).
Next, you're going to need to apply the autocomplete widget to the second input. Something like:
$("#country_autocomplete").autocomplete({
source: function (request, response) {
var continent = $("#continent_autocomplete").val()
, country = request.term;
$.ajax({
url: '/db/country.php?continent=' + continent + "&country=" + country,
success: function(data) {
response(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
});
Just for some polish, you'll probably want to clear #country_autocomplete when #continent_autocomplete changes. You can do that by adding an event handler for autocomplete's change event:
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
change: function () {
$("#country_autocomplete).val('');
}
});
Lastly, you'll want to remove any code that has to do with populating the country select, since you no longer need it.
The jQuery plugin Autocomplete like Google supports such functionality:
autocomplete.php (agly style, the whole logic at one place -- just to show the principle)
if(!empty($_GET['foo_name']) && !empty($_GET['bar_number'])) {
$sql = 'SELECT ... FROM ... WHERE';
$db = new MySQLi(...);
$db->query($sql);
$numbers = [];
while($row = $result->fetch_assoc()){
$numbers[] = $row['bar_number'];
}
}
echo json_encode($numbers);
autocomplete.html
<link href="/components/autocompletelikegoogle/jquery.autocomplete.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/components/autocompletelikegoogle/jquery.autocomplete.js"></script>
<script type="text/javascript" src="/js/autocomplete.js"></script>
<input type="text" name="foo_name" id="foo-name" value="">
<input type="text" name="bar_number" id="bar-number" value="">
autocomplete.js
$(function() {
$("#foo").autocomplete({
minLength: 3,
limit: 5,
source : [{
url:"/my/ajax/controller/foo?data[foo_name]=%QUERY%",
type:'remote'
}],
});
});
$(function() {
$("#bar").autocomplete({
minLength: 3,
limit: 5,
appendMethod:'replace',
source : [
function(query, add) {
fooName = $('#foo-name').val();
$.getJSON("/my/ajax/controller/bar?data[bar_number]=" + query + "&data[foo_name]=" + fooName, function(response) {
add(response);
})
}],
});
});

Categories