Function within function in JavaScript - Need to understand this code: - javascript

I have below code within a function called render. How do I call the str variable value outside render function?
Also, please can you explain below code? I'm fairly new to js and head is hurting looking at the function calls having functions as a parameter.
My understanding is that app.getList is an object which takes function as a parameter? but it is not returning anything. Sorry, I'm lost here.
app.getList("FieldList", function(reply){
var str = "";
$.each(reply.qFieldList.qItems, function(index, value) {
str += value.qName + ' ';
});
console.log(str);
});
Full Code:
define(["jquery",
//mashup and extension interface
"qlik",
//add stylesheet
"text!./css/mystyle.css",
"client.utils/state",
"client.utils/routing"
],
function($, qlik, cssContent, clientState, clientRedirect) {
/*-----------------------------------------------------------------*/
// function redirect (sheetId){
// clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state])
// }
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
var render = function($elem, layout) {
var html = '',
app = qlik.currApp();
//get list of tab objects and insert into div
app.getAppObjectList('sheet', function(arrayitem) {
//for each sheet in the app, create a list item
$.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) {
//include the sheet id as the list item id to be used as a reference for active sheet
html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + ');
//wrap anchor tag to be used by bootstrap styling
html += '<a>';
//give the link the same name as the sheet
html += myvalue.qData.title;
html += '</a>';
html += '</li>';
});
html += '</ul></div>';
html += "<button id='myButton'> Click Me!! </button>";
console.log(arrayitem.qAppObjectList);
console.log(html);
//insert html into the extension object
return $elem.html(html);
});
/* Test Code Start from here */
app.getList("FieldList", function(reply) {
var str = "";
$.each(reply.qFieldList.qItems, function(key, value) {
str += value.qName + ' ';
});
console.log(str);
});
};
/*-----------------------------------------------------------------*/
return {
/*-----------------------------------------------------------------*/
paint: function($element, layout) {
console.count();
/*-----------------------------------------------------------------*/
$(function() {
$element.html("#myButton").click(function() {
// for(var mynum = 1; mynum <= 5; mynum++){
// alert('button test' + mynum);
// };
});
});
/*-----------------------------------------------------------------*/
render($element, layout);
/*-----------------------------------------------------------------*/
}
};
});

app.getList is probably asynchronous (meaning it runs in the background). The function you've passed to it is a callback. That function will be ran at some point in the future, once the AJAX call (or whatever asynchronous method is ran) is done.
Your callback is passed reply, which is the "return" value from getList(). You cannot access str from outside of this function. You need to do whatever code with reply and/or str in that function only.

Related

How to display json data from js file in html page inside div

Here,I am getting data from db in JSON format into my .js file and I am getting in div also .But I am not getting the div in my HTML page.Please can anyone tell me how to show in my HTML page.Below is my code:
My json array:
[{"chat_question_id":"1",
"chat_question_title":"What is PHP?"},
{"chat_question_id":"17",
"chat_question_title":"what is php?",}
Below is my js code:
function ChatQuestionsInfo(bRowId)
{
var actionType = "";
var hdnFlagForSearchQue = $("#hdnFlagForSearchQue").val();
if(hdnFlagForSearchQue=="insert"){
actionType = "ChatQuestionsInfo";
} else {
actionType = "searchQuestiontitle";
}
if($.trim($("#questionname").val())==""){
$("#questionname").focus();
alert("Enter Question Name");
return false;
}
if($.trim($("#technologytags").val())==""){
$("#technologytags").focus();
return false;
}
$.post(rootUrl+"includes/ajax/ajax_chat.php", {action: actionType,bRowId:bRowId,bQuestionName: $.trim($("#questionname").val()),bTechnologyTags: $.trim($("#technologytags").val())},
function(data){
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="tab-content">';
htmlText += '<div id="newquestions"> : ' + data[key].chat_question_title + '</div>';
htmlText += '</div>';
}
$('.chat_body_form').append(htmlText);
}, "json");
return false;
}
HTML code:
<div id="newquestions"></div>
I think you need to make 2 changes, 1 is in ajax_chat.php file. and second in your javascript.
Every JSON output need to have in pure JSON output, so javascript (or jquery) can easily read it. so on output of ajax_chat.php file, you have to set a header to give proper output content type.
for example
header('Content-Type:application/json');
echo json_encode('your varialbe array');
In jquery it is better to use $.each then for loop, and also you can append the data directly in the loop.
for example
function(data){
$.each(data,function(i){
$('.chat_body_form').append('<div class="tab-content"><div id="newquestions"> : '+ $(this).chat_question_title + '</div></div>';
});
}
I think these changes will work and also will be very simple and clean code to understand or change,
Thanks...

Why is this JavaScript parameter getting lost?

In this function, the value parameter is being passed down to fill in my URL. This works perfectly.
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + '(More from ' + value.snippet.channelTitle + ')</li>';
});
$('#results').html(html);
}
In this nearly identical function, the value param loses its value. I can't see how. It's difficult to debug why this is happening because console.log() just returns "ReferenceError: $ is not defined" no matter what I check (it returns this in the first section too, which works well).
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + ') </li>';
});
$('#results').html(html);
$('#results li a').click(function(){
playVid($(this).attr(value.id.videoId));
});
}
function playVid(vidID) {
var embedVid = 'https://www.youtube.com/embed/'+vidID+'?autoplay=1';
document.getElementById('player').src = embedVid;
}
Here I'm trying to push the value param (in the url again) to an iframe with id="player". The iframe receives an invalid param and the video won't play. Meanwhile the video plays in the first example. Where does value get lost?
value only exists within the scope of the each loop. So, first fix your reference error, and then I suggest the following changes in that second example:
1) Update the href with the videoId value in the each loop like in the first example:
<a href="https://www.youtube.com/watch?v=' + value.id.videoId + '">
2) And then launch the player with that value:
$('#results li a').click(function(e) {
e.preventDefault();
playVid($(this).attr('href'));
});

jQuery UI accordion not working when data is refreshed

I have an HTML page in which data is being dynamically loaded into accordions. The accordion call is happening from inside a function. This function is being called at regular intervals to refresh the data. The accordion is showing correctly the first time, but getting destroyed when the data is refreshed. Here is some relevant code:
HTML:
...
<div id="itemsList"></div>
...
JavaScript:
function updateList() {
var storedStates = startSpinner(spinner, 'itemsList');
$.post('interface/getitemss.php',
function(data) {
var dataObj = $.parseJSON(data);
if(dataObj.status == 0) {
var itemDetails = dataObj['data'];
$("#itemsList").html("");
var infoLevel = getInfoLevel();
for (var i = 0; i < itemsDetails.length; i++) {
var rowContent = "<h3>";
if (item.type == 3 && item.approvals > 0) {
rowContent += "<span class='" + qaprColor + "'>";
rowContent += "<i class='icon-bell'></i>" + space + item.approvals + "</span>" + pipespace;
}
...
rowContent += "</div>";
$("#itemsList").append(rowContent);
}
$("#itemsList").accordion();
else in the code, I am using this:
var intervalTimer = setInterval(function() {updateList();}, <?php echo $interval; ?>);
This called the updateList() method regularly to update the data. The problem is, the moment this method is called, the previously-working accordion is destroyed and the data are appearing like normal HTML. Does anyone know how this could be fixed? Thanks!!
Have you tried calling destroy on the accordion before creating it again?
$("#itemsList").accordion( "destroy" );
$("#itemsList").accordion();
found in api docs

Limit number of Dynamic list Items in a Function

I would like to achieve 2 things with this Code I have been working on so not sure if to separate the Questions:
JS:
function listPosts(data) {
postlimit =
var output='<ul data-role="listview" data-filter="true">';
$.each(data.posts,function(key,val) {
output += '<li>';
output += '<a href="#devotionpost" onclick="showPost(' + val.id + ')">';
output += '<h3>' + val.title + '</h3>';
output += '<p>' + excerpt + '</p>';
output += '</a>';
output += '</li>';
}); // go through each post
output+='</ul>';
$('#postlist').html(output);
} // lists all the posts
Questions:
1: I would like to limit the number of Dynamic List Posts returned to 8
2: While I limit the displayed items, I want to add a 'More...' text at the bottom so another set of 8 items is appended to already displayed list.
I am already trying out some codes but was hoping to get some guidance
function listPosts(data, postlimit) {
var $output = $('<ul class="posts" data-role="listview" data-filter="true">');
$.each(data.posts,function(key, val) {
$("<li>", {id: "post_" + val.id})
.append([
$("<h3>", {text: val.title}),
$("<p>", {text: val.excerpt})
])
.appendTo($output);
return (postlimit-- > 1);
});
$('#postlist').empty().append($output);
}
// exemplary delegated event handler
$(document).on("click", "ul.posts h3", function () {
$(this).show();
});
later ...
listPosts(data, 8);
Notes:
from $.each() you can return true or false. If you return false, the loop stops.
Try not to build HTML from concatenated strings. This is prone to XSS vulnerabilities that are easy to avoid. jQuery gives you the tools to build HTML safely.
Generally, for the same reason, try to avoid working with .html(), especially if you already have DOM elements to work with.
Don't use inline event handlers like onclick. At all. Ever.
I am answering you on basis of pure logic and implementation of logic. there could be API stuff for it , but I don't really know. Secondly; It would be a good solution to find some jQuery plugin if you don't have any problems with using jQuery.
call the function onMoreClick() upon clicking the More... html item
var end = 8;
var start = 1;
function onMoreClick()
{
start = end
end = end+8;
listPosts(data)
}
function listPosts(data) {
postlimit =
var output='<ul data-role="listview" data-filter="true">';
var i = start;
$.each(data.posts,function(key,val) {
if(i<end && i >=start){
output += '<li>';
output += '<a href="#devotionpost" onclick="showPost(' + val.id + ')">';
output += '<h3>' + val.title + '</h3>';
output += '<p>' + excerpt + '</p>';
output += '</a>';
output += '</li>';
i++;
}
}); // go through each post
output+='</ul>';
$('#postlist').html(output);
} // lists all the posts

Issue with JavaScript Array

Can you please take a look at following code and let me know why I am not able to run the program?
enter code here
$(document).ready(function()
{
var comp=new Array("AAPL","MSFT","XRTX&");
var t = setInterval(function(){getPrice();},200);});
function getPrice() {
for (var i=0;i<comp.length;i++){
$.getJSON('https://finance.google.com/finance/info?client=ig&q='+comp[i]+'&callback=?', function(response){
var stockInfo = response[0];
var stockString = '<div id="stockprice">';
stockString += 'Candente Copper: DNT $'+''+stockInfo.l+'';
stockString += '</div>';
$('#stockprice').replaceWith(stockString);
$("#stockprice:contains('-')").addClass('red');
$("#stockprice:contains('+')").addClass('green');
}
});
}​
Is there any problem with my Array object or other parts of program has issue? Please be advised that the code works fine without calling the array elements.
Thanks
Your {s, }s, (s and )s do not all match up correctly. Also, in order for your function to have a reference to the comp variable, they must both be in the same function scope, in this case: $(document).ready(function(){ ... });. You'll notice that I also increased your setInterval to 2000 (2s).
EXAMPLE
$(document).ready(function()
{
var comp = new Array("AAPL","MSFT","XRTX&");
var t = setInterval(function(){getPrice();},2000);
function getPrice()
{
for (var i=0;i<comp.length;i++){
$.getJSON('https://finance.google.com/finance/info?client=ig&q='+comp[i]+'&callback=?', function(response){
var stockInfo = response[0];
var stockString = '<div id="stockprice">';
stockString += 'Candente Copper: DNT $'+''+stockInfo.l+'';
stockString += '</div>';
$('#stockprice').replaceWith(stockString);
$("#stockprice:contains('-')").addClass('red');
$("#stockprice:contains('+')").addClass('green');
});
}
}
});​

Categories

Resources