Clear previous results from query - javascript

Through the attached code I do a search on youtube based on the username and the results are shown. If I search twice, the results add up. I would like previous results to be deleted. I try with htmlString = card; but it show only one result.Thanks to everyone who wants to help me solve this problem.
var musicCards = [];
jQuery(document).ready(function() {
jQuery("#searchButton").on("click", function() {
var query = jQuery("#queryInput").val();
if (query != "") {
loadYoutubeService(query);
console.log(query + "");
}
});
});
function loadYoutubeService(query) {
gapi.client.load('youtube', 'v3', function() {
gapi.client.setApiKey('ADADADADADA');
search(query);
});
}
function search(query) {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: query,
type: 'channel',
maxResults: 15
});
request.execute(function(response) {
jQuery.each(response.items, function(i, item) {
if (!item['']) {
var musicCard = {};
musicCard._id = item['snippet']['customUrl'];
musicCard.title = item['snippet']['title'];
musicCard.linkprofilo = item['snippet']['channelId'];
musicCard.url = "https://www.youtube.com/channel/";
musicCard.description = item['snippet']['description'];
musicCard.immagine = item['snippet']['thumbnails']['high']['url'];
musicCards.push(musicCard);
}
});
renderView();
});
}
function renderView() {
var htmlString = "";
musicCards.forEach(function(musicCard, i) {
var card = createCard(musicCard._id, musicCard.title, musicCard.description, musicCard.url,musicCard.immagine, musicCard.linkprofilo);
htmlString += card;
});
jQuery('#youtube-utente').html(htmlString);
}
function createCard(_id, title, description, url, immagine, linkprofilo) {
var card =
'<div class="card">' +
'<div class="info">' +
'<img src="' + immagine + '" alt="' + description + '">' +
'</div>' +
'<div class="content">Clicca per selezionare:' +
'<h3>' + title + '</h3>' +
'<a class="seleziona" href="' + url +linkprofilo+'">'+ url +linkprofilo+'</a>' +
'<p>' + description + '</p>' +
'</div>' +
'</div>';
return card;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

Solved using :
request.execute(function(response) {
musicCards.length = 0; // clear array

Related

Want to use YDN-db database instead of Ajax with Select2

I want to use YDN-db with select2, i tried few options but unable to sort.
So i want to use executeSql command as below
APP.db.executeSql("SELECT * FROM products WHERE name like '%test%'").then(function(results) {
//something
}
so i tried following in last (i already used other tweaks of it aswell)
$('#add_product_id').select2({
data:function (params) {
console.log(params);
APP.db.executeSql("SELECT * FROM products WHERE name = '"+params+"'").then(function(resultRows) {
if(resultRows.length > 0) {
$.each( resultRows, function( i, productRow ) {
console.log(productRow);
var title ='<span class="result-title">' + productRow.name + '</span>';
var price = '<span class="result-price">' + productRow.price + '</span>'
;
var sku = '<span class="result-sku">' + pos_i18n[60] + ' ' + productRow.sku + '</span>';
var stock = '<span class="result-stock">' + pos_i18n[61] + ' ' + productRow.stock_quantity + '</span>';
var firstRow = '<div class="result-row first">' + title + price + '</div>';
var secondRow = '<div class="result-row second">' + sku + stock + '</div>';
});
}
});
},
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 3,
cache: true,
multiple: true,
}).change(function () {
var val = $(this).select2('data');
$(this).html('');
if (!empty(val)) {
val = is_array(val) ? val[0] : val;
}
});
YDN query executed by requested parameter not coming log which user actually types on search2 field,
console.log(params);
Please can any one guide me how can i use YDN-db instead of Ajax with Select2?

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.

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!

How do I hyperlink JSON API return values with variable URL addresses?

I have an HTML/CSS search bar where people can type a keyword and, on click, my Open States JSON API code returns New Jersey state bills that match that keyword.
Search Bar Screenshot
Screenshot of a Result
I want the bill titles that are returned to be hyperlinked to their page on the New Jersey state legislature site, but I can only find instructions for how to hyperlink a return with a static site.
Here is my JavaScript code so far (with API key removed):
e.preventDefault();
// console.log($("#billID").val());
var billSearchValue = $("#billID").val();
if(billSearchValue=='')
{
alert("Enter Desired Query Parameters");
} else{
// console.log(billSearchValue);
}
var searchQuery = "&q=" + billSearchValue;
var baseUrl = "http://openstates.org/api/v1/bills/?state=nj";
var apiKey = "";
var apiKeyParam = "&apikey=";
var apiKeyParams = apiKeyParam + apiKey;
var urlJSON = baseUrl + searchQuery + apiKeyParam + apiKey;
// console.log(urlJSON);
$.getJSON(urlJSON, function (data) {
var billsVar = [];
$.each(data, function(key, val) {
billsVar.push(val);
});
for (var i = 0; i < billsVar.length; i++) {
var billList = "<li>Bill <ul class=\"ul-sub\">"
var billTitle = "<li><strong>Bill Title</strong>: " + billsVar[i]['title'] + "</li>";
var billCreatedAt = "<li><strong>Bill Created</strong>: " + billsVar[i]['created_at'] + "</li>";
var billUpdatedAt = "<li><strong>Bill Updated</strong>: " + billsVar[i]['updated_at'] + "</li>";
var billID = "<li><strong>ID</strong>: " + billsVar[i]['id'] + "</li>";
var billChamber = "<li><strong>Bill Chamber</strong>: " + billsVar[i]['chamber'] + "</li>";
var billState = "<li><strong>Bill State (Probably Don't Want/Need This)</strong>: " + billsVar[i]['state'] + "</li>";
var billSession = "<li><strong>Bill Session</strong>: " + billsVar[i]['session'] + "</li>";
var billType = "<li><strong>Bill Type</strong>: " + billsVar[i]['type'] + "</li>";
var billSubjects = "<li><strong>Subjects</strong>: " + billsVar[i]['subjects'] + "</li>";
var billBillID = "<li><strong>Bill ID</strong>: " + billsVar[i]['bill_id'] + "</li>";
var billOutput = billList + billTitle + billCreatedAt + billUpdatedAt + billID + billChamber + billState + billSession + billType + billSubjects + billBillID + "</ul></li>";
$("#jsonlist").append(billOutput);
}
});
})
});
After a bit of research I see that a bill hyperlink is like this:
http://openstates.org/nj/bills/{Bill Session}/{Bill ID}/
I can't test my code because I have no API key, but the solution could be something like:
var billTitle = '<li><strong>Bill Title</strong>: '
+ '<a href="http://openstates.org/nj/bills/' +
billsVar[i]['session'] + '/' + billsVar[i]['bill_id'].split(' ').join('') + '/">'
+ billsVar[i]['title'] + '</a></li>';

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories