Output response details via loop - javascript

I submit some data via jQuery .ajax() and receive some data back via response. I need to output the data on my page. For example this is one of the responses I get:
{
"res": 1,
"item": [
{"id":"1","desc":"blue box","rating":"1"},
{"id":"2","desc":"red ball","rating":"5"}
]
}
I output this response via a loop like this:
...
success: function (response) {
for (var i = 0; i < response.item.length; i++){
var item = response.item[i].id,
desc = response.item[i].desc,
rate = response.item[i].rating;
$('#em' + response.res).append(item+'. '+ desc + ' Rating:' + rate);
}
}
Unfortunately what I get is two rows of the same item. What am I missing?

For starters, your not closing your for loop.
success: function (response) {
for (var i = 0; i < response.item.length; i++){
var item = response.item[i].id,
desc = response.item[i].desc,
rate = response.item[i].rating;
$('#em' + response.res).append(item + '. ' + desc + ' Rating:' + rate);
}
}

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);
}
}
})();

Array to String with multiple languages

I have some data that is being fed into my form via php. I am then adding additional information to that and it is being sent out. There is no telling how many rows will be in my table, and Values 1-3 is the additional information that I am adding to EACH row.
How I send the info:
if(isset($_POST['val1']))
{
echo "Submitting\n";
print_r($_POST);
$variable = "val1=" . $_POST['val1'] . ",val2=" . $_POST['val2'] . ",val3=" . $_POST['val3'];
// set post fields
$post = [
'submit' => 'true',
'activity_name' => 'DataSend',
'params' => [
'Data' => $variable
]
];
How I think I need to get it to go out as a string to the application (I realize there is a bunch of options here, I'm not sure how to get it to work) I need this to go out as a string, right now it is being received as an Array:
<script type="text/javascript">
function sendData() {
var inputs = document.getElementById(‘TableName’).getElementsByTagName('input'),
data = [],
name, val1[], val2[], val3[];
for (var i = 0; i < inputs.length; i++) {
if ( inputs[i].type === 'submit') {
continue;
}
var variable = ''; for (var i = 0, len = input.length; i<len,i++) { variable += 'val1' + i + '=' + val1[i] + ',val2' + i + '=' + val2[i] + ',val3' + i + '=' + val3[i] + ','; }
var array_objects = [
{'name': 'val1';},
{'name': 'val2';},
{'name': 'val3';},
]
var array_to_join = [];
for (x = 0; x < array_objects.length;
x++) {
_.map(array_objects[x], function(key, value) {
array_to_join.push(key + '=' + value);
});
}
document.body.innerHTML =
array_to_join.join(', ');
}
}
}
</script>

Execute script after receiving a response in Chrome extension

I am trying to create a simple chrome extension. When a user clicks a checkbox a few datas are send to the background script and from there to the popup. The data is transmitted successfully and it is stored in localstorage at popup
$(document).ready(function() {
chrome.runtime.sendMessage({
from: 'popup',
subject: 'getmessage',
}, function(response) {
for (var x = 0; x < JSON.parse(response).length; x++) {
localStorage.setItem(JSON.parse(response)[x].acnumber, JSON.stringify(JSON.parse(response)[x]));
}
});
for (var i = 0, len = localStorage.length; i < len; i++) {
var datas = JSON.parse(localStorage.getItem(localStorage.key(i)));
var value = datas;
console.log(value);
$('table').append('<tr class="' + value.acnumber + '"><td>' + value.acnumber + '</td><td>' + value.name + '</td><td>' + value.amount + '</td></tr>')
}
})
The problem is that i have to open the popup twice to see the data (appended to the table). The loop is executing before the datas are added to the localstorage
You'll need to move the append table code inside the response function if you want to process the data right after the response callback is fired. Since you mentioned you need the data on multiple pages, you can move the chrome.runtime.sendMessage in its own function and call it only if you don't already have the data. Something like
function getMessage() {
chrome.runtime.sendMessage({
from: 'popup',
subject: 'getmessage',
}, function(response) {
localStorage['haveMessage'] = true;
for (var x = 0; x < JSON.parse(response).length; x++) {
localStorage.setItem(JSON.parse(response)[x].acnumber, JSON.stringify(JSON.parse(response)[x]));
}
processMessage();
});
}
function processMessage() {
for (var i = 0, len = localStorage.length; i < len; i++) {
var datas = JSON.parse(localStorage.getItem(localStorage.key(i)));
var value = datas;
console.log(value);
$('table').append('<tr class="' + value.acnumber + '"><td>' + value.acnumber + '</td><td>' + value.name + '</td><td>' + value.amount + '</td></tr>')
}
}
if (locaStorage['haveMessage']) {
processMessage();
} else {
getMessage();
}

Inserting JSON data into Sqlite/webSQL database

I am pulling data from my remote database and get this JSON data:
{"list1":{"id":1, "item":"testobj1"},"list2":{"id":2, "item":"testobj2"},"list3":{"id":3,
"item":"testobj3"},"list4":{"id":4, "item":"testobj4"},"list5":{"id":5, "item":"testobj5"}}
I can now loop through the objects in the data and display a list of objects on my screen. It works fine:
var d = JSON.parse(hr.responseText);
databox.innerHTML = "";
for (var o in d) {
if (d[o].item) {
databox.innerHTML += '<p>' + d[o].item + '</p>' + '<hr>';
}
}
Now however, I would like to insert this data into my Sqlite database. I am not quite sure how I can tell the loop that 'd[o].id' and 'd[o].item' are the items I would like insert into my db.
db.transaction(function(tx) {
var sql = "INSERT OR REPLACE INTO testTable (id, item) " + "VALUES
(?, ?)";
log('Inserting or Updating in local database:');
var d = JSON.parse(hr.responseText);
var id = d[o].id;
var item = d[o].item;
for (var i = 0; i < d.length; i++) {
log(d[o].id + ' ' + d[o].item);
var params = [d[o].id, d[o].item];
tx.executeSql(sql, params);
}
log('Synchronization complete (' + d + ' items synchronized)');
}, this.txErrorHandler, function(tx) {
callback();
});
I hope somebody can take a look at this loop and tell me where did I go wrong. Many thanks in advance!
You're iterating over d as if it's an array rather than an object. Something like this is probably what you're looking for:
var d = JSON.parse(hr.responseText);
for (var o in d) {
var params = [d[o].id, d[o].item];
tx.executeSql(sql, params);
}

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

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);
}
});

Categories

Resources