world countres list with cities - php

is there any solution to show user all countries and after select country it reselect all cities of its country? be best with script selecting
p.s. russian name of countries

Sure, there's a solution. You could have Country and City models with Id and Name properties:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
And an action that would give you all cities in a country:
public class CountriesController : Controller
{
public ActionResult Index()
{
IEnumerable<Country> countries = Repository.GetCountries();
return View(countries);
}
}
public class CitiesController: Controller
{
public ActionResult Index(string countryId)
{
IEnumerable<City> cities = Repository.GetCities(countryId);
return Json(cities);
}
}
And have a view similar to this:
<%= Html.DropDownList("selectedCountry", new SelectList(Model, "Id", "Name")) %>
<%= Html.DropDownList("selectedCity", Enumerable.Empty<City>()) %>
Then setup javascript:
$(function() {
$('#selectedCountry').change(function() {
var selectedCountry = $(this).val();
$.getJSON('/cities/index', { countryId: selectedCountry }, function(cities) {
var citiesSelect = $('#selectedCity');
citiesSelect.empty();
$(json).each(function(i, city) {
citiesSelect.append('<option value="' + city.Id + '">' + city.Name + '</option>');
});
});
});
});

I thing, better solution is use JSON to exists database. For example you can use geonames.org
http://jqueryui.com/demos/autocomplete/#remote-jsonp
Example:
<meta charset="utf-8">
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
#city { width: 25em; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="city">Your city: </label>
<input id="city" />
Powered by geonames.org
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</div><!-- End demo -->
<div class="demo-description">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are cities, displayed when at least two characters are entered into the field.</p>
<p>In this case, the datasource is the geonames.org webservice. While only the city name itself ends up in the input after selecting an element, more info is displayed in the suggestions to help find the right entry. That data is also available in callbacks, as illustrated by the Result area below the input.</p>
</div><!-- End demo-description -->

If you just need a one-time list (and not something that's continuously updated), then manually scraping the Russian Wikipedia page for list of countries isn't too bad. Could do something similar with a list of cities as well, but trying to get a complete list of cities is somewhat foolhardy. I'd try and limit it to the top 200 in the world or so.
Note: I just assume that's the page for list of countries because I speak no Russian but that's the first result I got when I searched for it.

Related

How to implement autocomplete functionality using PHP, jQuery and AJAX in following scenario?

I'm using PHP, Smarty, MySQL, jQuery and AJAX for my website. Now the scenario is as follows:
There are three fields present on my form. The code for these three fields from smarty template is as follows:
<label>Class</label>
<div class="form-element">
<select name="class_id" id="class_id" onchange="get_section_by_class(this.value, 'get_section_by_class', '#section_id'); return false;">
<option value="">-Select Class-</option>
{foreach from=$all_class item=class key=key}
<option value="{$class.group_id}" {if $class_id == $class.group_id} selected="selected"{/if}>{$class.group_name}</option>
{/foreach}
</select>
</div>
<label>Section</label>
<div class="form-element">
<select name="section_id" id="section_id">
{if empty($section_id)}
<option value="">-Select Section-</option>
{else}
<option value="all">All</option>
{/if}
{foreach from=$all_section_by_class item=section key=key}
<option value="{$section.group_id}" {if $section_id==$section.group_id} selected="selected"{/if}>{$section.group_name}</option>
{/foreach}
</select>
</div>
<label>Name</label>
<div class="form-element">
<input type="text" class="" name="user_name" id="user_name" value="{$user_name}" />
</div>
Now from above code I want to make the field named user_name autopopulate. The values to be displayed as auto populated depends on the values selected from the other two select controls from above code. That is I want to pass the values of controls class_id and section_id into the AJAX request to fetch the autopopulate list of Usernames.
For this I've written following code but it's not working for me. Can you help me in making the text field named user_name autocomplete enabled? Thanks in advance. My non-workable code is as follows:
{literal}
<script language="javascript" type="text/javascript">
$(function() {
$("#user_name").autocomplete({
source: function( request, response ) {
$.ajax({
url: "report_student_result.php",
data: {'request_type':'ajax', 'op':'get_student_names', 'class_id':request.class_id, 'section_id':section_id },
dataType: "json",
success: function( data ) {
response( $.map( data.myData, function( item ) {
return {
//How to access the jason response here and assign it in autopopulate?
}
}));
}
});
}
});
});
</script>
{/literal}
The PHP code from the file report_student_result.php is as follows(one of the the switch case):
<?php
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
global $gDb;
switch($op) {
case'get_student_names':
// escape your parameters to prevent sql injection
$param = mysql_real_escape_string($_GET['term']);
$options = array();
$sql = " SELECT CONCAT(u.user_first_name, " ", u.user_last_name) as full_name FROM users as u JOIN users_groups_subscribe as ugs ON u.user_id = ugs.subscribe_user_id WHERE ugs.subscribe_group_id=10 ";
$this->mDb->Query( $sql);
$data = $gDb->FetchArray();
$data = json_encode($data);
echo $data;
die;
break;
}
?>
I'm also not getting how should I access the json response. After so much googling and all reasearch I've written above code.It may have many mistakes, please help me to make the field autocomplete workable.
You can do this in following manner. I've not tested the code thoroughly. Hope it will work for you.
<script language="javascript" type="text/javascript">
$(function() {
$( "#user_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "report_student_result.php",
dataType: "json",
data: {
request_type: "ajax",
op: "get_student_names",
class_id: $('#class_id').val(),
section_id: $('#section_id').val(),
name_startsWith: request.term
},
success: function( data ) {
response(
$.map(data, function(item) {
return {
label: item.full_name,
value: item.full_name
}
})
);
}
});
},
minLength: 2,
select: function( event, ui ) {
if(ui.item) {
$(event.target).val(ui.item.value);
}
return false;
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
Try this
$("#user_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "report_student_result.php",
dataType: "json",
data: {
request_type: "ajax",
op: "get_student_names",
class_id: $('#class_id').val(),
section_id: $('#section_id').val()
},
success: function(data) {
response(
$.map(data, function(item) {
return {
label: item.full_name,
value: item.full_name
}
})
);
}
});
},
select: function(event, ui) {
if(ui.item) {
$(event.target).val(ui.item.value);
}
return false;
}
});
Here the response from the server should be in the following form
[{"full_name":"Name 1"},{"full_name":"Name 2"},{"full_name":"Name 3"},.......]
Hope that helps!
Always test your PHP directly to make sure that the content you are sending to the client is what you expect. Also, I typically always send an ID along with the data so that I can send the ID back to the server if I want to do something with it. Also, no need to use CONCAT in your query as you can combine them on the client (nothing wrong on what you did, but good to have options).
I personally do not use Smarty templates. What would give you a greater audience of individuals providing answers would be to just show the resulting HTML.
Try the following jQuery script. I don't know what you want to do, and you wight not need the focus event or the blur() and preventDefault() in the select event.
$("#user_name").autocomplete({
source: 'report_student_result.php?request_type=ajax&op=get_student_names&class_id='+$('#class_id').val()+'&section_id='+$('#section_id').val(),
minLength: 2,
focus: function( event, ui ) {event.preventDefault();$(this).val( ui.item.label );},
select: function(event, ui) {
$(this).val('').blur();
event.preventDefault();
//Access your returned data (in object "ui") however you want.
console.log(ui);
//Note that you could have sent multiple values such as ui.item.firstname, ui.item.lastname if you want
alert(ui.item.full_name);
}
})
I had the same issue with response option of autocomplete widget. I upgraded my Autocomplete widget version from 1.8 to 1.9. Now it's working completely fine. Assuming that your code is correct and your using version lesser then 1.9, I recommend you to switch from 1.8 to 1.9. Hope it Works..

Auto complete not showing result jquery

I am trying to create an auto complete using jqueryui.I am echo ing a database result from the remote file search.php.It is showing the correct word in the response of fire bug but the suggetion list is not at all showing in my html page.
Can anybody please help me?
i'm using the code of multipile ,remote demo in the jqueryui.com
my php code
<?php include("connection.php");
$q=mysql_real_escape_string($_GET['term']);
$x="select fieldname from tablename where fieldname like '$q%'";
$query=mysql_query($x);
while($row=mysql_fetch_array($query)) { echo $row['fieldname']."\n"; } ?>
========================================================================
------------------------------------------------------------------------
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#birds" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" size="50" />
</div>
If your remote file is placed on different domain you have to use JSONP.
JSON dosen't support cross-domain data transfer.
Read more about Same Origin policy

JQuery UI Autocomplete with PHP file source

I am trying to use JQueryUI autocomplete, with data coming from a remote source (another php script).
Below is the example given in the demos on the JQueryUI website:
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
My question is about the PHP script "search.php". Should this script simply return an array?
The response should be a JSON formatted array in either of these two formats:
An Array of Strings:
[ "Choice1", "Choice2" ]
OR
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]

jquery autocomplete with php source & json issue

I want to create jquery autocomplete and php, the problem is the data shown in each record of the autocomplete has two values, I managed to do this like this (without PHP),
$(function() {
var authors = [
{
label: "jQuery",
desc: "the write less, do more, JavaScript library"
},
{
label: "jQuery UI",
desc: "the official user interface library for jQuery"
},
{
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine"
}
];
$( "#authorname" ).autocomplete({
minLength: 0,
source: authors,
focus: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
now I want to change the source to php page (change authors to "getauthors.php")
I don't know what to put inside "getauthors.php" in order to pass two things for label and desc.
I managed to pass one thing like this using json,
<?php
$json = array();
$json[]="test";
$json[]="test2";
$json[]="test3";
echo json_encode($json);
?>
which outputs like this,
you can see that the second thing is always undefined, how I can pass value to this in php using json (or any other way).
Thanks.
<?php
$json = array();
$json[] = array ("label"=>"test", "desc"=>"description");
...
echo json_encode($json);
?>

JQuery GET works only first time, second time I just get server response... why?

I have some JQuery where when you click on a "Add to Basket" button (it's really a link), the first time everything works as expected however click the button a second time, although the product is added to basket (database row has increased quantity), the response sent by server is outputted rather than "captured" by JQuery in the SUCCESS function.
I don't understand why this would happen, any thoughts on this?
JQuery
$(function() {
$( '.button' ).click(function( e ) {
e.preventDefault();
var url = $( this ).children( 'a' ).attr( 'href' );
var elem = $( this );
var parent = $( this ).parent().parent();
var html = parent.html(); alert( html );
$.ajax({
type: 'get',
url: url,
data: '',
cache: false,
dataType: 'text',
beforeSend: function( rs ) {
parent.html( '<div class="basket-item item-border" style="width:896px;text-align:center;"><p class="para"><img src="/media/images/spinner.gif" />Please wait...</p></div>' );
},
success: function( rs ) {
parent.html( html );
if( rs = 'YES' ) {
alert( 'Okay' );
} else {
alert( 'Something went wrong' );
}
},
error: function( rs, err ) {
if( rs.status == 0 ) {
alert( '--- Offline' );
} else if( rs.status == 404 ) {
alert( '404 Not Found' );
} else if( rs.status == 501 ) {
alert( '501 Internal Error' );
} else if( err == 'timeout' ) {
alert( '--- Timeout' );
} else {
alert( '--- Unknown' );
}
}
});
});
});
And here is a section of the HTML the JQuery works on
<div>
<div class="basket-item item-border" style="width:512px;text-align:left;">
<p class="para">
<img
width="48"
height="48"
alt="Sample Soap Pack (£3.99)"
src="http://www.mj.local/media/images/products/generic/0929005236213037.jpg" />
Sample Soap Pack</p>
</div>
<div class="basket-item item-border"><p>3.99</p></div>
<div class="basket-item item-border" style="width:256px;text-align:center;">
<p class="button"><a href="http://www.mj.local/shop/add/sample-soap-pack/">
<span class="add">Add to Basket</span>
</a></p>
</div>
</div>
The contents of the parent DIV are replaced with a "Please wait.." message and then restored, as expected so would this alter any way JQuery works? I have another JQuery working okay when swapping HTML so why now with this?
Thanks.
it's because on success you are replacing the html of the parent, your .button will be replaced, and the new .button won't have the click event binded anymore.
You could fix it by using live jQuery <1.7:
$(function() {
$('.button').live('click', function() {
//your function here
});
});
or on for jquery >1.7:
$(function() {
$(document).on("click", ".button", function(){ });
});
You are replacing your .button element inside the callback function for the AJAX request that clicking on the .button element makes and when you remove the .button element the click event handler for that element is also removed. I would use event delegation so the event handler will affect all the elements currently in the DOM and ones added later (for example by an AJAX call):
Just change:
$( '.button' ).click(function( e ) {
To:
$(document).delegate('.button', 'click', function( e ) {
Here are docs for .delegate(): http://api.jquery.com/delegate

Categories