I working with odoo12ce and have some problems writting a new widget
My new widget shows some data and after 3 second it should disappear
start: function () {
var texto = ""
texto += "<ul>"
this.valor.forEach(element => {
texto += "<li>" + element.cant + ' ' + element.type + "</li>"
});
texto += "</ul>"
this.$el.append(texto);
setTimeout( function(){
this.$el.empty();
}, 3000);
},
And I got the error: Cannot read property 'empty' of undefined
Outside the function the object works fine but inside it is not recognised. What could I do to solve it??
Thanks in advance
you just need to add this to context of the setTimeout. so your code would be something like the following:
start: function () {
var self = this;
var texto = ""
texto += "<ul>"
this.valor.forEach(element => {
texto += "<li>" + element.cant + ' ' + element.type + "</li>"
});
texto += "</ul>"
this.$el.append(texto);
setTimeout( function(){
self.$el.empty();
}, 3000);
},
don't hesitate to let us know if it is working or not.
Related
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?
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);
});
}
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/> (μg/L)</th>',
'<th>Recreational Water Quality Objective <br/> (20 μg/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!
In the following lines of code, I try to add a function inside html tag in javascript:
nuevo = "<p class='item'>" + res.tarea + "<button onclick = '" + return EliminarTareas(database) + (" + res.tarea +");'>" + "Eliminar" + "</button></p>";
$('#listatareas').append(nuevo);
function EliminarTareas(id, base) {
base.transaction(function(tx) {
tx.executeSql("DELETE tarea FROM Tareas WHERE tarea=?", [id], function () {
});
});
}
The main problem is this part +return EliminarTareas(" + database + ", " + res.tarea +");'>". It discards the second parameter since you closed the paranthesis ), and it also has quote problems.
It should be like this +" return EliminarTareas(" + database + ", " + res.tarea + ");'>"
However, I believe addressing this task with .data would be effective, and it may provide a better structure. Below is my version with some codes from yours (DEMO: https://jsfiddle.net/9q4hLs3a/):
var nuevo = $("<p class='item'><button data-var1='" + database + "' data-var2='" + res.tarea + "'>Eliminar</button></p>");
$('#listatareas').append(nuevo);
$(document).ready(function(){
$(document).on('click', '#listatareas button', function(){
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
EliminarTareas(var1 , var2 )
});
function EliminarTareas(id, base){
base.transaction(function(tx){
tx.executeSql("DELETE tarea FROM Tareas WHERE tarea=?", [id], function (){
});
}
I think this is what you wanted
"<p class='item'>"+ res.tarea +"<button onclick = 'EliminarTareas("+database+","+res.tarea +")'>Eliminar</button></p>";
My end goal is to have a home page that pulls RSS feeds and displays them on my home page for my personal website. This is all done from the client side and I'm not looking to build a server site script to do this (I will though only if no other way is possible).
Below is the page load code. (I don't think this is a problem area but it nice to see the starting point)
$(document).ready(function () { // Here
loadpageF(); //<- problems is in this function
GetBackGround(document.body); //this just messes with the css of the site
});
function loadpageF() {
addTableFeed("http://www.npr.org/rss/rss.php?id=1001");
addTableFeed("http://news.yahoo.com/rss/odd");
addTableFeed("http://www.nfl.com/rss/rsslanding?searchString=team&abbr=DAL");
addTableFeed("http://www.npr.org/rss/rss.php?id=1007");
$(".MainArea").css("width",$("iframe").length * (270));
}
//This function sets up where the RSS data will be place after formatting
function addTableFeed(feedlink) {
var numOfCell = maintb.getElementsByTagName("iframe").length;
maintb.innerHTML += "<iframe id='f" + numOfCell + "' class='iframeFeed'></iframe>";
getRSSFeed(feedlink, "f" + numOfCell);
}
This code basically calls a function for each rss to add and iframe and the passes the iframe id and the URL to another function (shown below and I am 99% sure is the problem) which getting the data.
function getRSSFeed(feedlink, iframeid) {
/*var xmlhttp; old way I did it below realizing it did not work in firefox
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var hold = xmlhttp.responseText
loadData(hold, iframeid);
}
}
xmlhttp.open("get", feedlink, false);
xmlhttp.send();*/ //end of the old way
//new way to try to use JSON of course failing at my in goal
$.ajax({
type: "GET",
url: feedlink,
async: true,
dataType: "text",
success: function(data){
loadData(data, iframeid);
},
error: function(data, statusCode) {
alert("ERROR: "+data.error)
}
});}
The function loadData works fine when called, however it is not called for the Yahoo.com and NFL.com feed. Instead I get an alert as shown below.
//Note I has to transcribe from dialog box there may be errors
ERROR: function () {
if( list ) {
// First, we save the current length
var start = list length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
¡f( jQuery.isFunction( arg ) && (!options unique || self.has( arg)
list .push( arg);
else if( arg && arg.length ) {
// Inspect recursively
add( arg);
}
});
})( arguments);
//Do we need to add the callbacks to the
// current firing batch?
if (firing ) (
firingLength = list length;
//wiIh memory, if we’re not firing then
// we should call right away
J else if ( memory ) (
firingstart = start;
fire( memory);
Just in case it is needed, below is the load data code.
function loadData(xml, ifid) {
var htmlStr;
var artCount = 0;
var $xml = $($.parseXML(xml));
$("#" + ifid)[0].contentDocument.open();
$("#" + ifid)[0].contentDocument.close();
$("#" + ifid)[0].contentDocument.write("<head><link rel='Stylesheet' type='text/css' href='" + document.getElementById("StyleSheet").href + "' /></head>");
//RSS 2.0 handler
$xml.find("channel item").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("description").text();
var link = $article.find("link").text();
var pubDate = $article.find("pubDate").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" +artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//Atom 1.0 handler
$xml.find("feed entry").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("summary").text();
var link = $article.find("link").attr("href");
var pubDate = $article.find("published").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" + artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//$("#" + ifid).contents().find(".ArticalBody").hide();
}
Please forgive me for any typos or spelling errors. I can also post the whole web page if needed.