Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   конфликтуют плагин стилизации с ajax запросом (https://javascript.ru/forum/jquery/34381-konfliktuyut-plagin-stilizacii-s-ajax-zaprosom.html)

prohor.zotikov 02.01.2013 01:28

конфликтуют плагин стилизации с ajax запросом
 
здравствуйте. такая проблема распространена и я много где нашел разных советов. Чаще всего предлагают поменять переменную $ на jQuery... но не помогает. Плагин замечательный, но ajax работает только когда я его отключаю... вот код

это плагин в файле jquery.formstyler.js (взял отсюда http://dimox.name/jquery-form-styler/?cp=3#comments)
(function($) {
	$(function() {
		$.fn.styler = function(opt) {
	
			var opt = $.extend({
				browseText: 'Выбрать',
				zIndex: '1000'
			}, opt);
	
			return this.each(function() {
				var el = $(this);
	
				if (el.is('select')) {
					el.each(function() {
						if (el.next('span.jqselect').length < 1) {
							// одиночный селект
							function doSelect() {
								var selectbox =
									$('<span class="selectbox jqselect" style="display:inline-block;position:relative;z-index:' + opt.zIndex + '">'+
											'<div class="select" style="float:left"><div class="text"></div>'+
												'<b class="trigger"><i class="arrow"></i></b>'+
											'</div>'+
										'</span>');
								el.after(selectbox).css({position: 'absolute', left: -9999});
								var divSelect = selectbox.find('div.select');
								var divText = selectbox.find('div.text');
								var option = el.find('option');
								var optionSelected = option.filter(':selected');
								/* берем опцию по умолчанию */
								if (optionSelected.length) {
									divText.text(optionSelected.text());
								} else {
									divText.text(option.filter(':first').text());
								}
								/* проверяем активность селекта */
								if (el.is(':disabled')) {
									selectbox.addClass('disabled');
								} else {
									var ddlist = '';
									for (i = 0; i < option.length; i++) {
										var selected = '';
										var disabled = ' class="disabled"';
										if (typeof option.eq(i).attr('selected') !== 'undefined' && option.eq(i).attr('selected') !== false) selected = ' class="selected sel"';
										if (option.eq(i).is(':disabled')) selected = disabled;
										ddlist += '<li' + selected + '>'+ option.eq(i).text() +'</li>';
									}
									var dropdown =
										$('<div class="dropdown" style="position:absolute;overflow:auto;overflow-x:hidden">'+
												'<ul style="list-style:none">' + ddlist + '</ul>'+
											'</div>').hide();
									selectbox.append(dropdown);
									var li = dropdown.find('li');
									var selectHeight = selectbox.outerHeight();
									if (dropdown.css('left') == 'auto') dropdown.css({left: 0});
									if (dropdown.css('top') == 'auto') dropdown.css({top: selectHeight});
									var liHeight = li.outerHeight();
									var position = dropdown.css('top');
									/* при клике на псевдоселекте */
									divSelect.click(function() {
										/* умное позиционирование */
										var topOffset = selectbox.offset().top;
										var bottomOffset = $(window).height() - selectHeight - (topOffset - $(window).scrollTop());
										if (bottomOffset < 0 || bottomOffset < liHeight * 6)	{
											dropdown.height('auto').css({top: 'auto', bottom: position});
											if (dropdown.outerHeight() > topOffset - $(window).scrollTop() - 20 ) {
												dropdown.height(Math.floor((topOffset - $(window).scrollTop() - 20) / liHeight) * liHeight);
											}
										} else if (bottomOffset > liHeight * 6) {
											dropdown.height('auto').css({bottom: 'auto', top: position});
											if (dropdown.outerHeight() > bottomOffset - 20 ) {
												dropdown.height(Math.floor((bottomOffset - 20) / liHeight) * liHeight);
											}
										}
										$('span.selectbox').css({zIndex: (opt.zIndex-1)}).removeClass('focused');
										selectbox.css({zIndex: opt.zIndex});
										if (dropdown.is(':hidden')) {
											$('div.dropdown:visible').hide();
											dropdown.show();
										} else {
											dropdown.hide();
										}
										return false;
									});
									/* при наведении курсора на пункт списка */
									li.hover(function() {
										$(this).siblings().removeClass('selected');
									});
									var selectedText = li.filter('.selected').text();
									/* при клике на пункт списка */
									li.filter(':not(.disabled)').click(function() {
										var liText = $(this).text();
										if (selectedText != liText) {
											$(this).addClass('selected sel').siblings().removeClass('selected sel');
											option.removeAttr('selected').eq($(this).index()).attr('selected', true);
											selectedText = liText;
											divText.text(liText);
											el.change();
										}
										dropdown.hide();
									});
									dropdown.mouseout(function() {
										dropdown.find('li.sel').addClass('selected');
									});
									/* фокус на селекте */
									el.focus(function() {
										$('span.selectbox').removeClass('focused');
										selectbox.addClass('focused');
									})
									/* меняем селект с клавиатуры */
									.keyup(function() {
										divText.text(option.filter(':selected').text());
										li.removeClass('selected sel').eq(option.filter(':selected').index()).addClass('selected sel');
									});
									/* прячем выпадающий список при клике за пределами селекта */
									$(document).on('onchange', function(e) {
										if (!$(e.target).parents().hasClass('selectbox')) {
											dropdown.hide().find('li.sel').addClass('selected');
											selectbox.removeClass('focused');
										}
									});
								}
							} // end doSelect()
							// мультиселект
							 // end doMultipleSelect()
							if (el.is('[multiple]')) doMultipleSelect(); else doSelect();
							// обновление при динамическом изменении
							el.on('refresh', function() {
								el.next().remove();
								if (el.is('[multiple]')) doMultipleSelect(); else doSelect();
							})
						}
					});
				// end select
				}
			});
	
		}
	})
})(jQuery)


вот ajax запрос в файле ajax.js

<script type="text/javascript">
(function(jQuery) {
	jQuery(function() {
		jQuery('#country_id').change(function () {
			var country_id = jQuery(this).val();
			if (country_id == '0') {
				jQuery('#region_id').html('<option>- В начале выберите страну -</option>');
				jQuery('#region_id').attr('disabled', true);
				return(false);
			}
			jQuery('#region_id').attr('disabled', true);
			jQuery('#region_id').html('<option>загрузка...</option>');
			
			var url = 'js/ajax.php';
			jQuery.post(url, "country_id=" + country_id, 
					function (result) 
					{ 
						if (result.type == 'error') { alert('error'); return(false); } 
					
						else { var options = ''; jQuery(result.regions).each ( function() { options += '<option value="' + jQuery(this).attr('id') + '">' + jQuery(this).attr('title') + '</option>'; }); jQuery('#region_id').html(options); jQuery('#region_id').attr('disabled', false); }
					},
					"json"
			);
		});
	})
})(jQuery)
</script>


так подключаю эти файлы
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<title>Добро пожаловать</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<link href="style/header.css" rel="stylesheet" type="text/css">
<link href="style/main.css" rel="stylesheet" type="text/css">
<link href="style/jquery.formstyler.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.formstyler.js"></script>
<script type="text/javascript">
(function($) {
	$(function() {
		$('select').styler();
	})
})(jQuery)
</script>

<?php include('js/input.js'); ?>
<?php include('js/ajax.js'); ?>

</head>


просто плагин как то перекрывает запрос... помогите советом

Deff 02.01.2013 01:42

prohor.zotikov,
Ссылка на Вашу тестовую Инет-страничку - имеется ?

prohor.zotikov 02.01.2013 01:57

Вложений: 2
я в mamp'е сайт делаю, не выкладывал на хостинг еще... вот скриншоты

когда отключен плагин
http://javascript.ru/forum/attachmen...d=135707721 5

когда включен плагин
http://javascript.ru/forum/attachmen...d=135707721 5

хоть какую страну выбирай, а в списке городов ничего не меняется

Deff 02.01.2013 02:13

Ну починка авто по фотографии - тяжела, особливо после НГ

prohor.zotikov 02.01.2013 02:19

кстати пользуясь случаем поздравляю всех с новым годом )

Hoshinokoe 02.01.2013 12:41

prohor.zotikov,

Выложите фрагмент разметки, который отображен на скриншотах. Тут не форум экстрасенсов, по картинкам не гадаем :).

Как я понимаю, там селекты country_id и region_id.

P.S. Какие ошибки в консоли браузера ?

prohor.zotikov 02.01.2013 13:20

вот фрагмент из основного файла

<div class="main_center_field">
			<div class="main_field_text"><p>Выберите вашу страну</p></div>
			<div class="selection"><?php include('select/registration_country.php'); ?></div>
		</div>
		<div class="main_field_border"></div>
		<div class="main_center_field">
			<div class="main_field_text"><p>Выберите ваш город</p></div>
			<div class="selection"><select name="region_id" id="region_id" class="registration_select"  disabled="disabled"><option value="0">- В начале выберите страну -</option></select></div>
		</div>
		<div class="main_field_border"></div>
		<div class="main_center_field">
			<div class="main_field_text"><p>Выберите ваш пол</p></div>
			<div class="selection"><?php include('select/registration_sex.php'); ?></div>
		</div>


registration_country.php

<select class="registration_select" name="country_id" id="country_id">
<?php
include('blocks/db.php');
$result=mysql_query('SELECT * FROM countries',$db);
if(!$result) { echo'<p>Возникли проблемы с сервером</p>'; exit(); } 
if(mysql_num_rows($result)>0)
{	
	$array=mysql_fetch_array($result);
	echo'<option value="0" selected="on">- Страна не выбрана -</option>';
	do { printf('<option value=%s>%s</option>',$array['id'],$array['country']); }
	while($array=mysql_fetch_array($result));
}
else { echo'<p>Возникли ошибки при запросе к серверу</p>'; }
?>  
</select>


registration_sex.php

<select class="registration_select" name="sex" id="sex">
<?php
echo '<option value="0" selected>- Пол не выбран -</option>';
echo '<option value="m">Мужской</option>';
echo '<option value="w">Женский</option>';
?>
</select>

prohor.zotikov 02.01.2013 13:21

ошибок в браузере нет...

prohor.zotikov 02.01.2013 14:13

Вложений: 2
веб-инспектор показывает что ajax запрос срабатывает, но на странице не отображается... вот скриншот

http://javascript.ru/forum/attachmen...d=135712139 6

вот скриншот консоли ошибок... ни каких ошибок не отображается

http://javascript.ru/forum/attachmen...d=135712139 6

Hoshinokoe 02.01.2013 14:21

Цитата:

Сообщение от prohor.zotikov (Сообщение 224742)
хоть какую страну выбирай, а в списке городов ничего не меняется

Все правильно. После получения данных вы изменяете разметку в оригинальном селекте, а не в плагине. Чтобы плагин обновил свое состояние, необходимо сгенерировать событие refresh.

Добавьте строку в файл ajax.js:
jQuery('#region_id').html(options);
jQuery('#region_id').attr('disabled', false);

jQuery('#region_id').trigger('refresh'); // обновит состояние плагина

prohor.zotikov 02.01.2013 14:26

Аааа!!! все заработало!!!! спасибо спасибо спасибо спасибо!!!!! ))))) Всем всем спасибо за участие! Hoshinokoe - ты лучший! ) всех еще раз с новым годом! )

demo7878 29.10.2013 22:37

Помогите пожалуста как обновить плагин в этом коде?
var ajax = new Array();

function getRegionList(sel){
var countryCode = sel.options[sel.selectedIndex].value;
var region = document.getElementById('region');
region.options.length = 0;    
if(countryCode.length > 0){
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'takesettings.php?country='+countryCode;
ajax[index].onCompletion = function(){ 
createRegion(index);
};
ajax[index].runAJAX();    
} 
}

function createRegion(index) {
    var obj = document.getElementById('region'); 
    eval(ajax[index].response);
    getCityList(obj);
	
}

function getCityList(sel){
var regionCode = sel.options[sel.selectedIndex].value;
var city = document.getElementById('city');
city.options.length = 0;    
if(regionCode.length > 0) {
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'takesettings.php?region='+regionCode;
ajax[index].onCompletion = function(){ 
createCities(index); 
};
ajax[index].runAJAX();     
} 
}

function createCities(index) {
    var obj = document.getElementById('city'); 
    eval(ajax[index].response);   
}

Hoshinokoe 30.10.2013 00:18

demo7878,

Русским языком опиши проблему для начала. Что за плагин используется ?
Также ссылку на тестовую страницу или сюда код целиком.

demo7878 30.10.2013 00:27

У меня проблема таже что и у него при выборе страны не обновляеться регион и город
Выше я написал функции
Вот php код
//////////////////////////////////////////////* Страна / Город */
$select_contry = "<select id=\"country\" name=\"country\" onchange=\"getRegionList(this)\">"; 
$select_contry .= "<option value=\"0\">Выберите страну</option>"; 
$countries = mysql_query("SELECT id_country, country_name_ru FROM country ORDER BY country_name_ru")/* or sqlerr(__FILE__, __LINE__)*/;
while($lista = mysql_fetch_assoc($countries)) {
$select_contry .= "<option value=".$lista['id_country']."".($auth["country"] == $lista['id_country'] ? " selected" : "").">".$lista['country_name_ru']."</option>\n"; 
}
$select_contry .= "</select>"; 

$select_region = "  <select id=\"region\" name=\"region\" onchange=\"getCityList(this)\">"; 
$select_region .= "<option value=\"0\">Выберите страну</option>\n";
$regions = mysql_query("SELECT reg.id, reg.region_name_ru FROM region AS reg LEFT JOIN country co ON reg.id_country = co.id_country WHERE co.id_country = ".$auth['country']." ORDER BY reg.region_name_ru")/* or sqlerr(__FILE__, __LINE__)*/;
if (mysql_num_rows($regions) > 0) {
while($lista = mysql_fetch_array($regions)) {
$select_region .= "<option value=".$lista['id']."".($auth['region'] == $lista['id'] ? " selected" : "").">".$lista['region_name_ru']."</option>\n"; 
}
} else {
$select_region .= "<option value=\"0\">Выберите страну</option>\n"; 
}
$select_region .= "</select>"; 

$select_city = "  <select id=\"city\" name=\"city\">"; 
$cities = mysql_query("SELECT ci.id, ci.city_name_ru FROM city AS ci LEFT JOIN region rg ON ci.id_region = rg.id WHERE rg.id = ".$auth['region']." ORDER BY ci.city_name_ru")/* or sqlerr(__FILE__, __LINE__)*/;
if (mysql_num_rows($cities) > 0) {
while($lista = mysql_fetch_array($cities)) {
$select_city .= "<option value=".$lista['id']."".($auth['city'] == $lista['id'] ? " selected" : "").">".$lista['city_name_ru']."</option>\n"; 
}
} else {
$select_city .= "<option value=\"0\">Выберите регион</option>\n"; 
}
$select_city .= "</select>";


Вот скрипт city_country.js
/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* [url]www.twilightuniverse.com[/url] */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}


Вот скрипт jquery стилизатора так сказать
http://www.hmil.com.ua/demo/select/

Hoshinokoe 30.10.2013 19:44

Цитата:

Сообщение от demo7878
Вот скрипт jquery стилизатора так сказать
http://www.hmil.com.ua/demo/select/

Древний какой-то плагин, нету у него refresh.
Попробуй инициализировать плагин заново после обновления значения в оригинальном селекте.

function createRegion(index) {
    var obj = document.getElementById('region');
    $(obj).selectBox('destroy'); // удаляем существующий
    eval(ajax[index].response); //тут приходят новые значения ???
    $(obj).selectBox(); //заново инициализируем
    getCityList(obj);    
}


function createCities(index) {
    var obj = document.getElementById('city');
    $(obj).selectBox('destroy'); // удаляем существующий
    eval(ajax[index].response);  //тут приходят новые значения ???
    $(obj).selectBox(); //заново инициализируем
}

demo7878 30.10.2013 19:57

воооо спасибо заработало только исправил буква B большая в названии selectbox


Часовой пояс GMT +3, время: 06:26.