Can't scrobble tracks (batch) to Last.fm API. Invalid method signature - javascript

I've been trying this for a while now, but I can't get my head around what's wrong. Maybe I've tried so many ways that I'm not even sure this piece of code is right anymore.
Basically I'm trying to use the track.scrobble method from the Last.fm API, sending a batch of tracks.
That's the code I have, and it's always returning Invalid method signature. Does anyone can give me some help here, please?
UPDATE
Based on mccannf answer, I've changed the code, but am still getting the error:
var apiUrl = "http://ws.audioscrobbler.com/2.0/";
var apiMethod = "track.scrobble";
var apiKey = "MY_API_KEY";
var apiSecret = "MY_API_SECRET";
var key = "MY_SESSION_KEY";
var apiSig = "";
var lastfmScrobble = function (data) {
var dataToScrobble = setTiming(data);
var albums = [];
var artists = [];;
var timestamps = [];
var tracks = [];
var dataToHash = "";
for (var i = 0; i < dataToScrobble.tracks.length; i++) {
albums["album["+ i.toString() + "]"] = dataToScrobble.album;
artists["artist[" + i.toString() + "]"] = dataToScrobble.artist;
timestamps["timestamp[" + i.toString() + "]"] = dataToScrobble.tracks[i].split("|")[1];
tracks["track[" + i.toString() + "]"] = dataToScrobble.tracks[i].split("|")[0];
}
dataToHash += albums.sort().join("");
dataToHash += "api_key" + apiKey;
dataToHash += artists.sort().join("");
dataToHash += "method" + apiMethod;
dataToHash += "sk" + key;
dataToHash += timestamps.sort().join("");
dataToHash += tracks.sort().join("");
dataToHash += apiSecret;
apiSig = $.md5(unescape(encodeURIComponent(dataToHash)));
var songsToScrobble = {};
$.extend(songsToScrobble,
albums.sort(),
{ api_key: apiKey },
{ api_sig: apiSig },
artists.sort(),
{ method: apiMethod },
{ sk: key },
timestamps.sort(),
tracks.sort());
$.ajax({
url: apiUrl,
type: "POST",
data: songsToScrobble,
success: function (data) {
console.log(data);
}
});
}
Now the object sent has the correct format (JSON). What can still be wrong?

I did a quick sample JS Fiddle of your code.
The dataToHash is like this:
album[0]Achtung Babyalbum[1]Achtung Babyapi_keyxxxBLAHxxxartist[0]U2artist[1]U2methodtrack.scrobbleskkkkFOOkkktimestamp[0]1379368800timestamp[1]1379369000track[0]Onetrack[1]The FlymmmySecrettt
The songsToScrobble variable in the code above looked like this:
{ "album": [
"album[0]Achtung Baby",
"album[1]Achtung Baby"
],
"api_key":"xxxBLAHxxx",
"api_sig":"8dbc147e533411a41ba9169f59e65b3a",
"artist":["artist[0]U2","artist[1]U2"],
"method": "track.scrobble",
"sk":"kkkFOOkkk"
"timestamp": [
"timestamp[0]1379368800",
"timestamp[1]1379369000"
],
"track": [
"track[0]One",
"track[1]The Fly"
]
}
I believe songsToScrobble should look like this:
{ "album[0]": "Achtung Baby",
"album[1]": "Achtung Baby",
"api_key":"xxxBLAHxxx",
"api_sig":"8dbc147e533411a41ba9169f59e65b3a",
"artist[0]": "U2",
"artist[1]": "U2",
"method": "track.scrobble",
"sk":"kkkFOOkkk"
"timestamp[0]": "1379368800",
"timestamp[1]": "1379369000",
"track[0]": "One",
"track[1]": "The Fly"
}
Only other minor point is to make sure dataToHash is UTF-8 encoded before you convert to MD5 hash.
Edit
This is how I created the data for the ajax call. NOTE: this is untested - I don't have a last.fm account.
var songsToScrobble = {};
function addDataToScrobble(parentElement, inputData) {
if ($.isArray(inputData)) {
$.each(inputData, function(index ,element) {
songsToScrobble[parentElement + "[" + index + "]"] = element;
dataToHash += parentElement + "[" + index + "]" + element;
});
} else {
songsToScrobble[parentElement] = inputData;
dataToHash += parentElement + inputData;
}
}
for (var i = 0; i < data.tracks.length; i++) {
albums.push(data.album);
artists.push(data.artist);
// The tracks are coming in the format: title|timestamp
timestamps.push(data.tracks[i].split("|")[1]);
tracks.push(data.tracks[i].split("|")[0]);
}
addDataToScrobble("album", albums);
addDataToScrobble("api_key", apiKey);
addDataToScrobble("artist", artists);
addDataToScrobble("method", apiMethod);
addDataToScrobble("sk", key);
addDataToScrobble("timestamp", timestamps);
addDataToScrobble("track", tracks);
apiSig = $.md5(unescape(encodeURIComponent(dataToHash+apiSecret)));
songsToScrobble["api_sig"] = apiSig;
$.ajax({
url: apiUrl,
type: "POST",
data: songsToScrobble,
success: function (data) {
console.log(data);
}
});

Related

change API data depending on if statment

I'm trying to fetch data through API , and the URL contains two object and I targeted the quizzes , "quizzes": [2 items], "warnings": []
quizzes return me two objects with their details.
what I'm trying to achieve is to add if statement to retrieve the grades (another API) depends on quiz name and it is working well , but I want to add inside it another if to retrieve grades depends on the another quiz name, please see the code below how to target posttest inside pretest they have the same key and I want the data to be changed depends on quiz name.
var get_quiz = {
"url": "MyURL"
};
$.ajax(get_quiz).done(function (get_quiz_res) {
var reslength = Object.keys(get_quiz_res).length;
for (let b = 0; b < reslength; b++) {
var get_grade = {
"url": "*******&quizid="+get_quiz_res.quizzes[b].id"
};
$.ajax(get_grade).done(function (get_grade_res) {
var posttest=''
if (get_quiz_res.quizzes[b].name === "Post Test"){
posttest = get_grade_res.grade;
}
if (get_quiz_res.quizzes[b].name === "Pre Test"){
var row = $('<tr><td>' + userincourseres[i].fullname + '</td><td>' + get_grade_res.grade + '</td><td>' + posttest + '</td><td>');
$('#myTable').append(row);
}
});
}
});
the userincourseres[i].fullname from another api and it is working.
You can use async/await with $ajax if your JQuery version is 3+.
const get_quiz = {
url: "MyURL",
};
(async function run() {
const get_quiz_res = await $.ajax(get_quiz);
const reslength = Object.keys(get_quiz_res).length;
for (let b = 0; b < reslength; b++) {
const get_grade = {
url: "*******&quizid=" + get_quiz_res.quizzes[b].id,
};
let posttest = "";
const get_grade_res = await $.ajax(get_grade);
if (get_quiz_res.quizzes[b].name === "Post Test") {
posttest = get_grade_res.grade;
}
if (get_quiz_res.quizzes[b].name === "Pre Test") {
var row = $(
"<tr><td>" +
userincourseres[i].fullname +
"</td><td>" +
get_grade_res.grade +
"</td><td>" +
posttest +
"</td><td>"
);
$("#myTable").append(row);
}
}
})();

Drop down list (Asp.net web forms) not getting populated with data

I have jQuery call to get the data and a dropdown list on the UI, which is not populating the data.
I have tried many ways, commented is the code I used.
Let me know if I did something wrong in the code.
var questionData;
var optionData;
$(document).ready(function () {
$.ajax({
url: 'coaching-assessment-tool.aspx/GetCATQuestionAndOptions',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
questionData = data.d[0];
optionData = data.d[1];
console.log(questionData[0].QuestionText);
console.log("Question Data", questionData);
console.log("Option Data", optionData);
//Questions
document.getElementById('firstQuestion').innerHTML = questionData[0].QuestionText;
document.getElementById('secondQuestion').innerHTML = questionData[1].QuestionText;
document.getElementById('thirdQuestion').innerHTML = questionData[2].QuestionText;
document.getElementById('fourthQuestion').innerHTML = questionData[3].QuestionText;
document.getElementById('fifthQuestion').innerHTML = questionData[4].QuestionText;
document.getElementById('sixthQuestion').innerHTML = questionData[5].QuestionText;
document.getElementById('seventhQuestion').innerHTML = questionData[6].QuestionText;
document.getElementById('eighthQuestion').innerHTML = questionData[7].QuestionText;
document.getElementById('ninthQuestion').innerHTML = questionData[8].QuestionText;
document.getElementById('tenthQuestion').innerHTML = questionData[9].QuestionText;
//Responses
//var ddlFirstResponse = document.getElementById('#ddlFirstResponse');
//ddlFirstResponse.empty();
$(function () {
$('#ddlFirstResponse').append($("<option></option>").val('').html(''));
$.each(optionData, function (key, value) {
//console.log('option: ' + value.OptionText + ' | id: ' + value.OptionId);
//$('#ddlFirstResponse').append($("<option></option>").val(value.OptionId).html(value.OptionText));
$("#ddlFirstResponse").append("<option value='" + value.OptionId + "'>" + value.OptionText + "</option>");
});
});
},
error: function (error) {
console.log(error);
alert('Error retrieving data. Please contact support.');
}
});
});
<asp:DropDownList ID="ddlFirstResponse" runat="server"></asp:DropDownList>
Your data return handler is a bit off when the returned data is acquired, you can do the following to alleviate that:
function (data, status) {
var json = data;
obj = JSON.parse(json);
var opt = null;
$("#targetIDOfControl").empty();
for (i = 0; i < obj.People.length; i++) {
if (i < obj.People.length) {
opt = null;
opt = document.createElement("option");
document.getElementById("targetIDOfControl").options.add(opt);
opt.text = obj.People[i].Name;
opt.value = obj.People[i].ID;
}
}
The above example creates an option then sets its text and values. Then replicates more options depending on the amount of indexes in the JSON array returned.
Since I received response a bit late, I did trial and error, and finally made it to work.
Here is the code changes I made to make it work.
var ddlFirstResponse = **$("[id*=ddlFirstResponse]");**
ddlFirstResponse.empty();
$(function () {
ddlFirstResponse.append($("<option></option>").val('').html('-- Select value --'));
$.each(industryOptionData, function (key, value) {
//console.log('option: ' + value.OptionText + ' | id: ' + value.OptionId);
ddlFirstResponse.append($("<option></option>").val(value.OptionId).html(value.OptionText));
//ddlFirstResponse.append("<option value='" + value.OptionId + "'>" + value.OptionText + "</option>");
});
});
//var ddlFirstResponse = document.getElementById('ddlFirstResponse'); --> Failed
var ddlFirstResponse = $("[id*=ddlFirstResponse]"); --> worked

button function is not defined with htmlstring

I am able to display out all the details including the button. However, the main problem is that the when I click the button, nothing happens. It says that BtnRemoveAdmin() is not defined when I inspect for errors. However, I have function BtnRemoveAdmin()?? I have tried to move the function to htmlstring. Nothing works. I am not sure what went wrong.
(function () {
$(document).ready(function () {
showadmin();
});
function showadmin() {
var url = serverURL() + "/showadmin.php";
var userid = "userid";
var employeename = "employeename";
var role ="role";
var JSONObject = {
"userid": userid,
"employeename": employeename,
"role": role,
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("fail");
}
});
}
function _getAdminResult(arr) {
for (var i = 0; i < arr.length; i++) {
htmlstring = '<div class="grid-container">' +
'<div>' + arr[i].userid + '</div>' +
'<div>' + arr[i].employeename + '</div>' +
'<div>' + arr[i].role + '</div>' +
'<div>' + '<button onclick="BtnRemoveAdmin()">Remove</button>' + // 'BtnRemoveAdmin' is not defined
'</div>' ;
$("#name").append(htmlstring);
}
function BtnRemoveAdmin() {
var data = event.data;
removeadmin(data.id);
}
}
function removeadmin(userid) {
window.location = "removeadmin.php?userid=" + userid;
}
})();
All your code is defined inside an IIFE.
That includes BtnRemoveAdmin.
When you generate your JavaScript as a string, it is evaled in a different scope.
BtnRemoveAdmin does not exist in that scope.
Don't generate your HTML by mashing strings together.
Use DOM instead.
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
I use JQuery, and sometimes I get the same problem with plain JS functions not being called.
So I create JQuery functions :
$.fn.extend({
btnRemoveAdmin: function() {
...//Do what you want here
}
});
To call it use :
<button onclick="$().btnRemoveAdmin();"></button>
Hope it helps you !

Post restful method java error

Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';

Merging JSON api Response using Javascript

I am trying get paged json responses from Topsy (http://code.google.com/p/otterapi/) and am having problems merging the objects. I want to do this in browser as the api rate limit is per ip/user and to low to do things server side.
Here is my code. Is there a better way? Of course there is because this doesn't work. I guess I want to get this working, but also to understand if there is a safer, and/or more efficient way.
The error message I get is ...
TypeError: Result of expression 'window.holdtweetslist.prototype' [undefined] is not an object.
Thanks in advance.
Cheers
Stephen
$("#gettweets").live('click', function(event){
event.preventDefault();
getTweets('stephenbaugh');
});
function getTweets(name) {
var MAX_TWEETS = 500;
var TWEETSPERPAGE = 50;
var BASE = 'http://otter.topsy.com/search.json?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + name + '&page=1';
var currentpage = 1;
alert(BASE);
$.ajax({
dataType: "json",
url: BASE,
success: function(data) {
window.responcesreceived = 1;
var response=data.response;
alert(response.total);
window.totalweets = response.total;
window.pagestoget = Math.ceil(window.totalweets/window.TWEETSPERPAGE);
window.holdtweetslist = response.list;
window.holdtweetslist.prototype.Merge = (function (ob) {var o = this;var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {o[z] = ob[z];}}return o;});
// alert(data);
;; gotTweets(data);
var loopcounter = 1;
do
{
currentpage = currentpage + 1;
pausecomp(1500);
var BASE = 'http://otter.topsy.com/search.json?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + name + '&page=' + currentpage;
alert(BASE);
$.ajax({dataType: "json", url: BASE, success: gotTweets(data)});
}
while (currentpage<pagestoget);
}
});
};
function gotTweets(data)
{
window.responcesreceived = window.responcesreceived + 1;
var response = data.response;
alert(response.total);
window.holdtweetslist.Merge(response.list);
window.tweetsfound = window.tweetsfound + response.total;
if (window.responcesreceived == window.pagestoget) {
// sendforprocessingsendtweetlist();
alert(window.tweetsfound);
}
}
You are calling Merge as an static method, but declared it as an "instance" method (for the prototype reserved word).
Remove prototype from Merge declaration, so you'll have:
window.holdtweetslist.Merge = (function(ob)...
This will fix the javascript error.
This is Vipul from Topsy. Would you share the literal JSON you are receiving? I want to ensure you are not receiving a broken response.
THanks to Edgar and Vipul for there help. Unfortunately they were able to answer my questions. I have managed to work out that the issue was a combination of jquery not parsing the json properly and needing to use jsonp with topsy.
Here is a little test I created that works.
Create a doc with this object on it ....
RUN TEST
You will need JQUERY
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
And put the following in a script too. The is cycle through the required number of tweets from Topsy.
Thanks again everyone.
$("#gettweets").live('click', function(event){
event.preventDefault();
getTweets('stephenbaugh');
});
var MAX_TWEETS = 500;
var TWEETSPERPAGE = 50;
var BASE = 'http://otter.topsy.com/search.json';
var currentpage;
var responcesreceived;
var totalweets;
var pagestoget;
var totalweets;
var TWEETSPERPAGE;
var holdtweetslist = [];
var requestssent;
var responcesreceived;
var tweetsfound;
var nametoget;
function getTweets(name) {
nametoget=name;
currentpage = 1;
responcesreceived = 0;
pagestoget = 0;
var BASE = 'http://otter.topsy.com/search.js?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + nametoget + '&page=1';
$('#gettweets').html(BASE);
$.ajax({url: BASE,
dataType: 'jsonp',
success : function(data) {
getalltweets(data);
}
});
};
function getalltweets(data) {
totalweets = data.response.total;
$('#gettweets').append('<p>'+"total tweets " + totalweets+'</p>');
$('#gettweets').append('<p>'+"max tweets " + MAX_TWEETS+'</p>');
if (MAX_TWEETS < totalweets) {
totalweets = 500
}
$('#gettweets').append('<p>'+"new total tweets " + totalweets+'</p>');
gotTweets(data);
pagestoget = Math.ceil(totalweets/TWEETSPERPAGE);
var getpagesint = self.setInterval(function() {
currentpage = ++currentpage;
var BASE = 'http://otter.topsy.com/search.js?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + nametoget + '&page=' + currentpage;
$.ajax({url: BASE,
dataType: 'jsonp',
success : function(data) {
gotTweets(data);
}
});
if (currentpage == pagestoget) {
$('#gettweets').append('<p>'+"finished sending " + currentpage+ ' of ' + pagestoget + '</p>');
clearInterval(getpagesint);
};
}, 2000);
};
function gotTweets(data)
{
responcesreceived = responcesreceived + 1;
holdlist = data.response.list;
for (x in holdlist)
{
holdtweetslist.push(holdlist[x]);
}
// var family = parents.concat(children);
$('#gettweets').append('<p>receipt # ' + responcesreceived+' - is page : ' +data.response.page+ ' array length = ' + holdtweetslist.length +'</p>');
// holdtweetslist.Merge(response.list);
tweetsfound = tweetsfound + data.response.total;
if (responcesreceived == pagestoget) {
// sendforprocessingsendtweetlist();
$('#gettweets').append('<p>'+"finished receiving " + responcesreceived + ' of ' + pagestoget + '</p>');
}
}

Categories

Resources