ajax callback to insert image if exists - javascript

I've been following this answer in an attempt to write good asynchronous js - but I can't quite figure out what's going wrong for me.
I'm using autocomplete to request a specific set of files from the server, but for some datasets these files may not exist (i.e, there may be one, or up to four files). If they do exist, I want to append .html to include them.
The images don't load unless I add
async: false
to the .ajax call, which makes the callback redundant.
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
$.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
})(i);
}
Then image_html contains html for only those images that exist.
$('#outputcontent').html(outer_html + image_html + outer_html_end);
Can anyone explain to my misunderstanding here please? Why isn't image_html being populated?
EDIT: 'full' code below. I use jquery autocomplete to pull from the stellar_comp array, then for those with properties that exist (some are blank), html is generated. Within that is the ajax call.
$(function () {
var stellar_comp = [
{
value:'X0005-28',
data: {
set0: {
aperture:'X2105-28',
secat:'X025-18',
set:'1',
run:'r06',
continuumFilter:'J',
narrowBandFilter:'638/28',
numberOfSources:'1',
priorityCode:'1'
etc... etc ...
},
},
];
$('#autocomplete').autocomplete({
lookup: stellar_comp,
onSelect: function (suggestion) {
var path_Value = 'data/' + suggestion.value + '/';
var outer_html = '<h1>' + suggestion.value + ' </h1> <div class="container">';
var outer_html_end = '</div>';
for (var category in suggestion.data) {
if (suggestion.data.hasOwnProperty(category)) {
if (suggestion.data[category].aperture) {
summary_table_contents = '<tr> <td>' + suggestion.data[category].set + '</td> <td>' + suggestion.data[category].run + '</td> <td>' + suggestion.data[category].continuumFilter + '</td> <td>' + suggestion.data[category].narrowBandFilter + '</td> <td>' + suggestion.data[category].numberOfSources + '</td> <td>' + suggestion.data[category].priorityCode + '</td></tr> ';
summary_table += summary_table_contents;
var aperturePlot = suggestion.data[category].aperture + '_' + suggestion.data[category].run;
var seCATPlot = suggestion.data[category].secat + '_Rsub_ss_' + suggestion.data[category].run;
var aperture_match = suggestion.data[category].aperture_match;
cog = path_Plots + aperturePlot + '_cog';
sbprof = path_Plots + aperturePlot + '_sbprof';
thumb_cog = '';
thumb_cog_temp = '';
thumb_sb = '';
temp='';
for (var i = 1; i < 5; i++) {
(function (counter) {
function some_function(callback) {
$.ajax({
type: "GET",
url: cog + counter + "_1.jpg",
async: false,
success: function (result) {
callback(counter);
}
});
}
some_function(function (num) {
var thumb_cog_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + cog + num + '_1.jpg"> <img class="img-thumbnail" src="' + cog + num + '_4.jpg" /></a> <div class="caption"><h5>' + suggestion.value + ':S' + num + '</h5></div></div>';
var thumb_sb_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + sbprof + num + '_1.jpg"><img class="img-thumbnail" src="' + sbprof + num + '_4.jpg" /></a><div class="caption"><h5>' + suggestion.value + ':S' + num + ' </h5></div></div>';
console.log(num, counter);
thumb_cog += thumb_cog_temp;
thumb_sb += thumb_sb_temp;
});
})(i);
}
cog_sbprofile_row='<div class="row"><h3>C o G</h3> ' + thumb_cog + '</div><div class="row"><h3>Profiles</h3> ' + thumb_sb + '</div>';
console.log(cog_sbprofile_row);
body_html += aperture_row;
body_html += seCAT_row;
body_html += aperture_match_row;
body_html += pixel_map_row;
body_html += skyprofile_row;
body_html += cog_sbprofile_row;
body_html += '<hr>';
};
};
};
top_html += summary_table + '</tbody> </table> </div></div> <hr>';
$('#outputcontent').html(outer_html + hipass_container + top_html + body_html + outer_html_end);
}
});
});

The current problem is due to using the resulting HTML string, before it has been created via multiple asynchronous calls. You need to either defer that operation until all loads are completed, or change the situation so it is not dependent on final completion (progressive loading looks busier anyway).
Personally I would simply insert placeholders for the images as you loop and insert each as they load. This way the order is retained. You can even do effects (fade etc) on each as they load:
var wrapper = "";
for (var i = 1; i < 5; i++) {
// Make a placeholder element for each image we expect
wrapper += '<div class="thumbnail" id="thumb_' + i + '">'
(function (num) {
// call the function
$.ajax({
type: "GET",
url: num + "_1.jpg",
success: function (result) {
var image_temp = '<img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num;
// Insert new image into unique element and fade it in
$('#thumb_'+num).append(image_temp).fadeIn();
}
});
})(i);
}
// Append all placeholders immediately - these will be appended to as each image is loaded
$('#outputcontent').html(outer_html + wrappers + outer_html_end);
Update:
As Alnitak points out, the whole exercise is a little pointless as you are ignoring the result returned from the Ajax call anyway, so you might as well drop the Ajax call (which adds no value) and simply build the image elements on the fly server-side :)

You have to do the appending after all ajax requests finish their jobs. First define this:
var after = function(reqs) {
var d = $.Deferred(),
cnt = reqs.length;
if (!cnt) {
d.resolve();
}
var limit = cnt; // separate var just in case reqs are synchronous
// so it won't mess up the loop
for (var i = 0; i < limit; i++) {
reqs[i].always(function() {
cnt--;
if (!cnt) {
d.resolve();
}
});
}
return d.promise();
};
You can use $.when instead of this but if one of the requests results in 404 it won't wait for others. Now:
var image_html = "",
requests = [];
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
return $.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
var req = ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
requests.push(req); // push the request to the array
})(i);
}
after(requests).done(function() {
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});
Note that I've added return $.ajax(...).
BTW: what's the point of defining ajaxTest function? Just put everything in an anonymous callback.
Read more about deferred objects and promises here:
http://api.jquery.com/category/deferred-object/
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
or just google it.
EDIT: if the order is important then you just have to tweak the callback function a bit:
var image_html = []; // array instead of string
// some code...
var req = ajaxTest(function (num) {
// ...
image_html[counter] = image_temp;
});
// some code...
after(requests).done(function() {
image_html = image_html.join("");
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});

Related

Is it possible to add a load more button that iterates through a for loop?

Im using an api to get and display food recipes for a project.
function getrecipe(q) {
$.ajax({
url: "https://api.spoonacular.com/recipes/search?apiKey=a568c4a88785422fbf4cf46b976c40e8&number=20&query=" + q,
success: function (res) {
for (var i = 0; i < 4; i++) {
document.getElementById("output").innerHTML += "<div class='pure-u-1 pure-u-md-1-3'><h1>" + res.results[i].title.substr(0,24) + "</h1><br><a href='" + res.results[i].sourceUrl + "'><img class='pure-img' src='" + res.baseUri + res.results[i].image + "' width='400' /></a><br>Ready in " + res.results[i].readyInMinutes + " minutes<br></div>"
console.log(q);
}
}
});
}
The html is
<input id="search-recipes" placeholder="Ingredient"><button class="pure-button" onclick="getrecipe(document.getElementById('search-recipes').value)">Search</button>
<div id="output"></div>
The "number=20" in the url is how many recipes I'm getting back from the API. The for loop is displaying 4 results on my html page. How can I add a load more button that would iterate through and display the next 4 results?
It would be easy if you save the result in a global variable and then create a function to loop through it to display the result.
function getrecipe(q) {
$.ajax({
url: "https://api.spoonacular.com/recipes/search?apiKey=a568c4a88785422fbf4cf46b976c40e8&number=20&query=" + q,
success: function (res) {
return res;
}
});
}
var resArray = getrecipe(q);
var x = 0;
var y = 4;
loadMore(); //this will run the function once
function loadMore(){
for(var i=x ; i< y; i++){
document.getElementById("output").innerHTML += "<div class='pure-u-1 pure-u-md-1-3'><h1>" + resArray.results[i].title.substr(0,24) + "</h1><br><a href='" + resArray.results[i].sourceUrl + "'><img class='pure-img' src='" + resArray.baseUri + resArray.results[i].image + "' width='400' /></a><br>Ready in " + resArray.results[i].readyInMinutes + " minutes<br></div>"
}
x = y;
y = y+4;
}
HTML file
<input id="search-recipes" placeholder="Ingredient"><button class="pure-button" onclick="getrecipe(document.getElementById('search-recipes').value)">Search</button>
<div id="output"></div>
<button onClick="loadMore()">Loard More></button>

Callback function not defined even though it has been defined right before calling in javascript

I am using for loop get all the data place in a div. I have following code in javascript so far:
<script type="text/javascript">
function callback(){
$.getScript("/frontend/vendor/jquery/jquery.min.js", function() {
$('input').on('change', function(){
var qty = $(this).attr('id');
var price = $('#'+qty+'_price').attr('value');
var subtotal = qty * price;
$('#'+qty+'_total').html('€ '+subtotal);
})
});
}
function checkout(callback){
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++){
var eventId = unique[n];
$.ajax({
"url":"/get_my_product/"+ eventId,
"type":"GET",
"dataType":"json",
"contentType":"application/json",
success:function(response){
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>"+party+"</a></h5></td><td class='product-col'><h5 class='product-title'><a>"+response.date+"</a></h5></td><td value='"+response.price+"' id='"+n+"_price'>€ "+response.price+"</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='"+n+"' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='"+n+"_total'>€ "+response.price+"</td></tr>";
$('#data').append(html);
}
})
}
callback && callback();
}
checkout();
</script>
When I am trying to call the function after the loop completion it does not work. What is wrong here?
Change
function checkout(callback){
to
function checkout() {
I think the argument callback to the function checkout "shadows" the previously defined callback function. Then, when you call the function checkout you are passing nothing to the function, and callback will be undefined.
Or, in the last line, pass the function as an argument:
checkout(callback);
Makes no sense to add another version of jQuery to add events. You are not passing the callback to the method so it is always going to be undefined. And you are not waiting for the Ajax calls to complete before calling the callback.
// No reason for loading the JQuery version here
function addMyEvents() {
$('input').on('change', function() {
var qty = $(this).attr('id');
var price = $('#' + qty + '_price').attr('value');
var subtotal = qty * price;
$('#' + qty + '_total').html('€ ' + subtotal);
})
}
function checkout(callback) {
// hold the ajax calls
const myAjaxCalls = []
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++) {
var eventId = unique[n];
// push the ajax calls to an array
myAjaxCalls.push($.ajax({
"url": "/get_my_product/" + eventId,
"type": "GET",
"dataType": "json",
"contentType": "application/json",
success: function(response) {
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>€ " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>€ " + response.price + "</td></tr>";
$('#data').append(html);
}
}))
}
// if we have a callback
if (callback) {
// wait for all the ajax calls to be done
$.when.apply($, myAjaxCalls).done(callback)
}
}
// pass the function to the method.
checkout(addMyEvents);
Now the best part is you do not even need to worry about the callback to bind events. You can just use event delegation and it would work. This way whenever an input is added to the page, it will be picked up.
$(document).on('change', 'input', function() {
var qty = $(this).attr('id');
var price = $('#' + qty + '_price').attr('value');
var subtotal = qty * price;
$('#' + qty + '_total').html('€ ' + subtotal);
})
function checkout() {
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++) {
var eventId = unique[n];
$.ajax({
"url": "/get_my_product/" + eventId,
"type": "GET",
"dataType": "json",
"contentType": "application/json",
success: function(response) {
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>€ " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>€ " + response.price + "</td></tr>";
$('#data').append(html);
}
})
}
}
checkout();

I have javascript code to view a news from RSS as a vertical list. I need help to move the list of topics as horizontal one by one, in one line

I have javascript code to view a news from RSS as a vertical list.
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
I need help to move the list of topics as horizontal one by one, in one line. by used javascript code. this code display just 5 topics, which I need it, but I have problem to how can I movement it as horizontal.

How to return a variable from a callback after building variable with .getjson and .each

The Problem
I'm trying to figure out how to return HTML that I've built from a JSON file with jQuery.
I seem to have gotten returnLocations() to wait until getLocations() is finished so that the variable locationsBody is finalized with information gathered from my .each loop. The trouble (I think) is my not being able to return that variable to output it to my HTML page.
The Question
How can I return the variable locationsBody?
Note
(there may be errors in the below code as I trimmed it down as best I could but I think it should illustrate the problem with or without them)
The jQuery
the global variables
var locationsFull = 'un d fined';
var locationsOpener = '' +
'<div class="locations-header">places youve been</div>' +
'<div class="locations-container">' +
'<div class="locations-nav left">left</div>' +
'<div class="locations-nav right">right</div>'
;
var locationsBody = '<div class="locations-inner">'; // opening of container
var locationsCloser = '</div>'; // closing of container
the function
function locationsFunction() {
function getLocations() {
var wait = $.Deferred();
var area = 'Area1';
var counter = 1;
$.getJSON("locations.json", function(data) {
$(data.places).each(function() {
var location = this.location;
var image = this.image;
if (this.area === 'Area1') {
if (counter == 2) {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div></div>'
;
counter = 0; // added closing of container, reset to 0
} else {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div>'
;
counter = counter + 1;
}
}
})
wait.resolve();
})
return wait;
}
function returnLocations() {
locationsFull = locationsOpener + locationsBody + locationsCloser; // works, proven in alert and console.log
//alert(locationsFull); // works
console.log(locationsFull); // works
//return locationsFull; // doesnt work
//return 'anything'; // doesnt work
}
getLocations().then(returnLocations);
}
the call
$(function() {
$('.locations-body').html(locationsFunction());
})
The JSON File
{"places":[
{
"area": "Area1",
"location": "Downtown",
"image": "downtown.jpg"
},
{
"area": "Area1",
"location": "Uptown",
"image": "uptown.jpg"
}
]}
The HTML
<div class="locations-body"></div>
Further Note: Questions similar to this have been asked dozens of times on stackoverflow alone and those questions and answers have hundreds of thousands of reads. I have read through all of the top ones and more over the last 2 days. My problem is my inability to thoroughly understand the answers and apply them to my exact situation as seems to be the problem of the dozens (hundreds/thousands?) of people asking these questions and the hundreds of thousands (millions?) of people that have been searching for solutions to asynchronous problems.
You could just call .html() inside the returnLocations() function if that's viable.
the function
function returnLocations() {
locationsFull = locationsOpener + locationsBody + locationsCloser;
$('.locations-body').html(locationsFull);
}
the call
$(function() {
locationsFunction();
}
Otherwise you'll need to look into callbacks, read this, if you need to do it this way I can update my answer with an example later on.
Have you tried
return wait.promise();
instead of returning the Deferred?
Then calling like this:
var deferredChain = $.Deferred();
deferredChain.then(getLocations).then(returnLocations);
deferredChain.resolve();
I discovered today that simply putting a .done at the end of $.getJSON seems to work just the same and is much easier than using $.Deferred and the associated lines of code to make it work.
function locationsFunction() {
var area = 'Area1';
var counter = 1;
$.getJSON("locations.json", function(data) {
$(data.places).each(function() {
var location = this.location;
var image = this.image;
if (this.area === 'Area1') {
if (counter == 2) {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div></div>'
;
counter = 0; // added closing of container, reset to 0
} else {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div>'
;
counter = counter + 1;
}
}
})
}).done(function() {
locationsFull = locationsOpener + locationsBody + locationsCloser;
$('.locations-body').html(locationsFull);
});
}

No response from 2nd ajax request

I am getting no response from a 2nd ajax request. I am trying to display an google information window on google map that contains only a single tab when a certain criteria is matched otherwise I want to display two tabs. I thought I could easily implement this with another marker function with tailored behaviour, but I receive no response. Any help on this is always appreciated. Thanks in advance.
// click event handler
google.maps.event.addListener(marker, 'click', function () {
var ecoli_array = [];
var marker = this;
var str = "";
var beach_status; // beach_status flag
// load gif before ajax request completes
infoWindow.setContent('<img src="img/loading.gif" alt="loading data"/>');
infoWindow.open(map, marker);
// override beach data when a beach is closed
beach_status = this.getBeachStatus();
beach_status = beach_status.toLowerCase();
if (beach_status === 'closed') {
str = [
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>' + this.status_description + '</p>'
].join('');
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
} else {
// chained ajax invocations
if ( this.displayOnlyAlgaeResults === false ) {
// Standard Use case
$.when(this.getEcoliData(), this.getAlgaeData()).done(function (data1, data2) {
str += marker.getHeader() + marker.afterGetEcoliData(data1[0].rows);
str += marker.afterGetAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
}else{
// Algae Only Use Case
var d = this.getOnlyAlgaeData();
console.log(d);
$.when( this.getOnlyAlgaeData() ).done(function ( rsp ) {
//console.log(rsp);
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
//str += marker.afterGetOnlyAlgaeData(data2[0].rows);
infoWindow.setContent(str);
infoWindow.open(map, marker); // changed this to marker to resolve issue
// render tabs UI
$(".tabs").tabs({ selected: 0 });
}); // end when call
} // end inner if else
} // end outer if else
}); // End click event handler
getOnlyAlgaeData: function () { // begin getAlgaeData
var obj;
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=xxxxx&callback=?';
var whereClause = " WHERE 'Beach_ID' = " + this.beach_id;
var query = "SELECT * FROM xxxx "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
// ecoli request
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}, // end getAlgaeData method
// added afterGetOnlyAlgaeData
afterGetOnlyAlgaeData: function (data) {
var algae_rows_str = "";
algae_rows = data;
var algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<table id="algae_table " class="data">',
'<tr>',
'<th>Sample Date</th>',
'<th class="centerText">Blue Green Algae Cells <br/>(cells/ mL) </th>',
'<th>Recreational Water Quality Objective <br/>(100,000 cells/mL)</th>',
'<th class="centerText">Algal Toxin Microcystin <br/> (&#956g/L)</th>',
'<th>Recreational Water Quality Objective <br/> (20 &#956g/L)</th>', // &mu instead of u
'</tr>'
].join('');
//console.log(algae_rows);
if (typeof algae_rows === 'undefined') {
algae_rows_str = [
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>This season, no algal blooms have been reported at this beach.</p>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
} else {
for (var i = 0; i < algae_rows.length; i++) {
//console.log(rows[i]);
//algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td></tr>';
algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td class="centerText">' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + checkBlueGreenAlgaeCellsForAdvisory(algae_rows[i][6]) + '</td><td class="centerText">' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + checkAlgaeToxinForAdvisory(algae_rows[i][4]) + '</td></tr>';
}
algae_rows_str += '</table>'
algae_rows_str += '</div></div></div>';
//return algae_rows_str;
} //end if
return algae_rows_str;
}, // end afterGetOnlyAlgaeData
}); // ====================end marker
I essentially copied two identical functions that work, gave them a slightly different name and customized each function to display 1 tab instead of two, but I get no response.
Thoughts?
thanks for the help, it ended up being something simple.
I was incorrectly referencing the response. Ie. I change the following line:
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp[0].rows );
to
str += marker.getAlgaeHeader() + marker.afterGetOnlyAlgaeData( rsp.rows );
Geez!

Categories