I have 2 drop-down menues. The first I populated with possible continents and want the second drop-down to what include all countries depending on the continent that was selected in the first menu. I have only 1 mysql table with columns: continent --> country. Currently there are all countries from all continents in the drop-down even when a continent was chosen. Thank you for your help!
Here is my code:
HTML
<input type="text" class="autosuggest" id="autosuggest2" placeholder="Select Country...">
<div class="country">
<ul class="result" id="result2"></ul>
</div>
<input type="text" class="autosuggest" id="autosuggest3" placeholder="Select Area...">
<div class="area">
<ul class="result" id="result3"></ul>
</div>
jQuery / Ajax
$(document).ready(function() {
$('#autosuggest1').keyup(function() {
var continent = $(this).attr('value');
$.post('php/dropdown.php', {continent:continent}, function(data) {
$('#result1').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest1').attr('value', result_value);
$('#result1').html('');
$('#result1').focusout('');
});
});
});
$('#autosuggest2').keyup(function() {
var country = $(this).attr('value');
$.post('php/dropdown.php', {country:country}, function(data) {
$('#result2').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest2').attr('value', result_value);
$('#result2').html('');
$('#result2').focusout('');
});
});
});
});
PHP
require_once '../connect/connectdropdown.php';
if (isset($_POST['continent']) == true && empty($_POST['continent']) == false) {
$continent = mysql_real_escape_string($_POST['continent']);
$query = mysql_query("SELECT DISTINCT `continent` FROM `area` WHERE `continent` LIKE '$continent%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['continent'], '</li>';
}
}
if (isset($_POST['country']) == true && empty($_POST['country']) == false) {
$country = mysql_real_escape_string($_POST['country']);
$query = mysql_query("SELECT DISTINCT `country` FROM `area` WHERE `country` LIKE '$country%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['country'], '</li>';
}
}
i wonder if you are still on this. Anyway a couple of things i would suggest:
Do only one query, pass it to json, and give it to javascript.
PHP
require_once '../connect/connectdropdown.php';
$id=0;
$result=array();
$query = mysql_query("SELECT * FROM `area` ");
while (($row = mysql_fetch_assoc($query)) !== false) {
$result[$id]=$row;
$id++;
}
echo json_encode($result);
Javascript
$(document).ready(function() {
var $mysqlData;
$.post('php/dropdown.php', {continent:continent}, function(data) {
//Json Data from server:
alert('JSON data: '+data)
//you can transform the data from PHP-Json to Javascript Object
$mysqlData = jQuery.parseJSON(data)
//now you can access your data like:
alert ('My first continent: '+$mysqlData[0].continent+' and it\'s first country: '+$mysqlData[0].country)
});
$('#autosuggest1').keyup(function() {
//Now you can use $mysqlData inside your logic
})
$('#autosuggest2').keyup(function() {
//You can use $mysqlData here too
})
});
i did not test this code, there might be some errors but that the logic i suggest you to take.
Related
I am trying to send an $_GET['CategoryID'] trought ajax to call in the destination file getdata.php and I can't make it work, I don't find the perfect info here. I know that I am really noob, but I am trying really hard to learn.
I been trying a lot of different code and it still not working.
<button type="button" name="btn_more" data-vid="<?php echo $stockID; ?>" id="btn_more" class="btn btn-success form-control">Ver Mais</button>
<input class="form-control" id="PresentCategoryID" name="PresentCategoryID" data-cat="<?php echo $_GET['categoryID']; ?>" value="<?php echo $_GET['categoryID'];
<script>
$(document).ready(function(){
$(document).on('click', '#btn_more', function(){
var last_video_id = $(this).data("vid");
var PresentCategoryID= ('PresentCategoryID');
$('#btn_more').html("<div class=loader></div>");
$.ajax({
url:"getdata.php",
method:"POST",
data:{
last_video_id:last_video_id,
PresentCategoryID:PresentCategoryID},
dataType:"text",
success:function(data)
{
if(data != '')
{
$('#remove_row').remove();
$('#result').append(data);
}
else
{
$('#btn_more').html("No Data");
}
}
});
});
});
</script>
My objective it's to call the categoryID in the getdata.php, like this,
<?php
$output = '';
$stockID = '';
$PresentCategoryID = '';
sleep(1);
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID > ".$_POST['last_video_id']." LIMIT 4";
?>
var PresentCategoryID= ('PresentCategoryID')
should be
var PresentCategoryID= $('#PresentCategoryID').val();
You need to use $ to select the element, add the # prefix to use it as an ID, and .val() to get the value of the input.
hey check this answer which will help your problem
$(document).ready(function() {
$(document).on('click', '#btn_more', function() {
var last_video_id = $(this).data("vid");
var PresentCategoryID = ('#PresentCategoryID').val();
$('#btn_more').html("<div class=loader></div>");
var data = {
last_video_id,
PresentCategoryID
};
$.get('getdata.php', JSON.stringify(data)).done(response => {
console.log(response);
if (response != '') {
$('#remove_row').remove();
$('#result').append(response);
} else {
$('#btn_more').html("No Data");
}
}).fail(() => {
console.log("Something went wrong");
});
});
});
PHP SCRIPT
<? php
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//if you using get request
//recommended way to get the data use the mysqlconn->real_escape_string($_GET['last_video_id']);
$last_video_id = $_GET['last_video_id'];
$PresentCategoryID = $_GET['PresentCategoryID'];
sleep(1);
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID='$$last_video_id'";
" LIMIT 4";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if you using post request then in jquery remove $.get to just $.post
$data = json_decode(file_get_contents('php://input'),true);
$last_video_id = $data['last_video_id'];
$PresentCategoryID = $data['PresentCategoryID'];
}
you want to send via 'GET' but you use the method 'POST'.
Best regards
MrKampf
The first box autocompletes as the user types and selects one of the options. The value is coming from a database with 3 attributes: id, name, and value. I would like the value of the selected name from the first text box to automatically display in the second box. How do I carry the value of the name once the name is selected by the user?
index.php:
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "search.php?json",
minLength: 3
});
});
</script>
</head>
<body>
<p>Type the name of a band: <input type="text" id="auto" /></p>
</body>
</html>
search php file
<?php
$mysqli = taken off;
$text = $mysqli->real_escape_string($_GET['term']);
$query = "SELECT name, salary FROM tag WHERE name LIKE '%$text%' ORDER BY
name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
?>
Try to append a trigger in the autocomplete, by doing something like this
$( '#auto' ).autocomplete({
select: function( event, ui ) {
var myValue = $(this).val();
//Do what you want with your value
}
});
this worked.
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "search.php?json",
minLength: 3,
close: function( event, ui ) { getSalary(document.getElementById('auto').value) },
change: function( event, ui ) { getSalary(document.getElementById('auto').value) },
select: function( event, ui ) { getSalary(document.getElementById('auto').value) }
});
});
function getSalary(name_salary){
$.post( "salary.php", { term: name_salary }, function(data) {
var test = JSON.parse(data);
document.getElementById('autosalary').value = test.value;
$( "#mincome" ).text(test.value);
});
}
</script>
I have a table that includes the taxonomic name of a species. So there are separate columns for each species, domain, kingdom, phylum, etc. I am using a select boxes for each of these classifications, and what I need to happen is when the first one (Domain) is selected, the database is queried to get all the kingdomes where domain is the value of the previous select.
Here's what I have for my PHP in 'search.php':
<select name="domain" id="domain">
<option value="standard">-- Domain --</option>
<?php while($row = mysql_fetch_array($get_domains, MYSQL_NUM))
{
echo "<option value='$row[0]'>$row[0]</option>";
} ?>
</select>
<select name="kingdom" id="kingdom" >
<option value="standard">-- Kingdom --</option>
<?php
$result = array();
$domain = $_POST['domain'];
$get_kingdoms = mysql_query("SELECT DISTINCT sci_kingdom FROM tbl_lifedata WHERE sci_domain = $domain");
while($row = mysql_fetch_array($get_kingdoms, MYSQL_NUM))
{
$result[] = array(
'name' => $row[0]
);
}
echo json_encode($result);
?>
</select>
And this is what I have in my jquery:
$('#domain').change(function() {
$domain = $('#domain option:selected').val();
if ($domain == 'standard') {
$('#kingdom').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Domain:');
} else {
$('#kingdom').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
}
});
$('#kingdom').change(function() {
$kingdom = $('#kingdom option:selected').val();
if ($kingdom == 'standard') {
$('#domain').removeAttr('disabled', 'disabled');
$('#phylum').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
} else {
$('#domain').attr('disabled', 'disabled');
$('#phylum').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Phylum:');
$.post("search.php", {
'domain': option
}, function(data) {
var sel = $("#kingdom");
sel.empty();
for (var i = 0; i < data.length; i++) {
sel.append('<option>' + data[i].name + '</option>');
}
}, "json");
}
});
I'm having the most trouble understanding how the .post() function works. I know exactly what I want to do, just not exactly how to do.
My goal:
- obtain the value of the domain select box when it is changed
- use that value in the mysql query to get the relevant kingdoms
- execute the query using jquery and then populate the kingdom select box
Thanks!
I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.
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);
})
}],
});
});