i wrote some codes in Codeigniter to assign query result into each polygons with $.getJSON but i found some problems.
Here is my $.getJSON code
$.getJSON("<?php echo base_url(); ?>Request/showData", function(data) {
var area_data = new Array(3);
var total_data = new Array(3);
for (var i = 0; i < data.length; i++) {
area_data[i] = data[i].Area;
total_data[i] = data[i].total;
}
layer.bindPopup(area_data + ':' + total_data);
})
from this js script, i got this kind of result
The expected result is each polygon shows its alphabet and value same like the red color. but right now i have each polygon shows all alphabets and values from query.
model function
public function map()
{
$query = $this->db->query(
"SELECT Area, sum(Value) as total from ( select Area,Value from try_1 union all select Area,Value from try_2 ) view_vall group by Area"
);
return $query->result_array();
}
controller function
public function showData()
{
$aa = $this->model_request->map();
echo json_encode($aa);
}
Thanks in advance
turns out that i found the answer..
it needs to add conditional with if after the looping and add variable to put value inside bindpopup.
$.getJSON("<?php echo base_url(); ?>Request/showData", function(data) {
var area_data = new Array(3);
var total_data = new Array(3);
for (var i = 0; i < data.length; i++) {
area_data[i] = data[i].Area;
total_data[i] = data[i].total;
}
var popup;
if (feature.properties.Area == 'A') {
popup = area_data[0] + ':' + total_data[0];
} else if (feature.properties.Area == 'B') {
popup = area_data[1] + ':' + total_data[1];
} else {
popup = area_data[2] + ':' + total_data[2];
}
layer.bindPopup(popup);
})
Related
I am setting up an HTML dropdown displaying items from our Google Cloud SQL data. However, there is something wrong with my code and can't figure it out.
Here is my code:
CODE.GS
function doGet(e){
var listfiltered = subjectfromDB(subjectdb)
var tmp = HtmlService.createTemplateFromFile("page");
tmp.listfiltered = listfiltered;
return tmp.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=device-width, initial-scale=1');
}
function subjectfromDB(){
var connectionName = 'xxxxxx';
var user = 'xxxxx';
var userPwd = 'xxxxx';
var db = 'xxxxxx';
var dbUrl = 'jdbc:google:mysql://' + connectionName + '/' + db;
var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery('SELECT SubjectName FROM Subject WHERE SubjectArchived != true');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
var rowString = '';
for (var col = 0; col < numCols; col++) {
rowString += results.getString(col + 1) + '\t';
}
Logger.log(rowString);
}
results.close();
stmt.close();
return rowString;
}
HTML
<select id="case1" name="case" class="validate browser-default" required>
<option value="" disabled selected>Select Case</option>
<? for (var i=0;i<listfiltered.length;i++){ ?>
<option><?= listfiltered[i]; ?></option>
<? } ?>
</select>
</div>
It only returns 1 item on the dropdown list. By the way, I used google apps script here.
Any help will be appreciated. Thank you very much!
Problem
Watch your types closely - subjectfromDB() returns a String, which you then pass to the template via listfiltered property. Once the template evaluates, your loop starts to iterate over listfiltered, which means that it iterates over each character in the String.
Solution
var options = [];
while (results.next()) {
var rowString = '';
for (var col = 0; col < numCols; col++) {
rowString += results.getString(col + 1) + '\t';
}
options.push(rowString));
}
results.close();
stmt.close();
return options;
Notes
In your code sample, the subjectfromDB function is called with subjectdb as its first argument, but it is declared to accept no parameters - please, check if this is intentional.
I created 3 objects that nest arrays of one another - we'll call them Table, Row and Column so I can show you what's wrong. Table has an array of Rows, and Row has an array of Columns. When I call properties of the Rows from Table, no problem. When I call properties of the Columns from Row, it says undefined, but in the debugger and the console it recognizes the object and it's properties. Maybe I've been staring at it too long but I can't see a fundamental difference.
I stripped the Table layer to be sure it wasn't an issue with nested objects. Here's the code, not working:
function Column()
{
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns)
{
this.columns = [];
this.columns = columns;
this.outputRows = function()
{
var temp = "<tr>";
for(var i = 0; i < this.columns.length; i++)
{
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
console.log("Problem: " + this.columns[i].content);
//yet the object exists, and has the correct properties:
console.log(this.columns[i]);
}
temp += "</tr>";
return temp;
};
}
function test()
{
var col = new Column();
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row([cols]);
console.log(row.outputRows());
}
Here is the interaction between the parent layer and the rows, working fine:
function Table(rows)
{
this.rows = [];
this.rows = rows;
this.outputTable = function()
{
var temp = "<table>";
for(var i = 0; i < this.rows.length; i++)
{
temp += this.rows[i].outputRows();
}
temp += "</table>";
return temp;
};
}
and the updated test function:
function test()
{
var column = new Column();
var cols = [column];
var row = new Row([cols]);
console.log(row.outputRows());
var rs = [row, row];
var table = new Table(rs);
console.log(table.outputTable());
}
Two rows print out as expected this way, with undefined inside each. I originally had column.content written as a function, it doesn't make a difference.
Please tell me what stupid mistake I'm missing here!
Change that line :
var row = new Row([cols])
into
var row = new Row(cols)
since cols is already an array, you don't need to put it in an array again.
function Column() {
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns) {
// removed this.columns = [] since you are assigning it in the next line
this.columns = columns;
this.outputRows = function() {
var temp = "<tr>";
for (var i = 0; i < this.columns.length; i++) {
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
}
temp += "</tr>";
return temp;
};
}
function test() {
var col = new Column()
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row(cols); // the problem was here
console.log(row.outputRows());
}
test()
My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);
I am trying to adjust the code in this question for my needs. I need to extract the title attributes from selected elements and post them but my attempt at adjusting it is not quite working...
function submit(id) {
var answers = document.getElementsByClassName("selected");
var answersobject = {qid: id}
for (var i = 0 ; i < answers.length ; i++){
var j = i + 1;
var ans = "a" + j;
answersobject[ans] = answers[i].getAttribute['title'];
}
var loc = "testsub.php";
$.redirectPost(loc, answersobject);
}
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
}
});
Currently it redirects but no data is being posted.
I am creating an app in which i am using jquery mobile autocomplete. To create the listview i am calling a function in js file. When a user enter the character in the input field it will call the js file and then i want to call another function which is return to access the data from data base and it will create and array object and this created array i want to pass back to the function called and then it will create an li base on that array.
Here is the code inside the demoautocomplete.js
function createlist(autocomplete_name){
var objdata=['user_name','user_id'];
$( "#"+autocomplete_name).on("listviewbeforefilter", function ( e, data ) {
var autocompleteData=new Array();
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
getdatafromtable(autocompleteData,value); var dataarray=getdatafromtable(autocompleteData);
if ( value && value.length > 1 )
{
$.mobile.loading('hide');
for(var j=0;j<dataarray.length;j++)
{
html +="<li id='"+dataarray[j].id+"'>"+dataarray[j].user_name+"</li>";
}
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
$.mobile.activePage.find('input[placeholder="Find a name..."]').attr('id','autocomplete');
}
$("ul>li").click(function()
{
var textval=$(this).text();
var id=$(this).attr('id');
$('#autocomplete').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
storeselectedid(id,autocompleteData);
});
});
}
function getdatafromtable(autocompleteData,value){
db.transaction(function(tx){
$.mobile.loading('show');
var selectQuery='select first_name||" "||last_name user_name,user_id from users where first_name like "%'+value+'%" or last_name like "%'+value+'%" limit 10';
var selectQuery1='select account_name user_name,account_id from crm_account where account_name like "%'+value+'%" limit 10';
tx.executeSql(selectQuery,[],function(tx,results){
var dataset=results.rows;
if(dataset.length>0){
for(var i=0;i<dataset.length;i++)
{
var item=dataset.item(i);
var element = new Object();
element['id']=autocomplete_name+"_"+i;
for(var j=0;j<objdata.length;j++)
{
element[objdata[j]]=item[objdata[j]];
}
autocompleteData[i]=element;
}
return autocompleteData;
}
});
}); }
here the script code in html from where js will be called:
$(function(){
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a name..."
data-filter-theme="d" >
</ul>
var autocomplete=$(document.createElement('ul')).attr('id',autocomplete_name);
autocomplete.attr('data-role','listview');
autocomplete.attr('data-inset',true);
autocomplete.attr('data-filter',true);
autocomplete.attr('data-filter-placeholder','Find a name');
autocomplete.appendTo("#contentDemo");
createlist(autocomplete_name); });
when getdatafromtablefunction is called it should create fill the data in the array object and pass that arrayobject back to the createlistfunction and then if loop should be executed.
here is the flow of code how it should work :
1. the page is loaded then when user enters a character in the input field.
2.it will go to thejs file then input value is assign to value variable. which i want to pass to the function getdatafromtable so base o that input it fetch the data from the database.
3.the retrive is stored in the array object than its pass back to the function from where it was called.
4.After retriving the array data it should create the li listview.
Any help is appreciated.
Thanks in advance.
Assuming your getdatafromtable function is properly made to return the array
var data_array = getdatafromtable(autocompleteData);
and in your getdatafromtable function you should have a return statement returning an array
Also dont name your variable the same as an already existing function. autocompleteData in this case is both a local variable and a function name.
Edit:
$("#" + autocomplete_name).on("listviewbeforefilter", function (e, data) {
var autocompleteData = new Array();
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
getdatafromtable(autocompleteData, $ul, $input, value, html);
});
function after_data_retrieved(autocompleteData, $ul, $input, value, html) {
if (value && value.length > 1) {
$.mobile.loading('hide');
for (var j = 0; j < dataarray.length; j++) {
html += "<li id='" + dataarray[j].id + "'>" + dataarray[j].user_name + "</li>";
}
$ul.html(html);
$ul.listview("refresh");
$ul.trigger("updatelayout");
$.mobile.activePage.find('input[placeholder="Find a name..."]').attr('id', 'autocomplete');
}
$("ul>li").click(function () {
var textval = $(this).text();
var id = $(this).attr('id');
$('#autocomplete').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
storeselectedid(id, autocompleteData);
});
}
function getdatafromtable(autocompleteData, $ul, $input, value, html) {
db.transaction(function (tx) {
$.mobile.loading('show');
var selectQuery = 'select first_name||" "||last_name user_name,user_id from users where first_name like "%' + value + '%" or last_name like "%' + value + '%" limit 10';
var selectQuery1 = 'select account_name user_name,account_id from crm_account where account_name like "%' + value + '%" limit 10';
tx.executeSql(selectQuery, [], function (tx, results) {
var dataset = results.rows;
if (dataset.length > 0) {
for (var i = 0; i < dataset.length; i++) {
var item = dataset.item(i);
var element = new Object();
element['id'] = autocomplete_name + "_" + i;
for (var j = 0; j < objdata.length; j++) {
element[objdata[j]] = item[objdata[j]];
}
autocompleteData[i] = element;
}
}
after_data_retrieved(autocompleteData, $ul, $input, value, html);
});
});
}