Extracting user playcount from Last.fm API using JSON - javascript

In a nutshell, I'd like to display the Last.fm user playcount figure on my site (see 'playcount' on http://www.last.fm/api/show/user.getInfo). I've tried the following, but confess I have no idea if I'm on the right lines here.
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=XXX&api_key=XXX&limit=5&format=json&callback=?", function(data) {
var html = '';
$.each(data.user.playcount, function(i, item) {
html += "<p>" + item.playcount + "</p>";
});
$('#count').append(html);
});
});

The inner foreach loop is unnecessary, user.getInfo returns only one user's information after all. The following should work:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getInfo&user=XXX&api_key=XXX&format=json", function(data) {
var html = "<p>" + data.user.playcount + "</p>";
$('#count').append(html);
});
});
I have also removed the limit and callback parameters from the URL for brevity.

Related

Why always getting last row from json array result when iterate through with Jquery

I have json data in this structure
here is my json code
https://jsonblob.com/309e8861-7f26-11e7-9e0d-cf3972f3635e
and here is my jquery code example
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
$.each(data, function(index, val) {
$("#result").html("<p>" + val.name + "</p>");
});
});
});
HTML file
<button id="getJsonData">Load role list</button>
<div id="result"></div>
I don't get this, I get every value from json in console when do console.log, but when use html method to display result as html in screen it just showing last value from ending last json array. What is wrong here?
jquery .html always overrite previous html so we cant use html in loop section instead of that we can use append it simply append your p tag in result div
Instead of using this:-
$("#result").html("<p>" + val.name + "</p>");
use like this:-
$("#result").append("<p>" + val.name + "</p>");
You are overwriting the html with the code
$("#result").html("<p>" + val.name + "</p>");
Instead you can store the result in variable and then you write it to the element.Like this
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var html = '';
$.each(data, function(index, val) {
html +="<p>" + val.name + "</p>";
});
$("#result").html(html);
});
});
Your code should be :
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var listHtml="";
$.each(data, function(index, val) {
listHtml=listHtml+ "<p>" + val.name + "</p>";
});
$("#result").html(listHtml);
});
});
And Html should be same as your
<button id="getJsonData">Load role list</button>
<div id="result"></div>
Working example is here

I keep getting this error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This one is making me sick.because i cant find where i am going wrong.I will
appreciate any help or hint from you. below is my javascript code.so far the server side is fine but display the actual comment on the client side is the problem. please help me.
$(document).ready(function () {
// process the form
$('form.comments_form').each(function () {
var form_to_submit = $(this);
form_to_submit.submit(function (event) {
event.preventDefault();
var posta_id = form_to_submit.find("input[type=hidden].UNIQUE_ID").val();
var tetxarea1 = form_to_submit.find("textarea.target").val();
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(jQuery.parseJSON(response));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>'" + response.f_name + "'</span>";
comment_string += "<div class='my_msg'>'" + esponse.my_comment + "'</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>'" + response.my_comment_date + "'</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
});
});
});
i am trying to display the list to unordered lis with the class "comenting2"
change your code from
$("ul.comenting2").prepend(comment_string);
to
$("ul.comenting2").prepend($(comment_string));
Your response value already is an object since jquery parses it automatically (you put json as datatype). You are trying to json-parse an object, of course that has illegal characters.
Yes. To make it easier to understand the problem. I believe it would be great if you also supplied the sample of your JSON response. It is usually caused by bad JSON format.
Okay. Got your sample JSON response.
Try to change your code into:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(eval('('+response+')'));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>‘" + response.f_name + "’</span>";
comment_string += "<div class='my_msg'>‘" + esponse.my_comment + "’</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>‘" + response.my_comment_date + "’</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
Please noted the changes at ajax success and function display_the_comment(response)

How to speed up my Ajax call when there are multiple same ajax call made on a page?

When the page loads, I am also dynamically creating a block . I am using ajax call to go and fetch data from another page and then populating it and creating my structure that is then added to a particular dom element. However, the problem is when I do this several times on the page during page loads, it takes quite some time for all Ajax call to finish. Do you know how I can speed up the ajax call?
$('.content-tile').each(function (idx, ele) {
// Step 1: Get the stuffs and add it in the right place on page load
var node_id = $(ele).find('article').attr('data-history-node-id');
$.get('/node/' + node_id , function (data) {
var $title = $(data).find('.title').text();
var $summary = $(data).find('.article__body').text();
var $ctaText = $(data).find('.article__field-read-more-text').text();
var $redirectToFile = $(data).find('.article__field-nova-redirect-to-file').find('a').attr('href');
var $redirectToLink = $(data).find('.article__field-redirect-link').find('a').attr('href');
// Either redirect to file or redirect to link in the order
var $ctaLinkHref = $redirectToFile;
if ($redirectToLink) {
$ctaLinkHref = $redirectToLink;
}
var $contentHover = "<a class='content-added contenthover hoveredLink' href= " + $ctaLinkHref + "></a>";
$(ele).find('article').after($contentHover); // Add the div that will be targeted for the hover
var $contentHoverHeader = "<h2 class='contenthover__header'>" + $title + '</h2>';
var $contentHoverContent = "<p class='contenthover__content'>" + $summary + '</p>';
var $contentHoverLink = "<a class='contenthover__link' href=" + $ctaLinkHref + '>' + $ctaText + '</a>';
$(ele).find('.contenthover').append($contentHoverHeader, $contentHoverContent, $contentHoverLink);
});
});
As Rory mentioned, instead of calling multiple times, just create the single object, post it back and return all the related data in one go.
// construct the array
var nodes = []
$('.content-tile').each(function (idx, ele) {
var node_id = $(ele).find('article').attr('data-history-node-id');
nodes.push(node_id);
}
// call ajax now
$.ajax({
url: "/node/RetrieveDataByNodes", //the new method which can accept the array and return data
data: JSON.stringify(nodes),
type: 'GET',
dataType: 'json'
}).done(function(result) {
$.each(result, function (k, v) {
//do something for each value
console.log(v);
}
});

Use $.each and if with $.getJSON

Me and $.each aren't good friends, I can't seem to figure out how I should use this statement to print all my data in my JSON file. Another problem is the if statement, I tried it in many ways, but whatever I do, no data is being printed.
My JSON file
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
My $.getJSON script
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var el = document.getElementById("kome");
el.innerHTML = "<td><div class='dsc'>" + data.expo + "<br><em>" + data.datum + "</em></div></td>";
});
}
</script>
So how would I integrate the $.each statement and seperate from that, the if statement?
Try this
$.getJSON("home.json", function (data) {
var html = '',
el = document.getElementById("kome");
$.each(data, function (key, val) {
html += "<td><div class='dsc'>" + val.expo + "<br><em>" + val.datum + "</em></div></td>";
});
el.innerHTML = html;
});
Something like this?
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var html = '';
$.each(data, function(i, record) {
html += '' +
'<td>' +
'<a href="' + record.link + '" data-ajax="false">' +
'<img src="' + record.img + '">' +
'<div class="dsc">' +
record.expo + '<br>' +
'<em>' + record.datum + '</em>' +
'</div>' +
'</a>' +
'</td>';
});
$('#kome').html(html);
});
}
</script>
Note: I haven't tested this, so there may be a few syntax errors (mostly concerned about the quotes in the string concatenation).
I will note that you don't need jQuery's $.each for this; you can use a basic for-loop:
for (var i = 0; i < data.length; i++) {
var record = data[i];
... stuff...
}
jQuery's .each() is really useful when iterating over elements in the DOM, though. For example, if you wanted to iterate over the elements with class dsc, you could do:
$('.dsc').each(function(i, dsc) {
// Do stuff to the $(dsc) element.
});
Also, you might as well use jQuery's selectors (the $('#kome')) if you're going to use jQuery.
jQuery's API usually has solid examples for stuff; this is one such case.
$.each can iterate arrays [] or objects {}, your json contains both, so first you need to tackle array, that gives you an object on each iteration. Then you can access its properties.
jQuery each documentation
Second thing: to append to innerHTML use "+=" not "=" or you will reset html on each iteration.
var el = document.getElementById("kome");
$.getJSON('ajax/test.json', function(data) {
$.each(data, function(n, linkData) {
el.innerHTML += '' + linkData.expo + '';
});
}

Local JSON data to getJSON on URL

I am using this script which reads some internal json data.
The data is currently in the actual page.
I need to change the code to use getJSON? so that it reads the json from an external page/url
Here is the current full code:
<script>
var data = [{"id": "1","title": "mytitle"}];
var output = '';
$.each(data, function(index, value){
output += '<li data-icon="false">' + value.title + '</li>';
});
$('#listview').append(output).listview('refresh');
</script>
How do I change the code so I can use external json code instead of this way for example adding getJSON to it?
$.getJSON('url_to_script', function(data) {
var output = '';
$.each(data, function(index, value){
output += '<li data-icon="false">' + value.title + '</li>';
});
$('#listview').append(output).listview('refresh');
});
But if you're trying to get data from different domain then you need something following:
$.getJSON("url_to_script?jsoncallback=?",, function(data) {
var output = '';
$.each(data, function(index, value){
output += '<li data-icon="false">' + value.title + '</li>';
});
$('#listview').append(output).listview('refresh');
});
Read more about .getJSON().

Categories

Resources