How to load data on scroll in select2 dropdown without using pagination? - ajax

I have more than 1000 rows and it is taking much time in taking AJAX response and loading data in dropdwon.
I am using below code .
function fillperson() {
$.ajax({
// delay: 250 ,
url: Url,
type: "GET",
minimumInputLength:0,
data: { isGetAll: false, Id1: 0, ID2:0},
complete: function (data) {
var ele = document.getElementById('ddlperson');
ele.innerHTML = '';
var persondata = JSON.parse(data.responseText);
ele.innerHTML = '<option value="' + -1 + '">Select Person</option>';
ele.innerHTML += '<option value="' + 0 + '">ALL Person</option>';
var totaldata = persondata.length;
var i = 0;
for ( i ; i < data.length; i++) {
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['Id'] + '">' +data[i]['name'] + '(' + data[i]['code'] + ')' + '</option>';
}
$('#ddperson').select2();
},
});
}

Related

How can I refresh the leaflet marker value

Good evening,
I am using Leaflet.js to localize the station which measure the temperature of bud. The app needs to generate an alarm when the temperature is too low.
The user can view the temperature shown in markers.
The app needs to request a MySQL database to collect the needed records.
On each refreshed, I do not want to reload the map, because the station does not move.
Is there a way to reload only the makers, or to update the value?
Here is how I load my map
function refreshMap(){
loadMap();
}
function loadMap(){
var get_map_center = [];
$.ajax({
type: "POST",
url: "https://sub.domain.ch/sql/mysql.php",
crossDomain: true,
success: result,
error: error,
dataType: "json"
});
function error(data)
{
alert("Error getting datas from DB");
console.log("Error getting datas from DB");
console.log(data);
showMap(46.187164,5.997526,null);
}
function result(data){
console.info("data:",data);
for(var y=0; y < data.map_center.length; y++)
{
get_map_center.push(data.map_center[y]);
}
var allMarkers = [];
var markers = L.markerClusterGroup({
showCoverageOnHover: false
});
// THIS ADD AN IMAGE IF THE TEMPERATURE ARE NORMAL; LIMITE OR TO LOW
var nhtml = '<img src="img/property-types/vineyard.png">';
for (var i = 0; i < data.properties.length; i++)
{
allMarkers.push(L.latLng(data.properties[i]['la'], data.properties[i]['lo']));
if((data.properties[i]['b1']>=data.properties[i]['se'] && data.properties[i]['b1'] < data.properties[i]['se']+1) ||
(data.properties[i]['b2']>=data.properties[i]['se'] && data.properties[i]['b2'] < data.properties[i]['se']+1) ||
(data.properties[i]['b3']>=data.properties[i]['se'] && data.properties[i]['b3'] < data.properties[i]['se']+1) ||
(data.properties[i]['b4']>=data.properties[i]['se'] && data.properties[i]['b4'] < data.properties[i]['se']+1)
)
{
nhtml = '<img src="img/property-types/vineyard-orange.png">';
}
if(((data.properties[i]['b1'] < data.properties[i]['se']) && data.properties[i]['b1'] != null) ||
((data.properties[i]['b2'] < data.properties[i]['se']) && data.properties[i]['b2'] != null) ||
((data.properties[i]['b3'] < data.properties[i]['se']) && data.properties[i]['b3'] != null) ||
((data.properties[i]['b4'] < data.properties[i]['se']) && data.properties[i]['b4'] != null)
)
{
nhtml = '<img src="img/property-types/vineyard-red.png">';
}
else{
nhtml = '<img src="img/property-types/vineyard.png">';
}
var _icon = L.divIcon({
//html: '<img src="' + locations[i][7] +'">',
html: nhtml,
iconSize: [40, 48],
iconAnchor: [20, 48],
popupAnchor: [0, -48]
});
var title = data.properties[i]['station'];
var marker = L.marker(new L.LatLng(data.properties[i]['la'],data.properties[i]['lo']), {
title: title,
icon: _icon
});
var str ='';
if(data.properties[i]['b1'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b1'] + '°C</div>');
}
if(data.properties[i]['b2'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b2'] + '°C</div>');
}
if(data.properties[i]['b3'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b3'] + '°C</div>');
}
if(data.properties[i]['b4'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b4'] + '°C</div>');
}
marker.bindPopup(
'<div class="property">' +
'' +
'<div class="property-image">' +
'<img src="img/stations/station-' + data.properties[i]['id_station'] + '.jpg">' +
'</div>' +
'<div class="overlay">' +
'<div class="info">' +
'<h3>' + data.properties[i]['station'] + '</h3>' +
'<p>' + data.properties[i]['da'] + '</p>' +
// '<figure>' + data.properties[i]['la'] + ' ' + data.properties[i]['lo'] +'</figure>' +
str +
'<p> <a data-field=' + data.properties[i]['id_field'] +'" data-station=' + data.properties[i]['id_station'] +'" href="https://bud.eco-sensors.ch/charts.php?field='+ data.properties[i]['id_field'] +'#st-'+ data.properties[i]['id_station'] +'">Historique</a></p>' +
//'<div class="tag"> ' + data.properties[i]['se'] + '°C</div>' +
'</div>' +
'</div>' +
'' +
'</div>',{autoClose: true, closeOnClick: true, closeButton: true}
);
/*
*. THOSE VALUES NEEED TO BE UPDATED
*/
var val = '';
if(!isEmpty(data.properties[i]['b4']))
{
val = data.properties[i]['b4'] +'°C ';
}
if(!isEmpty(data.properties[i]['b1']))
{
val = val + data.properties[i]['b1'] +'°C ';
}
if(!isEmpty(data.properties[i]['su']))
{
val = val + data.properties[i]['su'] +'W/m2 ';
}
if(!isEmpty(data.properties[i]['an']))
{
val = val + data.properties[i]['an'] +'km/h ';
}
if(!isEmpty(data.properties[i]['sb']))
{
val = val + data.properties[i]['sb'] +'°C (B)';
}
if(!isEmpty(data.properties[i]['sl']))
{
val = val + data.properties[i]['sl'] +'°C (F)';
}
marker.bindTooltip(val, {direction: 'bottom', permanent: true});
markers.addLayer(marker);
}
showMap(get_map_center[0][0],get_map_center[0][1], markers);
} // End result
}
/*
* BUILD THE MAP AFTER THE FUNCTION 'result' OF AJAX
* I need it to make sure that the map is initialized when AJAX finishes loading
*/
function showMap(lat,lng, markers){
var map = L.map('map', {
//center: [46.187164,5.997526],
center: [lat,lng],
zoom: 14,
scrollWheelZoom: false
});
// add an OpenStreetMap tile layer
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
//subdomains: '0123',
maxZoom: 20,
attribution: 'OpenStreetMap contributors, CC-BY-SA'
}).addTo(map);
if(markers!=null){
map.addLayer(markers);
}
}
Maybe it can done better, but this works fine, except that I need to update the value in the bind tooltips when I make a new MySQL request to get the new value.
I hope I clearly explained my needs ;)
Is possible to reload the markers (or the value) without reloading the full map?
Many thanks
Create your map outside (=global), not in a function
var map = L.map('map', {
//center: [46.187164,5.997526],
center: [0, 0],
zoom: 14,
scrollWheelZoom: false
});
// add an OpenStreetMap tile layer
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
//subdomains: '0123',
maxZoom: 20,
attribution: 'OpenStreetMap contributors, CC-BY-SA'
}).addTo(map);
function loadMap() {
...
Create a featureGroup where you add the markers instead adding them to the map:
var map = ...
// add an OpenStreetMap tile layer
L.tileLayer( ... ).addTo(map);
var fg = L.featureGroup().addTo(map);
function loadMap() {
...
When loadMap is called, clear the featureGroup and then add the markers to it (then the old markers are removed and the new one are added => refresh Markers)
Instead of showMap:
function result(){
...
marker.bindTooltip(val, {direction: 'bottom', permanent: true});
markers.addLayer(marker);
}
showMap(get_map_center[0][0],get_map_center[0][1], markers);
} // End result
}
us this code:
function result(){
...
marker.bindTooltip(val, {direction: 'bottom', permanent: true});
markers.addLayer(marker);
}
fg.clearLayers();
fg.addLayer(markers);
map.panTo(get_map_center[0][0],get_map_center[0][1]);
} // End result
}
When you don't want that the map center is refreshed you can use a flag:
var map = ...
var fg = ...
var centered = false;
...
function result(){
...
fg.clearLayers();
fg.addLayer(markers);
if(!centered){
centered = true;
// map is centered only once
map.panTo(get_map_center[0][0],get_map_center[0][1]);
}
Summary:
var map = L.map('map', {
//center: [46.187164,5.997526],
center: [0, 0],
zoom: 14,
scrollWheelZoom: false
});
// add an OpenStreetMap tile layer
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
//subdomains: '0123',
maxZoom: 20,
attribution: 'OpenStreetMap contributors, CC-BY-SA'
}).addTo(map);
var fg = L.featureGroup().addTo(map);
var centered = false;
function refreshMap(){
loadMap();
}
function loadMap(){
var get_map_center = [];
$.ajax({
type: "POST",
url: "https://sub.domain.ch/sql/mysql.php",
crossDomain: true,
success: result,
error: error,
dataType: "json"
});
function error(data)
{
alert("Error getting datas from DB");
console.log("Error getting datas from DB");
console.log(data);
showMap(46.187164,5.997526,null);
}
function result(data){
console.info("data:",data);
for(var y=0; y < data.map_center.length; y++)
{
get_map_center.push(data.map_center[y]);
}
var allMarkers = [];
var markers = L.markerClusterGroup({
showCoverageOnHover: false
});
// THIS ADD AN IMAGE IF THE TEMPERATURE ARE NORMAL; LIMITE OR TO LOW
var nhtml = '<img src="img/property-types/vineyard.png">';
for (var i = 0; i < data.properties.length; i++)
{
allMarkers.push(L.latLng(data.properties[i]['la'], data.properties[i]['lo']));
if((data.properties[i]['b1']>=data.properties[i]['se'] && data.properties[i]['b1'] < data.properties[i]['se']+1) ||
(data.properties[i]['b2']>=data.properties[i]['se'] && data.properties[i]['b2'] < data.properties[i]['se']+1) ||
(data.properties[i]['b3']>=data.properties[i]['se'] && data.properties[i]['b3'] < data.properties[i]['se']+1) ||
(data.properties[i]['b4']>=data.properties[i]['se'] && data.properties[i]['b4'] < data.properties[i]['se']+1)
)
{
nhtml = '<img src="img/property-types/vineyard-orange.png">';
}
if(((data.properties[i]['b1'] < data.properties[i]['se']) && data.properties[i]['b1'] != null) ||
((data.properties[i]['b2'] < data.properties[i]['se']) && data.properties[i]['b2'] != null) ||
((data.properties[i]['b3'] < data.properties[i]['se']) && data.properties[i]['b3'] != null) ||
((data.properties[i]['b4'] < data.properties[i]['se']) && data.properties[i]['b4'] != null)
)
{
nhtml = '<img src="img/property-types/vineyard-red.png">';
}
else{
nhtml = '<img src="img/property-types/vineyard.png">';
}
var _icon = L.divIcon({
//html: '<img src="' + locations[i][7] +'">',
html: nhtml,
iconSize: [40, 48],
iconAnchor: [20, 48],
popupAnchor: [0, -48]
});
var title = data.properties[i]['station'];
var marker = L.marker(new L.LatLng(data.properties[i]['la'],data.properties[i]['lo']), {
title: title,
icon: _icon
});
var str ='';
if(data.properties[i]['b1'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b1'] + '°C</div>');
}
if(data.properties[i]['b2'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b2'] + '°C</div>');
}
if(data.properties[i]['b3'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b3'] + '°C</div>');
}
if(data.properties[i]['b4'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b4'] + '°C</div>');
}
marker.bindPopup(
'<div class="property">' +
'' +
'<div class="property-image">' +
'<img src="img/stations/station-' + data.properties[i]['id_station'] + '.jpg">' +
'</div>' +
'<div class="overlay">' +
'<div class="info">' +
'<h3>' + data.properties[i]['station'] + '</h3>' +
'<p>' + data.properties[i]['da'] + '</p>' +
// '<figure>' + data.properties[i]['la'] + ' ' + data.properties[i]['lo'] +'</figure>' +
str +
'<p> <a data-field=' + data.properties[i]['id_field'] +'" data-station=' + data.properties[i]['id_station'] +'" href="https://bud.eco-sensors.ch/charts.php?field='+ data.properties[i]['id_field'] +'#st-'+ data.properties[i]['id_station'] +'">Historique</a></p>' +
//'<div class="tag"> ' + data.properties[i]['se'] + '°C</div>' +
'</div>' +
'</div>' +
'' +
'</div>',{autoClose: true, closeOnClick: true, closeButton: true}
);
/*
*. THOSE VALUES NEEED TO BE UPDATED
*/
var val = '';
if(!isEmpty(data.properties[i]['b4']))
{
val = data.properties[i]['b4'] +'°C ';
}
if(!isEmpty(data.properties[i]['b1']))
{
val = val + data.properties[i]['b1'] +'°C ';
}
if(!isEmpty(data.properties[i]['su']))
{
val = val + data.properties[i]['su'] +'W/m2 ';
}
if(!isEmpty(data.properties[i]['an']))
{
val = val + data.properties[i]['an'] +'km/h ';
}
if(!isEmpty(data.properties[i]['sb']))
{
val = val + data.properties[i]['sb'] +'°C (B)';
}
if(!isEmpty(data.properties[i]['sl']))
{
val = val + data.properties[i]['sl'] +'°C (F)';
}
marker.bindTooltip(val, {direction: 'bottom', permanent: true});
markers.addLayer(marker);
}
fg.clearLayers();
fg.addLayer(markers);
if(!centered){
centered = true;
// map is centered only once
map.panTo(get_map_center[0][0],get_map_center[0][1]);
}
} // End result
}
Now you can call loadMap how often you want
So many thank, that works fine. That's great.
I just add to correct this
map.panTo(get_map_center[0][0],get_map_center[0][1]);
to
map.panTo([get_map_center[0][0],get_map_center[0][1]]);
Finally, the map was not show completely
I had that issue when I worked with leaflet, .... some year ago, and I found in my old code the following, and I added it after panto()
map.panTo([get_map_center[0][0] , get_map_center[0][1]]);
map.invalidateSize();
I did not know, if it would solve the problem. But I tried and the map is now well (and fully) displayed
I look at the doc
map.invalidateSize()
Checks if the map container size changed and
updates the map if so — call it after you've changed the map size
dynamically, also animating pan by default. If options.pan is false,
panning will not occur. If options.debounceMoveend is true, it will
delay moveend event so that it doesn't happen often even if the method
is called many times in a row.
and it seems to be right choose, isn't?
So many thanks, that helped a lot!!!

Getting a 500 Internal Server Error Jquery

While everything is running in the software, I get this error when I make a selection from the dropdown list in only one part. Where am I making a mistake? or is it a server error?
I have not received this error in any Laravel before. When trying to get something from a dropdown list, this error comes to the console and there is no reaction on the site.
https://prnt.sc/vaujzf
<script type="text/javascript">
$("ul#product").siblings('a').attr('aria-expanded','true');
$("ul#product").addClass("show");
$("ul#product #adjustment-create-menu").addClass("active");
var lims_product_array = [];
var product_code = [];
var product_name = [];
var product_qty = [];
$('.selectpicker').selectpicker({
style: 'btn-link',
});
$('#lims_productcodeSearch').on('input', function() {
var warehouse_id = $('#warehouse_id').val();
temp_data = $('#lims_productcodeSearch').val();
if (!warehouse_id) {
$('#lims_productcodeSearch').val(temp_data.substring(0, temp_data.length - 1));
alert('Please select Warehouse!');
}
});
$('select[name="warehouse_id"]').on('change', function() {
var id = $(this).val();
$.get('getproduct/' + id, function(data) {
lims_product_array = [];
product_code = data[0];
product_name = data[1];
product_qty = data[2];
$.each(product_code, function(index) {
lims_product_array.push(product_code[index] + ' (' + product_name[index] + ')');
});
});
});
var lims_productcodeSearch = $('#lims_productcodeSearch');
lims_productcodeSearch.autocomplete({
source: function(request, response) {
var matcher = new RegExp(".?" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(lims_product_array, function(item) {
return matcher.test(item);
}));
},
response: function(event, ui) {
if (ui.content.length == 1) {
var data = ui.content[0].value;
$(this).autocomplete( "close" );
productSearch(data);
};
},
select: function(event, ui) {
var data = ui.item.value;
productSearch(data);
}
});
$("#myTable").on('input', '.qty', function() {
rowindex = $(this).closest('tr').index();
checkQuantity($(this).val(), true);
});
$("table.order-list tbody").on("click", ".ibtnDel", function(event) {
rowindex = $(this).closest('tr').index();
$(this).closest("tr").remove();
calculateTotal();
});
$(window).keydown(function(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function() {
if (this === e.target) {
focusNext = true;
}
else if (focusNext) {
$(this).focus();
return false;
}
});
return false;
}
}
});
$('#adjustment-form').on('submit', function(e) {
var rownumber = $('table.order-list tbody tr:last').index();
if (rownumber < 0) {
alert("Please insert product to order table!")
e.preventDefault();
}
});
function productSearch(data) {
$.ajax({
type: 'GET',
url: 'lims_product_search',
data: {
data: data
},
success: function(data) {
var flag = 1;
$(".product-code").each(function(i) {
if ($(this).val() == data[1]) {
rowindex = i;
var qty = parseFloat($('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
checkQuantity(qty);
flag = 0;
}
});
$("input[name='product_code_name']").val('');
if(flag) {
var newRow = $("<tr>");
var cols = '';
cols += '<td>' + data[0] + '</td>';
cols += '<td>' + data[1] + '</td>';
cols += '<td><input type="number" class="form-control qty" name="qty[]" value="1" required step="any" /></td>';
cols += '<td class="action"><select name="action[]" class="form-control act-val"><option value="-">{{trans("file.Subtraction")}}</option><option value="+">{{trans("file.Addition")}}</option></select></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger">{{trans("file.delete")}}</button></td>';
cols += '<input type="hidden" class="product-code" name="product_code[]" value="' + data[1] + '"/>';
cols += '<input type="hidden" class="product-id" name="product_id[]" value="' + data[2] + '"/>';
newRow.append(cols);
$("table.order-list tbody").append(newRow);
rowindex = newRow.index();
calculateTotal();
}
}
});
}
function checkQuantity(qty) {
var row_product_code = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(2)').text();
var action = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.act-val').val();
var pos = product_code.indexOf(row_product_code);
if ( (qty > parseFloat(product_qty[pos])) && (action == '-') ) {
alert('Quantity exceeds stock quantity!');
var row_qty = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val();
row_qty = row_qty.substring(0, row_qty.length - 1);
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(row_qty);
}
else {
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(qty);
}
calculateTotal();
}
function calculateTotal() {
var total_qty = 0;
$(".qty").each(function() {
if ($(this).val() == '') {
total_qty += 0;
} else {
total_qty += parseFloat($(this).val());
}
});
$("#total-qty").text(total_qty);
$('input[name="total_qty"]').val(total_qty);
$('input[name="item"]').val($('table.order-list tbody tr:last').index() + 1);
}
</script>

How to loop 2 Dimensional Array on Google Script

There is a problem with my run time execution in my code. It takes too long to finish, since I have to loop a large amounts of data to look for matching data. I used array on the first loop value though, I don't know how to array the second value without affecting the first array.
Name of the first array : Source
Name of the Second array : Target
Here is my Code:
function inactive_sort_cebu() {
var ss = SpreadsheetApp.openById('169vIeTMLK4zN5VGCw1ktRteCwMToU8eGABFDxg52QBk');
// var sheet = ss.getSheets()[0];// Manila Roster
var sheet2 = ss.getSheets()[1];// Cebu Roster
var column = sheet2.getRange("C1:C").getValues();
var last = column.filter(String).length;
// -----------------------------------------------------------
var ss1 = SpreadsheetApp.openById('153ul2x2GpSopfMkCZiXCjmqdPTYhx4QiOdP5SBYzQkc');
// var sched_sheet = ss1.getSheets()[0];// ScheduledForm_Manila
var sched_sheet2 = ss1.getSheets()[1];// ScheduledForm_Cebu
var column2 = sched_sheet2.getRange("C1:C").getValues();
var last2 = column2.filter(String).length;
//// -------------------------Manila-Roster---------------------------------
var i= 2;
var column3 = sched_sheet2.getRange("J1:J").getValues();
var a = column3.filter(String).length - 1;
// var a = 0;
try{
var source = sched_sheet2.getRange("C2:C").getValues();
for (a;a<=last2;){
/// this is the code that i need to array without affecting the other array which is the source variable
var target = sheet2.getRange("C"+ i).getValue();
if(source[a] == target){
// Get "No Schedule Request data on Cell H
var data = sched_sheet2.getRange("H"+(a+2)).getValue();
// Get "Schedule Request data on Cell F
var data1 = sched_sheet2.getRange("F"+(a+2)).getValue();
var condition_1 = sched_sheet2.getRange("D"+(a+2)).getValue();
var condition_2 = sched_sheet2.getRange("G"+(a+2)).getValue();
var format_Con_2 = Utilities.formatDate(condition_2, 'Asia/Manila', 'm/dd/yyyy');
var condition_3 = sched_sheet2.getRange("K"+ (a+2)).getValue();
var date = new Date();
var date_Manila = Utilities.formatDate(date, 'Asia/Manila', 'm/dd/yyyy');
if(condition_1 == "No Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("N - "+ data);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else if (condition_1 == "Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("Y - "+data1);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else{a++;}
i=2;}
else {i++;}
}
This is a simple example of a web app that puts an editable spreadsheet on an HTML Page. Publish as a webapp. I loops through the 2D array that you get when you getValues from the getDataRange() method. In this case I'm just intertwining html into the mix.
Code.gs:
var SSID='SpreadsheetID';
var sheetName='Sheet Name';
function htmlSpreadsheet(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'dialog';
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode)
{
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
htmlss.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>

Pass function parameters for json fill drop down

How would pass the parameter into "foodName" from the function that sends the url and id? i.e. could you do something like the function:
call('/url/to/foodlist', "foodList", "food");
and replace
var input = item.food;?
Below is working code but would like a more general function then having to use part of name in the function (replace foodName so that it isn't in this function)
function call(url, id){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item.foodName;
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}
});
call('/url/to/foodlist', "foodList");
function call(url, id, paramName){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item[paramName]; // you can access to the properties using braces
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}

Twitter and jQuery , render tweeted links

I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });
Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
You need to parse the tweet content, find the urls and then put them in between yourself.
Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.
I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});

Resources