How to append result to Geocoder text box using arcgis javascript api? - javascript

I want to append result of a custom search in a Geocoder text box in arcgis javascript api by over ridding the default result.
I have written below code for that but i am not getting satisfactory result.
<!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 runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Geocoder</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<style>
html, body, #map
{
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#search
{
display: block;
position: absolute;
z-index: 3;
top: 20px;
left: 75px;
}
.spotlight
{
z-index: -1;
position: absolute;
left: 50%;
top: 50%;
border-radius: 50%;
opacity: 0;
box-shadow: inset rgba(0,0,0,0.25) 0px 0px 20px 20px, rgba(0,0,0,0.25) 0px 0px 0px 1000px;
transition: all 1000ms;
-moz-transition: all 1000ms;
-webkit-transition: all 1000ms;
}
.spotlight-active
{
z-index: 2;
opacity: 1;
}
</style>
<script src="http://js.arcgis.com/3.11/"></script>
<script type="text/javascript">
require([
"esri/map",
"esri/dijit/Geocoder",
"esri/graphic",
"esri/symbols/SimpleMarkerSymbol",
"esri/geometry/screenUtils",
"dojo/dom",
"dojo/dom-construct",
"dojo/query",
"dojo/_base/Color",
"esri/tasks/locator",
"esri/geometry/Polygon",
"dojo/_base/array",
"dojo/domReady!"
], function (
Map, Geocoder,
Graphic, SimpleMarkerSymbol, screenUtils,
dom, domConstruct, query, Color, Locator, Polygon, arrayUtils
) {
var _RLCCspatialReference = new esri.SpatialReference({ "wkt": 'classified' });
//var _RMapsExt = new esri.geometry.Extent(-4086033.961945721, -806460.9357572012, 3756052.906228016, 5050597.693910059, _RLCCspatialReference);
var _RMapsExt = new esri.geometry.Extent(-2498256.744659858, 887180.8538370342, 2243086.071359108, 4139445.6917000436, _RLCCspatialReference);
// create a map and instance of the geocoder widget here
var map = new esri.Map("map", { logo: false, nav: false, wrapAround180: true });
map.spatialReference = _RLCCspatialReference;
map.fullExtent = _RMapsExt;
map.initialExtent = _RMapsExt;
var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://xxxx.rxx.com/arcgis/rest/services/Rmaps_Updated/MapServer");
map.addLayer(tiledMapServiceLayer);
map.setScale(14000000);
map.setExtent(_RMapsExt, true);
var gc = [{
url: "http://11.66.22.33:6080/arcgis/rest/services/Locator_Comb_Prd/GeocodeServer",
name: "Locator_Comb_Prd",
singleLineFieldName: "SingleLine"
}];
var geocoder = new Geocoder({
map: map,
arcgisGeocoder: false,
geocoders: gc,
autoNavigate: false,
autoComplete: true,
showResults: true,
geocoders: gc,
geocoderMenu: false,
}, dom.byId("search"));
//"search" dom.byId("search")
geocoder.startup();
geocoder.on("select", showLocation);
geocoder.on("FindResults", showLocation);
dojo.connect(geocoder, 'onAutoComplete', function (results) {
$("#search_input").autocomplete({
source: function (request, response) {
$.support.cors = true;
$.ajax({
dataType: "json",
type: 'POST',
url: 'http://11.66.22.44/Geocoder/Query.aspx',
crossdomain: true,
timeout: 100000,
cache: true,
data: { RequestType: "AutoComplete", AutoCompleteValue: $("#search_input").val() },
success: function (data) {
//$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
if (data != null) {
response(data);
}
},
error: function (data) {
alert("error:" + data.statusText);
//$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function () {
},
close: function () {
},
focus: function (event, ui) {
},
select: function (event, ui) {
}
});
//console.log('autocomplete', results);
});
function showLocation(evt) {
var point = null;
if (evt.result.feature.geometry.type == "point" && evt.result.feature.geometry.x != 0 && evt.result.feature.geometry.y != 0) {
point = evt.result.feature.geometry;
map.graphics.clear();
var symbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_SQUARE).setColor(new Color([255, 0, 0, 0.5]));
var graphic = new Graphic(point, symbol);
map.graphics.add(graphic);
map.infoWindow.setTitle("Search Result");
map.infoWindow.setContent(evt.result.name);
map.infoWindow.show(evt.result.feature.geometry);
}
else {
map.graphics.clear();
locator = new Locator("http://11.66.66.33:6080/arcgis/rest/services/Locator_Comb_Prd/GeocodeServer");
locator.on("address-to-locations-complete", showResults);
var address = {
"SingleLine": evt.result.name
};
var resultName = evt.result.name;
locator.outSpatialReference = map.spatialReference;
var options = {
address: address,
outFields: ["Loc_name"]
};
locator.addressToLocations(options);
function showResults(evt) {
var symbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_SQUARE).setColor(new Color([255, 0, 0, 0.5]));
var geom;
arrayUtils.every(evt.addresses, function (candidate) {
if (candidate.location.type == "point" && candidate.location.x != 0 && candidate.location.y != 0) {
console.log(candidate.score);
if (candidate.score > 80) {
console.log(candidate.location);
var attributes = {
address: candidate.address,
score: candidate.score,
locatorName: candidate.attributes.Loc_name
};
geom = candidate.location;
point = geom;
var graphic = new Graphic(point, symbol);
//add a graphic to the map at the geocoded location
map.graphics.add(graphic);
//add a text symbol to the map listing the location of the matched address.
map.infoWindow.setTitle("Search Result");
map.infoWindow.setContent(resultName);
map.infoWindow.show(point);
return false; //break out of loop after one candidate with score greater than 80 is found.
}
}
else {
var polygonGeom = new Polygon(candidate.location.spatialReference);
polygonGeom.addRing(candidate.location.rings[0]);
geom = polygonGeom.getCentroid();
point = geom;
console.log(candidate.score);
if (candidate.score > 80) {
console.log(candidate.location);
var attributes = {
address: candidate.address,
score: candidate.score,
locatorName: candidate.attributes.Loc_name
};
point = geom;
var graphic = new Graphic(point, symbol);
//add a graphic to the map at the geocoded location
map.graphics.add(graphic);
//add a text symbol to the map listing the location of the matched address.
map.infoWindow.setTitle("Search Result");
map.infoWindow.setContent(resultName);
map.infoWindow.show(point);
return false; //break out of loop after one candidate with score greater than 80 is found.
}
}
});
if (geom !== undefined) {
map.centerAndZoom(geom, 14);
}
}
}
if (point != undefined || point != null) {
map.centerAndZoom(point, 14);
}
}
});
</script>
<script type="text/javascript">
$(function () {
$("#map").css("height", $(window).height());
$("#map").css("width", $(window).width());
//map_root
$("#map_root").css("height", $(window).height());
$("#map_root").css("height", $(window).width());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="search">
</div>
<div id="map" style="width: 100%; height: 100%;">
</div>
</form>
</body>
</html>
anyone any suggestion?

Yes i found solution to this problem basically I can append the data which i am receiving using Jquery.
After all it is just an HTML!
But still there can be a better solution please do post it.
$.ajax({
dataType: "json",
type: 'POST',
//url: 'http://11.66.22.44/Geocoder/Query.aspx',
url: 'Query.aspx',
//crossdomain: true,
timeout: 500000,
cache: true,
data: { RequestType: "AutoComplete", AutoCompleteValue: $("#search_input").val() },
success: function (data) {
//$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
var actualLength = $(".esriGeocoderResults ul").length;
if (data != null) {
//response(data);
if ($(".esriGeocoderResults ul").length == 0) {
$(".esriGeocoderResults").append('<ul role="presentation">');
}
if ($("#search").hasClass("esriGeocoderResultsOpen") == false) {
$("#search").addClass("esriGeocoderResultsOpen");
}
$(".esriGeocoderResults").css("display", "block");
for (var index = 0; index < data.length; index++) {
if ($(".esriGeocoderResults ul").text().indexOf(data[index]) == -1) {
if (actualLength % 2 == 0) {
$(".esriGeocoderResults ul").append('<li onClick = "locatorClick(this);" class="esriGeocoderResult esriGeocoderResultEven" title="' + data[index] + '" role="menuitem" tabindex="0" data-index="' + (actualLength) + '" data-item="true" data-text="' + data[index] + '">' + data[index] + '</li>');
actualLength++;
}
else {
$(".esriGeocoderResults ul").append('<li onClick = "locatorClick(this);" class="esriGeocoderResult esriGeocoderResultOdd" title="' + data[index] + '" role="menuitem" tabindex="0" data-index="' + (actualLength) + '" data-item="true" data-text="' + data[index] + '">' + data[index] + '</li>');
actualLength++;
}
}
}
$(".esriGeocoderResults ul").bind();
//alert($(".esriGeocoderResults ul").length);
//$(".esriGeocoderResults ul").append('<li><span class="tab">Message Center</span></li>');
}
},
error: function (data) {
alert("error:" + data.statusText);
//$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});

Related

How to get background to shuffle between images?

I have an HTML webpage with the background shuffling through the images using javascript that are listed within an array. I was wondering if it would be possible to shuffle between these images in a random order every time the webpage is loaded. There are currently about 61 images that are within the array all named 1.jpg, 2.jpg, 3.jpg within the pics folder. I would really like this to be updateable if we add/remove images in the future.
For example, one time it will be 3,2,1,5,3, the next it will 1,3,2,5,4, next 5,1,4,2,3 and so on. Complete randomness.
Here is my HTML and Javascript
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<script src="jquery.js"></script>
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</head>
<body>
</div>
<div id="carbon-block"></div>
</div>
</div>
<script src="jquery-background-slideshow.js"></script>
<script>
$(document).ready(function() {
/*
$(".layer").backgroundSlideshow({
delay: 3000,
transitionDuration: 3000,
images: [
"assets/images/image3.jpeg",
"assets/images/image4.jpeg"
]
})
*/
$("body").backgroundSlideshow({
onBeforeTransition: function(index) {
console.log("before transition", index)
},
onAfterTransition: function(index) {
console.log("after transition", index)
},
transitionDuration: 3000,
fixed: true,
images: ["pics/1.jpg", "pics/2.jpg", "pics/3.jpg", "pics/4.jpg"]
})
})
</script>
</body>
</html>
And here is there "jquery-background-slideshow.js"
* Author and copyright: Stefan Haack (https://shaack.com)
* Repository: https://github.com/shaack/jquery-background-slideshow/
* License: MIT, see file 'LICENSE'
*/
;(function ($) {
"use strict"
$.fn.backgroundSlideshow = function (options) {
this.each(function () {
var $container = $(this)
var $currentLayer = null
var $nextLayer = null
var currentImageIndex = 0
var nextImageIndex = 0
var preloadedImages = []
var config = {
delay: 5000,
transitionDuration: 3000,
onBeforeTransition: null,
onAfterTransition: null,
fixed: false,
images: []
}
for (var option in options) {
config[option] = options[option]
}
var transition = "opacity " + config.transitionDuration + "ms ease-in-out"
var layerStyles = {
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
backgroundPosition: "center center",
position: config.fixed ? "fixed" : "absolute",
left: 0,
right: 0,
bottom: 0,
top: 0,
zIndex: -1
}
var layerStylesTransition = {
transition: transition,
"-webkit-transition": transition,
"-moz-transition": transition,
"-o-transition": transition
}
function preLoadImage(index) {
if (!preloadedImages[index]) {
preloadedImages[index] = new Image()
preloadedImages[index].src = config.images[index]
}
}
function addLayer(imageSrc, withTransition) {
var $newLayer = $("<div class='backgroundSlideshowLayer'/>")
var thisLayerStyles = layerStyles
thisLayerStyles.backgroundImage = "url(" + imageSrc + ")"
$newLayer.css("opacity", "0")
$newLayer.css(thisLayerStyles)
if(withTransition) {
$newLayer.css(layerStylesTransition)
}
var $lastLayer = $container.find("> .backgroundSlideshowLayer").last()
if ($lastLayer[0]) {
$lastLayer.after($newLayer)
} else {
$container.prepend($newLayer)
}
return $newLayer
}
function nextImage(withTransition) {
currentImageIndex = nextImageIndex
nextImageIndex++
if (nextImageIndex >= config.images.length) {
nextImageIndex = 0
}
if ($nextLayer) {
$currentLayer = $nextLayer
} else {
$currentLayer = addLayer(config.images[currentImageIndex], withTransition)
}
if (config.onBeforeTransition) {
config.onBeforeTransition(currentImageIndex)
}
$currentLayer.css("opacity", "1")
setTimeout(function() {
if (config.onAfterTransition) {
config.onAfterTransition(currentImageIndex)
}
preLoadImage(nextImageIndex)
}, withTransition ? config.transitionDuration : 0)
setTimeout(function() {
$nextLayer = addLayer(config.images[nextImageIndex], true)
cleanUp()
}, config.transitionDuration)
}
function cleanUp() {
var $layers = $container.find("> .backgroundSlideshowLayer")
if ($layers.length > 2) {
$layers.first().remove()
}
}
$container.css("position", "relative")
nextImage(false)
setTimeout(function () {
nextImage(true)
setInterval(function () {
nextImage(true)
}, config.delay + config.transitionDuration)
}, config.delay)
})
}
}(jQuery)) ```
I would create an empty array and push all of my images in a random order and use the new array for display.
let randomImageOrder = [];
let imageArray = ['pics/1.jpg','pics/2.jpg','pics/3.jpg','pics/4.jpg','pics/5.jpg'];
while(imageArray.length > 0) {
let randomIndex = Math.floor(Math.random()*imageArray.length);
randomImageOrder.push(imageArray[Math.floor(Math.random()*imageArray.length)]);
imageArray.splice(randomIndex, 1);
}
console.log(randomImageOrder);

JavaScript If statement and Combo box functionality

I have two combo box's working independently. I would like to get them to work together. I either get State name queried or Farm Acreage queried. I cannot get them both to filter together.
Query Texas and 4 Acres. Get all the 4 acre counties in Texas. Right now it will either give me All of Texas or All 4 acre counties in the US.
The if statements are in the "app" object.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>Drop Down Test</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">
<style>
html,
body,
#mainWindow {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #FFF;
overflow: hidden;
font-family: "Trebuchet MS";
}
#header {
height: 3%;
overflow: auto;
}
</style>
<script>
var dojoConfig = {
parseOnLoad: true
};
</script>
<script src="http://js.arcgis.com/3.10/"></script>
<script>
var map;
require([
"esri/map",
"dojo/on",
"esri/tasks/query",
"esri/layers/FeatureLayer",
"dojo/store/Memory",
"dojo/_base/array",
"dojo/_base/lang",
"esri/request",
"dojo/json",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/form/Button",
"dijit/form/ComboBox",
"dojo/domReady!"
], function(
Map, on, Query, FeatureLayer, Memory, array, lang, esriRequest, json
) {
map = new Map("map", {
basemap: "topo",
center: [-98.579729, 39.828366],
zoom: 5
});
var crops = new FeatureLayer("https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0", {
mode: FeatureLayer.MODE_SELECTION,
outFields: ["*"]
});
map.addLayers([crops]);
map.on("layers-add-result", lang.hitch(this, function(){
var url = "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0/generateRenderer";
var classificationDef = {"type":"uniqueValueDef","uniqueValueFields":["STATE"]};
var classificationDef2 = {"type":"uniqueValueDef","uniqueValueFields":["TotalFarmedAcres"]};
var str = json.stringify(classificationDef);
var str2 = json.stringify(classificationDef2);
esriRequest({
url:url,
content:{
classificationDef:str,
f:'json'
},
handleAs:'json',
callbackParamName:'callback',
timeout:15000
}).then(lang.hitch(this,function(response){
var uniqueValueInfos = response && response.uniqueValueInfos;
if(uniqueValueInfos){
var store2 = new Memory({data:[]});
dijit.byId("uniqueValuesSelect").set('store',store2);
var data = array.map(uniqueValueInfos,lang.hitch(this,function(info,index){
var value = info.value;
//value = parseFloat(value);
var dataItem = {
id:index,
name:value
};
return dataItem;
}));
store2 = new Memory({data:data});
dijit.byId("uniqueValuesSelect").set('store',store2);
}
}),lang.hitch(this,function(error){
console.error(error);
}));
esriRequest({
url:url,
content:{
classificationDef:str2,
f:'json'
},
handleAs:'json',
callbackParamName:'callback',
timeout:15000
}).then(lang.hitch(this,function(response){
var uniqueValueInfos2 = response && response.uniqueValueInfos;
if(uniqueValueInfos2){
var store3 = new Memory({data:[]});
dijit.byId("uniqueValuesSelect2").set('store',store3);
var data2 = array.map(uniqueValueInfos2,lang.hitch(this,function(info,index){
var value2 = info.value;
//value2 = parseFloat(value2);
var dataItem2 = {
id:index,
name:value2
};
return dataItem2;
}));
store3 = new Memory({data:data2});
dijit.byId("uniqueValuesSelect2").set('store',store3);
}
}),lang.hitch(this,function(error){
console.error(error);
}));
}));
app = {
zoomRow: function(id, which){
crops.clearSelection();
var query = new Query();
if(which == "statename"){
query.where = "STATE='" + (id).toString() + "'";
}if(which == "FarmedAcres"){
query.where = "TotalFarmedAcres='" + (id).toString() + "'";
}
console.info(query.where);
query.returnGeometry = true;
crops.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (features) {
//var thePoly = features[0].geometry;
//var theExtent = thePoly.getExtent().expand(2); //Zoom out slightly from the polygon's extent
//map.setExtent(theExtent);
});
}
};
});
</script>
</head>
<body class="claro">
<div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline', gutters:false" style="padding:0px;margin:0px;">
<div id="header" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'" style="overflow:hidden;border:none;border-bottom: 3px solid #CC9900;font-family: Windows;font-size:14pt; color: #FFFFFF;background: #000000; "> Select a State and total Acres farmed:
<input id="uniqueValuesSelect" data-dojo-type="dijit.form.ComboBox" value="statename" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, 'statename');" />
<input id="uniqueValuesSelect2" data-dojo-type="dijit.form.ComboBox" value="FarmedAcres" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect2').value, 'FarmedAcres');" />
</div>
<div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'left'" style="width:100%;height:95%;border:none;padding:0px;margin:0px;"></div>
</div>
</body>
</html>
You need to have access to both comboboxes so you can do something like this:
app = {
zoomRow: function(stateId, acresId){
crops.clearSelection();
var query = new Query();
query.where = "STATE='" + (stateId).toString() + "' AND TotalFarmedAcres='" + (acresId).toString() + "'";
console.info(query.where);
query.returnGeometry = true;
crops.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (features) {
//var thePoly = features[0].geometry;
//var theExtent = thePoly.getExtent().expand(2); //Zoom out slightly from the polygon's extent
//map.setExtent(theExtent);
});
}
};
this means that the html should be something like this
<input id="uniqueValuesSelect" data-dojo-type="dijit.form.ComboBox" value="statename" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, document.getElementById('uniqueValuesSelect2').value);" />
<input id="uniqueValuesSelect2" data-dojo-type="dijit.form.ComboBox" value="FarmedAcres" onchange="app.zoomRow(document.getElementById('uniqueValuesSelect').value, document.getElementById('uniqueValuesSelect2').value);" />
Add corresponding validations to stateId, acresId for avoiding null or undefined values

ajax - How can I build a chat with Ajax and settimeout without the process taking a lot of virtual memory?

I'm trying to build a chat based on AJAX that receives data every second by settimeout.
I wrote a basic code where there is a number that increases each second of the number obtained from the php page2.
I checked it from my computer by opening the file in 3 different browsers and saw that it takes a lot of virtual memory from the server. My fear is what will happen if I build a real chat in this format and 50 people simultaneously enter?
I know that setTimeout takes a lot of memory, is there any other way to build chat? Or can I improve what I did?
I would be very happy to answer!
that's what i did:
<body>
<h1 id='number'>0</h1>
<script>
function ajax() {
if (window.XMLHttpRequest) {
var a = new XMLHttpRequest()
} else {
var a = new ActivXObject('Microsoft.XMLHTTP')
}
return a
}
var settime = 1000;
var myTime;
ajaxMain();
function ajaxMain() {
xmlhttp = ajax();
xmlhttp.onreadystatechange = function() {
if (((xmlhttp.readyState == 4) || (xmlhttp.readyState == 0)) && (xmlhttp.status == 200)) {
if (xmlhttp.responseText) {
id('mmm').innerHTML = (xmlhttp.responseText) * 1 + (id('number').innerHTML) * 1;
myTime = setTimeout('ajaxMain()', settime)
}
} else {
if (xmlhttp.responseText.match(/^\<\!/)) {
clearTimeout(myTime);
myTime = setTimeout('ajaxMain()', settime)
}
}
}
xmlhttp.open('GET', 'page2.php', true)
xmlhttp.send()
}
</script>
</body>
</html>
page2.php:
<?php
echo 1
?>
Thier is a full guide how to create an AJAX based chat system in PHP by Ashraf Gheith,
I'll quote:
CREATE TABLE `chat` (
`id` INT(9) NOT NULL AUTO_INCREMENT ,
`usrname` VARCHAR(255) NOT NULL ,
`color` VARCHAR(6) NOT NULL ,
`chattext` TEXT NOT NULL ,
`chattime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
) ENGINE = MyISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci;
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "/refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
body{
margin: 0;
padding: 0;
}
#view_ajax {
display: block;
overflow: auto;
width: 500px;
height: 300px;
border: 1px solid #333;
margin: 0 auto;
margin-top: 20px;
}
#ajaxForm{
display: block;
margin: 0 auto;
width: 500px;
height: 50px;
margin-top: 10px;
}
#chatInput{
width: 454px;
}
<html>
<head>
<title>Chat Room Example</title>
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<div id="view_ajax"></div>
<div id="ajaxForm">
<input type="text" id="chatInput" /><input type="button" value="Send" id="btnSend" />
</div>
</body>
</html>
The full guide will be on this link

jquery easyui datagrid cannot show data with the method'loadData'

I want to use datagrid to show some json data, And for some other reason I used the method 'loadData' to load the fetched json. It seems that the json has been fetched successfully (the browser alert correctly )but the following code can't work and the table(#dg) is blank.
#(category:String)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title id="category">#category</title>
<link rel="stylesheet" type="text/css" href="#routes.Assets.at("themes/default/easyui.css")">
<link rel="stylesheet" type="text/css" href="#routes.Assets.at("themes/icon.css")">
<style type="text/css">
body {
margin: 0px;
}
a {
color: #21759b;
text-decoration: none;
}
a:hover {
color: #0f3647;
text-decoration: underline;
}
</style>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="#routes.Assets.at("js/jquery.easyui.min.js")"></script>
<script type="text/javascript" src="#routes.Assets.at("js/datagrid-scrollview.js")"></script>
#*<script type="text/javascript" src="#routes.Assets.at(js/jquery.flot.min.js)"></script>*#
#*<script type="text/javascript" src="#routes.Assets.at(js/jquery.flot.time.min.js)"></script>*#
<script type="text/javascript" src="#routes.Assets.at("js/jquery.mousewheel.min.js")"></script>
<script type="text/javascript">
var field; //当前排序字段
var rows; //数据
var scrollLeft = 0; //横向滚动条位置,可恢复
var scrollEvent = function(e) { //滚动条事件
scrollLeft = $(this).scrollLeft();
};
//阻止连带滚动外部窗口
var preventScrollParent = function(e, d) {
var t = $(this);
if (d > 0 && t.scrollTop() <= 0) {
e.preventDefault();
} else {
if (d < 0 && (t.scrollTop() >= t.get(0).scrollHeight - t.innerHeight())) {
e.preventDefault();
}
}
};
$(function () {
// if ( parent.location.hostname != self.location.hostname ) {
// self.location = "/nopermission.html" ;
// }
field = "commentnum" ;
$("#dg").width($(self).width())
.height($(self).height())
.datagrid({
url: "http://localhost:9000/json/"+ $("#category" ).text() + "/" + field,
method:"GET",
loadMsg : 'Loading',
view : scrollview,
pageSize : 50,
autoRowHeight : false,
rownumbers : true,
singleSelect : true,
border : false,
striped : true,
onLoadSuccess : loadFinish,
columns:[[
{field:'id',title:'id',width:100},
{field:'name',title:'名字',width:400},
{field:'url',title:'访问购买',width:220,align:'right'},
// {field:'imgsrc',title:'图片',width:100,align:'right'},
{field:'price',title:'价格',width:60,align:'right'},
{field:'commentnum',title:'评论数',width:60,align:'right'},
{field:'likerate',title:'好评率',width:60,align:'right'},
{field:'category',title:'品类',width:60,align:'right'}
]]
}) ;
setTimeout(loaddata, 50);
});
//加载某列排序的数据
function loaddata() {
$("#dg").datagrid("loading");
$.getJSON("http://localhost:9000/json/"+ $("#category" ).text() + "/" + field, {}, function(result) {
rows = result.rows;
$("#dg").datagrid('loadData', rows);
});
}
//加载完成后处理
function loadFinish() {
$("#dg").datagrid("loaded");
$(".datagrid-view2 .datagrid-body").scrollLeft(scrollLeft);
$(".datagrid-header-row>td").css("font-weight", "normal");
$(".datagrid-header-row>td[field='" + field + "'").css("font-weight", "bold");
$(".datagrid-header-row>td").click(function() {
clickTitle($(this));
});
$(".datagrid-row a").click(function(e) {
e.stopPropagation();
})
$(".datagrid-view2 .datagrid-body").scroll(scrollEvent);
$(".datagrid-view2 .datagrid-body").bind('mousewheel', preventScrollParent);
}
//标题点击排序事件
function clickTitle(title) {
if (title.attr("field") && title.attr("field") != field && (title.attr("field") == "price"||title.attr("field")=="likerate"||title.attr("field")=="commentnum")) {
scrollLeft = $(".datagrid-view2 .datagrid-body").scrollLeft();
field = title.attr("field");
$(".datagrid-view2 .datagrid-body").unbind("scroll", scrollEvent);
$(".datagrid-view2 .datagrid-body").unbind('mousewheel', preventScrollParent);
loaddata();
}
}
//当前排序列加粗
function cellStyle(colname) {
return function(value, row, index) {
if (colname == field) return 'font-weight:bold;';
else return '';
}
}
</script>
</head>
<body>
<table id="dg"></table>
</body>
</html>

replacing selector 'ul:first-child' with class '.list_wrapper:first-child'

I have a box with text within that scrolling up like the old known marquee tag.
I am using the jquery scrollbox that I found on this website:
http://wmh.github.io/jquery-scrollbox/
now, in my css file I want to replace the ul & il tags with classes, say: .list_wrapper would be instead of ul, and .list would be instead of li, so far so good...
after modifying the css, the scroller stopped to work, i found that i need to modify the "jquery.scrollbox.js" file too, but my knowledge in js is basic.
my page:
<!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="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="/js/jquery.scrollbox.js" type="text/javascript"></script>
<style type="text/css">
#marquee {
height: 180px;
overflow: hidden;
margin: 0;
}
#marquee .list_wrapper {
width: 165px;
line-height: 25px;
list-style-type: none;
padding: 5;
margin: 0;
overflow: hidden;
}
#marquee .list {
overflow: hidden;
}
</style>
<script type="text/javascript">
$(function () {
$('#marquee').scrollbox({
linear: true,
step: 1,
delay: 0,
speed: 65
});
});
</script>
</head>
<body>
<div id="marquee">
<div class="list_wrapper">
<div class="list">• text 1</div>
<div class="list">• text 2</div>
<div class="list">• text 3</div>
<div class="list">• text 4</div>
<div class="list">• text 5</div>
<div class="list">• text 6</div>
</div>
</body>
</html>
heres ths js file (I think there's something to do with the "('ul:first-child') and ('li:first-child'):
/*!
* jQuery Scrollbox
* (c) 2009-2013 Hunter Wu <hunter.wu#gmail.com>
* MIT Licensed.
*
* http://github.com/wmh/jquery-scrollbox
*/
(function($) {
$.fn.scrollbox = function(config) {
//default config
var defConfig = {
linear: false, // Scroll method
startDelay: 2, // Start delay (in seconds)
delay: 3, // Delay after each scroll event (in seconds)
step: 5, // Distance of each single step (in pixels)
speed: 32, // Delay after each single step (in milliseconds)
switchItems: 1, // Items to switch after each scroll event
direction: 'vertical',
distance: 'auto',
autoPlay: true,
onMouseOverPause: true,
paused: false,
queue: null
};
config = $.extend(defConfig, config);
config.scrollOffset = config.direction === 'vertical' ? 'scrollTop' : 'scrollLeft';
if (config.queue) {
config.queue = $('#' + config.queue);
}
return this.each(function() {
var container = $(this),
containerUL,
scrollingId = null,
nextScrollId = null,
paused = false,
backward,
forward,
resetClock,
scrollForward,
scrollBackward;
if (config.onMouseOverPause) {
container.bind('mouseover', function() { paused = true; });
container.bind('mouseout', function() { paused = false; });
}
containerUL = container.children('ul:first-child');
scrollForward = function() {
if (paused) {
return;
}
var curLi,
i,
newScrollOffset,
scrollDistance,
theStep;
curLi = containerUL.children('li:first-child');
scrollDistance = config.distance !== 'auto' ? config.distance :
config.direction === 'vertical' ? curLi.height() : curLi.width();
// offset
if (!config.linear) {
theStep = Math.max(3, parseInt((scrollDistance - container[0][config.scrollOffset]) * 0.3, 10));
newScrollOffset = Math.min(container[0][config.scrollOffset] + theStep, scrollDistance);
} else {
newScrollOffset = Math.min(container[0][config.scrollOffset] + config.step, scrollDistance);
}
container[0][config.scrollOffset] = newScrollOffset;
if (newScrollOffset >= scrollDistance) {
for (i = 0; i < config.switchItems; i++) {
if (config.queue && config.queue.hasChildNodes() && config.queue.getElementsByTagName('li').length > 0) {
containerUL.append(config.queue.getElementsByTagName('li')[0]);
containerUL.remove(containerUL.children('li:first-child'));
} else {
containerUL.append(containerUL.children('li:first-child'));
}
}
container[0][config.scrollOffset] = 0;
clearInterval(scrollingId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
}
};
// Backward
// 1. If forwarding, then reverse
// 2. If stoping, then backward once
scrollBackward = function() {
if (paused) {
return;
}
var curLi,
i,
liLen,
newScrollOffset,
scrollDistance,
theStep;
// init
if (container[0][config.scrollOffset] === 0) {
liLen = containerUL.children('li').length;
for (i = 0; i < config.switchItems; i++) {
containerUL.children('li:last-child').insertBefore(containerUL.children('li:first-child'));
}
curLi = container.children('li:first-child');
scrollDistance = config.distance !== 'auto' ?
config.distance :
config.direction === 'vertical' ? curLi.height() : curLi.width();
container[0][config.scrollOffset] = scrollDistance;
}
// new offset
if (!config.linear) {
theStep = Math.max(3, parseInt(container[0][config.scrollOffset] * 0.3, 10));
newScrollOffset = Math.max(container[0][config.scrollOffset] - theStep, 0);
} else {
newScrollOffset = Math.max(container[0][config.scrollOffset] - config.step, 0);
}
container[0][config.scrollOffset] = newScrollOffset;
if (newScrollOffset === 0) {
clearInterval(scrollingId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
}
};
forward = function() {
clearInterval(scrollingId);
scrollingId = setInterval(scrollForward, config.speed);
};
backward = function() {
clearInterval(scrollingId);
scrollingId = setInterval(scrollBackward, config.speed);
};
resetClock = function(delay) {
config.delay = delay || config.delay;
clearTimeout(nextScrollId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
};
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.startDelay * 1000);
}
// bind events for container
container.bind('resetClock', function(delay) { resetClock(delay); });
container.bind('forward', function() { clearTimeout(nextScrollId); forward(); });
container.bind('backward', function() { clearTimeout(nextScrollId); backward(); });
container.bind('speedUp', function(speed) {
if (typeof speed === 'undefined') {
speed = Math.max(1, parseInt(config.speed / 2, 10));
}
config.speed = speed;
});
container.bind('speedDown', function(speed) {
if (typeof speed === 'undefined') {
speed = config.speed * 2;
}
config.speed = speed;
});
});
};
}(jQuery));
thank you!
open jquery-scrollbox.js and try to change by the hand (not automatically) all ul&li tag on div tag

Categories

Resources