Below is my JavaScript code for calling the server API:
<script type='text/javascript'>
call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) {
document.getElementById('show').innerHTML=response;
});
</script>
When I print the response in an HTML tag:
<h1 id='show'></h1>
I'm getting results in this format:
{"code":"200","status":"Success:Mail Credit Details","Mail Credits":"46"}
But what I want is a result like this:
<h1>code:200</h1>
<h1>status:Success:Mail Credit Details</h1>
<h1>Mail Credits:46</h1>
I tried the following, but nothing was displayed:
var obj=['show']
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["code"]+"</td>";
var td2="<td>"+obj[i]["status"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
First of all you'll need 3 h1 elements, so change the 'show' element to a div like this;
<div id='show'></div>
Then in your javascript code, access response elements by their name like this;
<script type='text/javascript'>
call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) {
var obj = JSON.parse(response);
for(var prop in obj) {
document.getElementById('show').innerHTML += '<h1>' + prop + ":" + obj[prop] + '</h1>';
}
});
Related
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.
I'm trying to list all blog posts with the Blogger API v3:
<script type="text/javascript">
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
$('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
$('.post p').html(Object.keys(response.items[i].title));
}
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>
This does append 3 divs (because of 3 posts) to my content div. But the content of each of this divs is:
<p>
"1"
"2"
"3"
"4"
"5"
</p>
I have no clue why, though I assume that title is an attribute of items[].
Any solutions or clues?
Thanks for answers!
You should removed Object.keys() and try this:
<script type="text/javascript">
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
$('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
$('.post p').html(response.items[i].title);
}
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>
In you case you shouldn't use Object.keys()
You request doesn't use the maxResults parameter and limited number of posts is retrieved so I recommend to use Google JavaScript Client Library - Blogger API and recursively retrieve all posts of a blog.
See the following example:
<script>
function renderResults(response) {
if (response.items) {
for (var i = 0; i < response.items.length; i++) {
//do whatever you want with the posts of your blog
}
}
if(response.nextPageToken) {
var blogId = 'XXX Your blogId XXX';
var request = gapi.client.blogger.posts.list({
'blogId': blogId,
'pageToken': response.nextPageToken,
'maxResults': 100,
});
request.execute(renderResults);
}
}
function init() {
gapi.client.setApiKey('XXX Get your API Key from https://code.google.com/apis/console XXX');
gapi.client.load('blogger', 'v3', function() {
var blogId = 'XXX Your blogId XXX';
var request = gapi.client.blogger.posts.list({
'blogId': blogId,
'maxResults': 100,
});
request.execute(renderResults);
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
I have written my javascript too much, and now the code keeps repeating itself, whereas I lack of knowledge on how to simplify matters. I have this idea of calling variable into function, but I don't know how to call this kind of function that contains dynamic variables.
Anyone got any tips on how can I achieve this?
var container = '#content_container';
function container_load(){
var data = $(this).attr('data');
var dataObject = {command : data};
var title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
container_load();
$(container).prepend(title);
});
});
Apparently, console returned ReferenceError: Can't find variable: dataObject
There is two issue is in your code
var container = '#content_container';
var title; //title should be declare as global,same as "container" variable
function container_load(dis){
var data = dis.attr('data');
var dataObject = {command : data};
title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
}
$(function(){
$('nav').on('click', 'a', function(){
container_load($(this)); //you have to pass the current element
$(container).prepend(title);
});
});
Demo : Demo
Try this :
var container = '#content_container';
function container_load(currElementId){
var data = $("#"+currElementId).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
var title = container_load(this.id);
$(container).prepend(title);
});
});
Here your problem is that you cannot 'this' in other function for that you need to pass it from your current function.
There seems to be few mistakes in your code, The scope is wrong and the data attribute is used not correctly I presume. I suppose this is what you wanted http://jsfiddle.net/EjEqK/2/
HTML
<nav >aaa</nav>
<div id="content_container"></div>
JS
function container_load() {
var data = $(this).data("val");
var dataObject = { command: data };
$("#content_container").prepend('<h2 data-val="' + dataObject.command + '">' + dataObject.command + '</h2>');
};
$(function () { $('nav > a').on('click', container_load); });
PS: If you don't need dataObject for anything else, directly use data
I think this will help you :
function container_load(currElement){
var data = $(currElement).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
}
$(function(){
var container = '#content_container';
$('nav')on.('click', 'a', function(){
var title = container_load(this);
$(container).prepend(title);
});
});
You could do the following :
var container = '#content_container',
title; // make title global
function container_load() {
var data = $(this).attr('data');
var dataObject = { command: data };
title = '<h2 data="' + dataObject.command + '">' +
dataObject.command + '</h2>';
};
$(function () {
$('nav') on.('click', 'a', function () {
container_load.call(this); // bind this to container_load
$(container).prepend(title);
});
});
But you could do even better :
$(function () {
$('nav') on.('click', 'a', function () {
var data = $(this).attr('data');
$('#content_container').prepend(
'<h2 data="' + data + '">' + data + '</h2>'
);
});
});
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');
});
}
}
});
Hello there i got some code here;
<script type="text/javascript">
$(function(){
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var feedTitle = item.title.$t;
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
var url = videoURL + videoID;
var thumb = "http://img.youtube.com/vi/"+ videoID +"/default.jpg";
HERE>>> list_data += '<button onclick="$('#bgndVideo').changeMovie('+ url +')">'+ feedTitle +'</button>';
});
$(list_data).appendTo(".playlist_elements");
});
});
</script>
This isnt working because of "$('#bgndVideo')" fragment that i need to pass as a text to be rendered in html so it looked like this in html:
<button onclick="$('#bgndVideo').changeMovie('http://www.youtube.com/watch?v=SOME_VIDEO_ID')"> Test </button>
How could i fix this so "$('#bgndVideo')" fragment would be treated as a text?
You would need to escape the 's:
list_data += '<button onclick="$(\'#bgndVideo\').changeMovie(\''+ url +'\')">'+ feedTitle +'</button>';
However, a cleaner approach might be something like this:
$list_data = $("<button>").html(feedTitle)
.click(function(){
$('#bgndVideo').changeMovie(url);
});