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();
}
Related
I am trying following code to display the tabs and tab content from Json data dynamically
<script>
var area, cus, project, curst;
$.ajax({
type: "POST",
url: "./QuizServlet",
success: function(responseText) {
console.log("rs" + responseText.toString());
var jsonData = JSON.parse(responseText);
var questions = new Array();
for (var i = 0; i < jsonData.length; i++) {
area = jsonData[i].area;
console.log("area" + area);
project = jsonData[i].projectName;
console.log("poj" + project);
projectdes = jsonData[i].projectDescription;
console.log("pojdes" + projectdes);
curst = jsonData[i].currentStatus;
console.log("cus" + curst);
var test = {
area: area,
cus: curst,
project: project,
projectdes: projectdes,
}
questions.push(test);
console.log("output" + test);
alert(JSON.stringify(test));
}
}
});
for (var i in test) {
$('.nav-tabs').append('<li role="area" class="">' + i + '</li>');
var div = '<div role="tabpanel" class="tab-pane" area="' + i + '">';
for (var j = 0; j < data[i].length; j++) {
var obj = data[i][j];
div += '<div area="' + obj.project + '">' + obj.projectdes + '</div>';
}
$('.tab-content').append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
</script>
<body>
<div class="container">
<ul class="nav nav-tabs" role="tablist"></ul>
<div class="tab-content"></div>
</div>
</body>
My Json data is coming correctly in JSON format from DB: Below data is coming fine from DB . I printed using alert statement
{"area":"CSE","cus":"progress","project":"Project 1","projectdes":"Class 1st"}
{"area":"ECE","cus":"complered","project":"Project 2","projectdes":"This is class 1st Project"}
{"area":"IT","cus":"progress","project":"project 1","projectdes":"This is Class 2nd project"}
{"area":"IT","cus":"pending","project":"Project 2","projectdes":"This is class 2nd project"}
I am trying to display area in tabs and other fields in tab content.But
the data is not getting displayed in jsp. I tried so many ways.But still data is not getting in tabs and tabs content. Please let me know where I am going wrong.
I updated the answer, you can replace the part of your <script> tag by the code below. And to make the UI feel better, modify the HTML and DOM part as per the UI frameworks like bootstrap, etc.
<script>
$.ajax({
type: "POST",
url: "./QuizServlet",
success: function (responseText) {
var jsonData = JSON.parse(responseText);
var uniueTabs = getUniqueLists(jsonData);
for (var i = 0; i < uniueTabs.length; i++) {
$('.nav-tabs').append('<li role="area" class="my-li' + i + '"><a href="#' + i +
'" aria-controls="' + i + '" role="tab" data-toggle="tab">' + uniueTabs[i].area +
'</a></li>');
var div = '<div role="tabpanel" class="tab-pane" area="' + i + '">';
for (var j = 0; j < uniueTabs[i].tabContent.length; j++) {
var obj = uniueTabs[i].tabContent[j];
div += '<div area="' + obj.project + '">' + obj.projectdes + '</div>';
}
$('.my-li' + i).append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
}
});
function getUniqueLists(responseText) {
var resArr = [];
responseText.filter(function (x, i) {
if (resArr.indexOf(x.area) === -1) {
resArr.push(x.area);
}
})
//console.log(resArr);
return mergeDataAreaWise(resArr, responseText);
}
function mergeDataAreaWise(area, responseText) {
var tabList = [];
for (var i = 0; i < area.length; i++) {
tabList.push({
area: area[i],
tabContent: []
});
}
for (var i = 0; i < tabList.length; i++) {
for (var j = 0; j < responseText.length; j++) {
var Obj = {
cus: responseText[j].cus,
project: responseText[j].project,
projectdes: responseText[j].projectdes
}
var currentArea = responseText[j].area;
if (tabList[i].area === currentArea) {
tabList[i].tabContent.push(Obj);
}
}
}
console.log(tabList);
return tabList;
}
</script>
Here is a similar plunkr example
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);
}
}
Here's a simple loop I'm running:
for (var key in TestApp.config.services) {
if (TestApp.config.services[key].files != "") {
var files = TestApp.config.services[key].files.split(',');
for (var i = 0; i <= files.length - 1; i++) {
var file_url = files[i];
console.log("About to download :" + file_url);
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(file_url) + '&callback=?', function(data) {
console.log("Downloaded file: " + file_url);
console.log(key);
});
}
}
}
The problem is that the key value is always the same by the time the JSON request finishes. How can I avoid this race condition so that the right key value is used when the $.getJSON is finished?
you need an Immediately-invoked function expression (IIFE):
for (var key in TestApp.config.services) {
if (TestApp.config.services[key].files != "") {
var files = TestApp.config.services[key].files.split(',');
for (var i = 0; i <= files.length - 1; i++) {
var file_url = files[i];
console.log("About to download :" + file_url);
// IIFE
(function(thiskey,this_file_url){
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(this_file_url) + '&callback=?', function(data) {
console.log("Downloaded file: " + this_file_url);
console.log(thiskey);
});
})(key,file_url);
}
}
}
One simple solution is to simply send the key with the request. I prefer to write it in {} notation.
Let me give you the basis to an answer to your question; I will disregard the part with the files, to emphasize where to look at.
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var items = ['Hello', 'World', 'foo', 'bar'];
for (var i=0; i < items.length; i++) {
console.log("About to download :" + items[i] + '" - key: ' + i);
$.getJSON( "ajax.php",
{
url: items[i],
key: i
},
function(data) {
var key = data.key;
console.log("Downloaded file: " + data.url + '" - key: ' + key);
}
);
}
</script>
ajax.php
<?php
echo json_encode(array('url'=>$_GET['url'], 'key'=>$_GET['key']));
?>
Below is the script:
$(document).ready(function () {
$.getJSON('table.json', function (data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
});
});
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000);
});
}
I want to update my data. The poll function is getting called after every 5 seconds which I checked through the alert. But data is not getting updated. Please tell me what I am doing wrong.
getJSON is a GET request so it will be cached. Set the proper no cache headers on the server.
Also look at your code, you are never processing the data
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000); //<--where is the processing you do nothing with the response???
});
}
$(document).ready(function() {
// make the initial JSON request
$.getJSON('table.json', init)
});
function poll() {
// make the subsequent JSON requests
$.getJSON('dummy.json', update);
}
function init(data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
}
function update(data) {
var rows = $("#mytable tr.tablecontent").toArray();
for (var i = 0, size = data.length; i < size; i++) {
if (rows[i])
rows[i].cells[3].firstChild.data = data[i].bid;
}
setTimeout(poll, 5000);
}
Here's the update function with more jQuery:
function update(data) {
$("#mytable tr.tablecontent > td:nth-child(4)")
.slice(0, data.length)
.text(function(i) {
return data[i].bid;
});
setTimeout(poll, 5000);
}
I am writing a game for Facebook. IN the following code, I have a problem. I have a for loop executing, and in that loop, I call a dialog and implement 'onconfirm' for the dialog. The problem is that I need to access th e loop counter inside of the onconfirm function. But because the onconfirm is called outside of the scope of the for loop, the counter value is no longer valid because it's been incremented. I need some way to pass the counter value to the dialog onconfirm as it was at the time the dialog was displayed, not after the loop has finished. Or maybe someone has a better solution. Any help would be appreciated. Thanks.
function unloadCargo() {
//debugger;
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Unloading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
debugger;
if(data.unloadableCargo.length == 0) {
loadCargo();
} else {
//console.log('unloadable cargo='+dump(data.unloadableCargo));
var i = 0;
var j = 0;
var ucCount = data.unloadableCargo.length;
for(i = 0; i < ucCount; i++) {
cargoDialog = new Dialog();
cargoDialog.showChoice('Unload Cargo', 'Unload ' + data.unloadableCargo[i].goods_name + ' at ' + data.unloadableCargo[i].city_name + ' for ' + data.unloadableCargo[i].payoff + 'M euros?');
cargoDialog.onconfirm = function() {
//console.log('unloadable cargo onconfirm='+dump(data.unloadableCargo));
var ajax = new Ajax();
var param = {"city_id": data.unloadableCargo[i].city_id, "goods_id": data.unloadableCargo[i].goods_id, "payoff": data.unloadableCargo[i].payoff};
ajax.ondone = function(demandData) {
var demands = document.getElementById('demands');
var innerXhtml = '<span>';
for(var j = 0; j < demandData.demands.length; j++) {
innerXhtml = innerXhtml + ' <div class="demand-item"><div class="demand-city">' + demandData.demands[j].city + '</div><div class="demand-pay">' + demandData.demands[j].cost + '</div><div class="demand-goods">' + demandData.demands[j].goods + '</div></div>';
}
innerXtml = innerXhtml + ' </span>';
demands.setInnerXHTML(innerXhtml);
// update balance
loadCargo();
}
ajax.post(baseURL + "/turn/do-unload-cargo", param);
}
cargoDialog.oncancel = function() { loadCargo(); }
}
//loadCargo();
}
}
ajax.post(baseURL + '/turn/unload-cargo');
}
You need to pass the value to the dialog somehow.
I have never looked at the FBJS, but it seems setContext can be used for that.
Try this:
cargoDialog = new Dialog().setContext({currentIndex: i});
// showChoice is the same
cargoDialog.onconfirm = function() {
alert(this.currentIndex); // Here you should be able to get it
}