Pass parameter to another page to generate listview from Json - json

Hello I'm using this js to pass the url parameter and it's working just fine, but my problem is that when I define the path to the JSON file I don't want to use the id of the item...I want to use another Id. For example: I have the following item:
{"id":"1",
"name":"Winery",
"street":"Chile",
"number":"898",
"phone":"4204040",
"mail":"winery#hotmail.com",
"web":"www.winery.com",
"lat":"-32.891638",
"long":"-68.846522",
"id_localidad":"1",
"id_provincia":"1"}
I want to put id_localidad at the end of the path, to generate the listview depending on the city (id_localidad is the id of the city where the shop is), not the id of the item. And this is not working for me.
Thanks in advance!
JS FILE
$('#PuntosDeVenta').live('pageshow',function(event){
var id = getUrlVars()["id"];
$.getJSON('http://localhost/CavaOnline/json_PuntosDeVentas.php?id_localidad='+id, function(vinerias) {
//THIS IS NOT WORKING, IS THE SAME AS PUTTING id, not id_localidad
$.each(vinerias, function(index, vineria) {
$('#listviewVinerias').append( '<li><a href="FichaTecnicaVineria.php?id=' + vineria[id - 1].id + '" > ' +
'<img src="pics/' + vineria[id - 1].img_url1 + '"/>' +
'<h4>' + vineria[id - 1].name+'</h4>' +
'<p>' + vineria[id - 1].street+ ' ' + vineria[id - 1].number+ '</p>' +
'</a></li>');
$('#listviewVinerias').listview('refresh')
});
});
});
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Div where I load the List
<div data-role="content">
<ul id="listviewVinerias" data-role="listview"></ul>
</div>

So I'm assuming your vinerias is a variable containing a list of JSON objects, even though I don't know why you are calling [id-1] everywhere.
If so, you can use the .filter() function to filter out the elements that have an id_localidad equal to the one specified.
var filteredVinerias = vinerias.filter(function(index){
return this["id_localidad"] === "1" //The localidad you want
});

Related

d3 variable equals the string "function(d)", not the value the function returns

In some d3js code, I am using an anonymous function(d) to return the value of -importance from a JSON file. I use the returned value, stored in kwdAssbly object, to decide whether or not to render part of a diagram.
where I break on:
kwdAssbly.opt = (function(d){
return d["-importance"];
});
With a watch set on the object kwdAssbly, the debugger shows numerical values for kwdAssbly.width & kwdAssbly.height but shows kwdAssbly.opt = kwdAssbly.opt(d). I'm expecting a string value of either required or optional! If I put a watch on d in the function, it shows -importance:"optional", but this isn't assigned to my kwdAssbly.opt object attribute
Why is the function declaration being returned as the value?
Here's a code snippet of the context:
.attr("nullAttrib", function(d, i) { // calculate the text width and store it
var kwdAssbly = {}; //the keyword group's height and width object
kwdAssbly.width = this.getBoundingClientRect().width + padding;
kwdAssbly.height = this.getBoundingClientRect().height;
kwdAssbly.opt = (function(d){
return d["-importance"];
});
kwdProps[i] = kwdAssbly;
if (i>0){
kwdX += kwdProps[i-1].width;
if (kwdProps[i].opt == "optional"){
OptOffset = 40;
var Lsiding = kwdgrp.append(function(){return sidingL})
.attr("transform","translate(" + kwdX + ", " + (kwdProps[i].height*2/3 + line1y + OptOffset) + ")");
var Rsiding = kwdgrp.append(function(){return sidingR})
.attr("transform","translate(" + kwdX+50 + ", " + (kwdProps[i].height*2/3 + line1y + OptOffset) + ")");
}
else {
OptOffset = 0;
}
}
Working/correct answer by Altocumulus:
You won't need an anonymous function to get the string value.
Just use kwdAssbly.opt = d["-importance"];

How do I make a JSON object produce HTML on the page

Here is my JSON
var gal = [
{
"folder":"nu_images",
"pic":"gd_42.jpg",
"boxclass":"pirobox_gall",
"alt":"Rand Poster 1",
"title":"Rand Poster 1",
"thfolder":"th",
"thumbpic":"th_gd_42.jpg"
},
{
"folder":"nu_images",
"pic":"gd_13.jpg",
"boxclass":"pirobox_gall",
"alt":"Explosive Pixel Design",
"title":"Explosive Pixel Design",
"thfolder":"th",
"thumbpic":"th_gd_13.jpg"
}
];
and here is my for loop
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML = "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + ""
};
I am trying to make my JSON show all of the objects in HTML one after the other. I can get it to show the first one or whatever number I put into the array but I don't know how to make it generate a list of them.
Here is a link to my jsfiddle. Any help you can offer would be greatly appreciated.
http://jsfiddle.net/o7cuxyhb/10/
It's being generated here <p id="gallery"></p> just not correctly.
You're overwriting your html with every loop iteration:
document.getElementById("gallery").innerHTML = ...
^---
Perhaps you want something more like
document.getElementById("gallery").innerHTML += ...
^---
which will concatenation the original html contents with your new stuff.
And technically, you shouldn't be doing this in a loop. Changing .innerHTML like that causes the document to be reflowed/re-rendered each time you change .innerHTML, which gets very expensive when you do it in a loop. You should be building your html as a plain string, THEN adding it to the dom.
e.g.
var str = '';
foreach(...) {
str += 'new html here';
}
document.getElementById("gallery").innerHTML += str;
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML += "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + "" };
Add a += instead of an = after innerHTML
Try this:
function displayJson(jsonArray){
var container = document.getElementById("gallery");
for (var i=0; i<jsonArray.length; i++){
var newElement = document.createElement("a").innerHTML = jsonToHtml(jsonArray[i])
container.appendChild(newElement);
}
}
function jsonToHtml(jsonObj){
//Define your dom object here
var el = document.createElement("a").innerHTML = '' // you code here
...
return el;
}
displayJson(gal);

Displaying sql records in a listview

I have some code below:
transaction.executeSql('SELECT * FROM Table1 ORDER BY date DESC', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#records').append('<li>' + 'item1: ' + row['row1'] + '<br>' + 'item2: ' + row['row2'] + '<br>' + 'item3: ' + row['row3'] + '<br>' + 'item4: ' + row['row4'] + '</li>');
$( "#records" ).listview().listview("refresh");
}
}
},errorHandler);
},errorHandler,nullHandler);
As you can see, each time I input a record, all of this is displayed as a list item in a listview. But my problem is, the part where I have appended a href = "#". This is to make each list item linked, but I want a link to a different location depending on the record. Right now, each record would link to the same place.
Is there a way to put that href somewhere else so that it can depend on each list item?
the HTML where the list appears is below:
<div data-role = "content">
<ul id = "records"></ul>
</div>
Please let me know if the question isn't clear, I'll try and make it clearer. Thanks
i guess you can always change href, like that maybe
$("#records li a").each(function() {
var s = $(this).text();
if (s == "text1") {
$(this).attr("href","href1");
}
else if (s == "text2") {
$(this).attr("href","href2");
}
});
might be some syntax errors above, im not jquery expert, i wanted to show general idea

Update jqGrid table with the results of Fusion Tables query in a Google Maps v3 page

I am looking to understand how to update a jqGrid table from Fusion Tables (FT) -
at the moment I can search or scroll on a Google Map, send an event listener that compiles a FT query of the spatial bounds of the viewport/map, to get a new set of results.
I want to use the new FT query string (or could use the Google code to retrieve the data - query.send(getData);) to update the jqGrid table with the new values.
Before I started using jqGrid, I tried/suceeded with the Google Visualisation API, and some of that code is below. Could anyone suggest how to move from table.draw, to loading/reloading a jqGrid table? Thanks a lot in advance.
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', getSpatialQuery);
google.maps.event.addListener(map, 'dragend', getSpatialQuery);
getSpatialQuery();
}
function getSpatialQuery() {
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
var spatialQuery = "ST_INTERSECTS(latitude, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))";
changeDataTable(spatialQuery);
}
function changeDataTable(spatialQuery) {
var whereClause = "";
if(spatialQuery) {
whereClause = " WHERE " + spatialQuery;
}
var queryText = encodeURIComponent("SELECT 'latitude', 'longitude', 'name' FROM xxxxxxxx" + whereClause + " LIMIT 50");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
}
function getData(response) {
var table = new google.visualization.Table(document.getElementById('visualization'));
table.draw(response.getDataTable(), {showRowNumber: true});
}
Oh, and I used Oleg's code jqGrid returns blank cells as a basis for just seeing if I could get a simple multi-select table to pull data from my FT - that worked fine with the simple mod of
url: 'http://www.google.com/fusiontables/api/query?sql=' +
In case this helps someone, I've taken some of the code I came up with and pasted it below:
// You can get the map bounds via then pass it via a function (below is hacked from several functions
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
var whereClause = "ST_INTERSECTS(latitude, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))";
//construct the URL to get the JSON
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; //
var queryOrderBy = ' ORDER BY \'name\' ASC';
var queryMain = "SELECT * FROM " + tableid + whereClause + queryOrderBy + " LIMIT 100";
var queryurl = encodeURI(queryUrlHead + queryMain + queryUrlTail);
//use the constructed URL to update the jqGrid table - this is the part that I didn't know in my above question
$("#gridTable").setGridParam({url:queryurl});
$("#gridTable").jqGrid('setGridParam',{datatype:'jsonp'}).trigger('reloadGrid');

DataTables Combo box width

I'm applying DataTables
to utilize filtering, sorting and pagination on my HTML table. I'm using the following code to apply these attributes to the table:
$(document).ready(function() {
<!-- Sorting and pagination -->
var oTable = $('#mainTable').dataTable( {
"sPaginationType": "full_numbers",
"bJQueryUI": true
});
<!-- Filtering -->
$("thead td").each( function ( i ) {
<!-- Create and populate combo boxes -->
this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
<!-- Filter data when selection changes -->
$('select', this).change( function () {
oTable.fnFilter( $(this).val(), i );
});
});
});
On the function call:
fnCreateSelect( oTable.fnGetColumnData(i));
..the combo boxes are filled with the data from the table. However, the boxes are automatically sized to contain the full length of the values (some of which span many lines) and so the columns are sized too big and run way off the page. I've determined it's not a CSS issue, so what I need is a way to make the combo boxes use multiple lines per entry, or only show a portion of the value so that I can fit all these columns on one page.
Thanks in advance!
Answer for anyone following this:
I changed the code in fnCreateSelect (where the combo boxes are built) to limit how much text is stored per value in the combo boxes as such:
function fnCreateSelect(aData) {
var r = '<select><option value=""></option>', i, iLen = aData.length;
for (i = 0; i < iLen; i++) {
// If string is a URL, handle it accordingly
if (aData[i].indexOf("href") != -1) {
var url = aData[i].substring(aData[i].indexOf('http'), aData[i].indexOf('">'));
r += '<option title="' + url + '" value="' + url + '">' + url.substring(0, 25);
if (url.length > 25)
r += '...';
}
else {
r += '<option title="' + aData[i] + '" value="' + aData[i] + '">' + aData[i].substring(0, 40)
if (aData[i].length > 40)
r += '...';
}
r += '</option>';
}
return r + '</select>';
}