При ошибке
Access to XMLHttpRequest at 'https://site1.ru/api.php' from origin 'https://site2.ru' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
добавить на отдающий данные сайт (в примере site1.ru) заголовок
header('Access-Control-Allow-Origin: *');
JS:
$(".input_place").autocomplete({
source:"/?ajax_action=get_places",
minLength:4,
position:{my:"left top",at:"left bottom"},
select:function(event,ui){
var loc=$(this).closest('form').attr('action');
if(ui.item.country_id){
loc+='?country[]='+ui.item.country_id;
$('#hidden_country').val(ui.item.country_id);
}
if(ui.item.district_id){
loc+='&district[]='+ui.item.district_id;
$('#hidden_district').val(ui.item.district_id);
}
if(ui.item.city_id){
loc+='&city[]='+ui.item.city_id;
$('#hidden_city').val(ui.item.city_id);
}
var selected=ui.item.country_name;
if(ui.item.district_name!=''){
selected=ui.item.district_name;
}
if(ui.item.city_name!=''){
selected=ui.item.city_name;
}
$(this).val(selected);
if($('#hidden_country').val()==undefined){
window.location.href=loc;
}
return false;
}
}).autocomplete("instance")._renderItem=function(ul,item){
var li=item.country_name;
if(item.district_name!=''){
li+=' '+item.district_name;
}
if(item.city_name!=''){
li+=' '+item.city_name;
}
return $("<li>").append(li).appendTo(ul);
};
if($_GET['ajax_action']=='get_places'){
$places=array();
$ajax_countries=get_from_base('*','countries',"shown=1 and (`name` LIKE '%".$_GET['term']."%' OR `id` IN (SELECT `parent` FROM `districts` WHERE`shown`=1 and (`name` LIKE '%".$_GET['term']."%' OR `id` IN (SELECT `parent` FROM `cities` WHERE`shown`=1 and `name` LIKE '%".$_GET['term']."%'))))",'pos');
if(count($ajax_countries)>0){
foreach($ajax_countries as $country){
$places[]=array('country_id'=>$country['id'],'country_name'=>$country['name'],'district_id'=>0,'district_name'=>'','city_id'=>0,'city_name'=>'');
$ajax_districts=get_from_base('*','districts',"`parent`=".$country['id']." and `shown`=1 and (`name` LIKE '%".$_GET['term']."%' OR `id` IN (SELECT `parent` FROM `cities` WHERE`shown`=1 and `name` LIKE '%".$_GET['term']."%'))",'pos');
if(count($ajax_districts)>0){
foreach($ajax_districts as $district){
$places[]=array('country_id'=>$country['id'],'country_name'=>$country['name'],'district_id'=>$district['id'],'district_name'=>$district['name'],'city_id'=>0,'city_name'=>'');
$ajax_cities=get_from_base('*','cities',"`parent`=".$district['id']." and `shown`=1 and `name` LIKE '%".$_GET['term']."%'",'pos');
if(count($ajax_cities)>0){
foreach($ajax_cities as $city){
$places[]=array('country_id'=>$country['id'],'country_name'=>$country['name'],'district_id'=>$district['id'],'district_name'=>$district['name'],'city_id'=>$city['id'],'city_name'=>$city['name']);
}
}
}
}
}
}
header('Content-Type: application/json');
echo json_encode($places);
exit();
}
https://jqueryui.com/autocomplete/#custom-data
Часть формы где у нас инпут для логина:
echo "<input type='text' id='login' name='login' onblur='checkName(this.value, \"\")'/>";
echo " — <label for='login'>LOGIN</label><br/>";
echo "<span class='hidden' id='nameCheckFailed'>NOT AVAILABLE</span>";
echo "<span class='hidden' id='nameCheckOK'>AVAILABLE</span><br/>";
Яваскрипт, подключенный например где-то в head:
function checkName(input,response) {
if (response != '') {
failtext=document.getElementById('nameCheckFailed');
oktext=document.getElementById('nameCheckOK');
if (response == '1') {
failtext.className='failtext';
oktext.className='hidden';
}
else {
failtext.className='hidden';
oktext.className='oktext';
}
}
else {
if (input != '') {
url='http://hostname/xml/checkUserName.php?q='+input;
loadXMLDoc(url);
}
else {
failtext.className='hidden';
oktext.className='hidden';
}
}
}
var req;
function loadXMLDoc(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange=processReqChange;
req.open("GET",url,true);
req.send(null);
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Micrisoft.XMLHTTP");
if (req) {
req.onreadystatechange=processReqchange;
req.open("GET",url,true);
req.send();
}
}
}
function processReqChange() {
if (req.readyState == 4) {
if (req.status == 200) {
response=req.responseXML.documentElement;
method=response.getElementsByTagName('method')[0].firstChild.data;
result=response.getElementsByTagName('result')[0].firstChild.data;
eval(method + '(\'\', result)');
}
else {
alert("There was a problem retrieving the XML data:\n"+req.statusText);
}
}
}
Файл /xml/checkUserName.php (в первой строчке инклуд подключения к БД, если не знаем что там и как — гуглим, еще конечно должна существовать таблица users с полем username, в которое пишутся логины)
<?php
include ($_SERVER['DOCUMENT_ROOT']."/include/dbconfig.php");
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
function nameInUse($q) {
$query=mysql_query("SELECT COUNT(*) FROM users WHERE username='".$q."'");
$result=mysql_fetch_array($query);
switch($result[0]) {
case '1' :
return '1';
break;
default:
return '0';
}
}
echo '<response>
<method>checkName</method>
<result>'.nameInUse($_GET['q']).'</result>
</response>';
?>
И CSS:
span.hidden {
display:none;
}
span.failtext {
display: inline;
background: #ffebea;
}
span.oktext {
display: inline;
background-color: #efffea;;
}
На основе: http://wmdn.ru/javascript/example-of-check-login-using-ajax/
Вариант от WMDN: http://wmdn.ru/javascript/example-of-check-login-using-ajax/