How to update a website's information with Jquery without refreshing - javascript

I am trying to create a webapp that will display information and update it when a JSON file is updated. My current code only updates when both the JSON file are updated and the page is refreshed. The key is not to have the page refreshed. Here is my current code
<script>
$.getJSON('package.json', function (data) {
for (var i in data) {
var username = data[i].username;
var value = data[i].value;
var tokens = data[i].tokens;
$("#playerlist").append('<tr><td>-' + username + ' has deposited $' + value + ' in ' + tokens + ' tokens' + '</td></tr>');
}
});
</script>
Any help is very appreciated. Thanks!

By using SetInterval we can update the UI in some timeinterval.
function refreshContent()
{
$.getJSON('package.json', function (data) {
for (var i in data) {
var username = data[i].username;
var value = data[i].value;
var tokens = data[i].tokens;
$("#playerlist").append('<tr><td>-' + username + ' has deposited $' + value + ' in ' + tokens + ' tokens' + '</td></tr>');
}
setTimeOut(refreshContent, 1000) /// again wait for 1 sec and do refresh
});
}
setTimeOut(refreshContent, 1000) \\\this will update in every 1 sec.

Related

Zapier Code (JS) + Twitter API - POST statuses/update (in_reply_to_status_id)

What I'm trying to achieve is a Zapier Code (JS) action to preform a Twitter reply to a given status ID with a given text .
I'm already using the functioning Zapier (JS) Code action offered by #KayCee which preform a POST favorites/create and would like to modify it so it would preform a reply action to any given status_id using the POST statuses/update (in_reply_to_status_id) as instructed by Twitter API.
Here is #KayCee's code with the modifications I made to preform a reply:
// This code requires that you set the ID of the tweet that you want to reply to as an input variable called "reply_to_id" and the text you wish to reply as an input variable called "status_text". Learn more at https://zapier.com/help/code/#data-variables
// INSTUCTIONS FOR SETTING THESE REQUIRED VARIABLES: After you create a new app at https://apps.twitter.com/, click on the name of the app to open it. Then, select the "Keys and Access Tokens" tab.
var twitterApplicationConsumerKey = 'CONSUMERKEY';
var twitterApplicationConsumerSecret = 'CONSUMERSECRET';
var twitterApplicationAccessToken = 'ACCESSTOKEN';
var twitterApplicationAccessTokenSecret = 'ACCESSTOKENSECRET';
// That's it. No need to edit anything below.
function b64_hmac_sha1(k,d,_p,_z){
if(!_p){_p='=';}if(!_z){_z=8;}function _f(t,b,c,d){if(t<20){return(b&c)|((~b)&d);}if(t<40){return b^c^d;}if(t<60){return(b&c)|(b&d)|(c&d);}return b^c^d;}function _k(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}function _s(x,y){var l=(x&0xFFFF)+(y&0xFFFF),m=(x>>16)+(y>>16)+(l>>16);return(m<<16)|(l&0xFFFF);}function _r(n,c){return(n<<c)|(n>>>(32-c));}function _c(x,l){x[l>>5]|=0x80<<(24-l%32);x[((l+64>>9)<<4)+15]=l;var w=[80],a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(var i=0;i<x.length;i+=16){var o=a,p=b,q=c,r=d,s=e;for(var j=0;j<80;j++){if(j<16){w[j]=x[i+j];}else{w[j]=_r(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);}var t=_s(_s(_r(a,5),_f(j,b,c,d)),_s(_s(e,w[j]),_k(j)));e=d;d=c;c=_r(b,30);b=a;a=t;}a=_s(a,o);b=_s(b,p);c=_s(c,q);d=_s(d,r);e=_s(e,s);}return[a,b,c,d,e];}function _b(s){var b=[],m=(1<<_z)-1;for(var i=0;i<s.length*_z;i+=_z){b[i>>5]|=(s.charCodeAt(i/8)&m)<<(32-_z-i%32);}return b;}function _h(k,d){var b=_b(k);if(b.length>16){b=_c(b,k.length*_z);}var p=[16],o=[16];for(var i=0;i<16;i++){p[i]=b[i]^0x36363636;o[i]=b[i]^0x5C5C5C5C;}var h=_c(p.concat(_b(d)),512+d.length*_z);return _c(o.concat(h),512+160);}function _n(b){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s='';for(var i=0;i<b.length*4;i+=3){var r=(((b[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((b[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((b[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>b.length*32){s+=_p;}else{s+=t.charAt((r>>6*(3-j))&0x3F);}}}return s;}function _x(k,d){return _n(_h(k,d));}return _x(k,d);
}
var replyToId = input.reply_to_id;
var status = input.status_text;
//create nonce
function generateRandomString(desiredLengthOfRandomString) {
var result = '';
var possibleCharactersForRandomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < desiredLengthOfRandomString; i++ )
result += possibleCharactersForRandomString.charAt(Math.floor(Math.random() * possibleCharactersForRandomString.length));
return result;
}
var randomString = generateRandomString(32);
var nonce = new Buffer(randomString).toString('base64');
//create timestamp
var timestamp = Math.floor(new Date() / 1000);
//create the signature
var signatureParameterString = 'in_reply_to_status_id=' + replyToId + '&status=' + status + '&oauth_consumer_key=' + twitterApplicationConsumerKey + '&oauth_nonce=' + encodeURIComponent(nonce) + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + timestamp + '&oauth_token=' + twitterApplicationAccessToken + '&oauth_version=1.0';
var signatureBaseString = 'POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json&' + encodeURIComponent(signatureParameterString);
var signingKey = encodeURIComponent(twitterApplicationConsumerSecret) + '&' + encodeURIComponent(twitterApplicationAccessTokenSecret);
var signature = b64_hmac_sha1(signingKey, signatureBaseString);
var apiUrl = 'https://api.twitter.com/1.1/statuses/update.json?in_reply_to_status_id=' + replyToId + '&status=' + status;
var oauthString = 'OAuth oauth_consumer_key="' + twitterApplicationConsumerKey + '", oauth_nonce="' + encodeURIComponent(nonce) + '", oauth_signature="' + encodeURIComponent(signature) + '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' + timestamp + '", oauth_token="' + twitterApplicationAccessToken + '", oauth_version="1.0"';
fetch(apiUrl, {
method: 'POST',
headers: {
'Authorization': oauthString
}
})
.then(function(res) {
return res.json();
})
.then(function(body) {
var output = body;
callback(null, output);
})
.catch(callback);
For some reason, I keep on getting error message: "Could not authenticate you" although the same code worked for performing a "like".
Not sure what am I doing wrong?

How to send a javascript array to php [duplicate]

This question already has answers here:
How to pass data from Javascript to PHP and vice versa? [duplicate]
(7 answers)
Closed 4 years ago.
I have an array named "seat" in my javascript file.It is used to store the seat numbers when a user clicks on a seat in a theater layout.In my function,I've used a window alert to show the user his selected seats,and when he clicks OK button,I want to send these booked seats(values in my array) to a php file named "confirm".
Here is the javascript function.
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved!');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
$_POST('confirm.php', {seat: seat})
})
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
And this is my php code.
$seat = "";
if(isset($_POST['seat']))
{
$seat = $_POST["seat"];
print_r($seat);
}
When this is executed I get the window alert,but the values stored in the array does not pass to the php file.Is there something wrong with this code?Please help!I'm stuck here!!!
$_POST isn't a built-in method, and jQuery doesn't provide a method like that either-- you can't just "set" the values into the $_POST array like this.
To post using jQuery, you would do something like the following, including a handler for data returning from the server (if you have any):
$.post("confirm.php", { seat: seat})
.done(function(data){
alert('Received data from server: ' + data);
});
You need to send the data to your PHP script, this does nothing in your JS code:
$_POST('confirm.php', {seat: seat})
use something like jQuery post method or vanilla JS XMLHttpRequest

Vue.js mounted function runs too early

Essentially what I am trying to do is to run a a function that adds up different variables and sets a new one its pretty simple:
addup: function () {
this.homeScore1 = this.m1g1h + this.m1g2h + this.m1g3h + this.m1g4h + this.m2g1h + this.m2g2h + this.m2g3h + this.m2g4h;
this.awayScore1 = this.m1g1a + this.m1g2a + this.m1g3a + this.m1g4a + this.m2g1a + this.m2g2a + this.m2g3a + this.m2g4a;
this.homeScore2 = this.m3g1h + this.m3g2h + this.m3g3h + this.m3g4h + this.m4g1h + this.m4g2h + this.m4g3h + this.m4g4h;
this.awayScore2 = this.m3g1a + this.m3g2a + this.m3g3a + this.m3g4a + this.m4g1a + this.m4g2a + this.m4g3a + this.m4g4a;
this.hdoubles = this.m5g1h + this.m5g2h + this.m5g3h + this.m5g4h;
this.adoubles = this.m5g1a + this.m5g2a + this.m5g3a + this.m5g4a;
alert(this.m1g1h);
//total handicap is set here
this.hhandicap = this.singlesHHandicap + this.doublesHHandicap;
this.ahandicap = this.singlesAHandicap + this.doublesAHandicap;
//total score is calculated here
this.homescore = this.homeScore1 + this.homeScore2 + this.hdoubles + this.hhandicap;
this.awayscore = this.awayScore1 + this.awayScore2 + this.adoubles +this.ahandicap;
},
the value of this.m1g1h for example is set in a function called this.updatesSinglesScores(); that is run on page creation, It calls my databse and assignes the values returned to some vue variables:
created: function () {
this.updatesSinglesScores();
this.updateDoublesScores();
},
afterwards I call the addup function on mounted:
mounted: function () {
this.addup();
}
So the problem I am having is that the variable this.homeScore1 for example, that is being displayed in the html of the page does not chnages it remains to 0. Upon further inspection with the alert in the addup function I learned that this.m1g1h remains 0, even though it should be another value. Furthermore if I run the addup function with a button everything works fine. So could some one explain to me why this.m1g1h remains 0? also why does the addup function work when called from a button?

How to sort the loaded XML data

In my application, I have an XML file that connects to different API and gathers information. Then in a div, it shows the fetched information.
I do it successfully, but the issue is, the XML will not load if element one by one. It loads data in parallel, so the divs it creates are not in the right order like how they are in the xml file.
Here is a demo that get some data from local, SoundCloud, Spotify and iTunes.
And this is the XML file it is loading from:
$.ajax({
url: "https://dl.dropboxusercontent.com/u/33538012/text.xml",
dataType: "xml",
success: parse,
error: function() {
alert("Error");
}
});
function parse(document) {
var inc = 1;
$(document).find("track").each(function() {
var rowNum = inc;
var trackType = $(this).find('type').text();
var trackTitle = $(this).find('title').text();
var soundcloud_url = $(this).find('soundcloud_url').text();
var spotify_track_uri = $(this).find('spotify_track_uri').text();
var itunes_id = $(this).find('itunes_id').text();
if (trackType == "audio") {
inc = inc + 1;
$(".playlist").append("<div id='" + rowNum + "' >" + rowNum + " " + trackTitle + "</div>");
} else if (trackType == "soundcloud") {
inc = inc + 1;
SC.initialize({
client_id: "b8f06bbb8e4e9e201f9e6e46001c3acb"
});
SC.resolve(soundcloud_url).then(function(sound) {
trackTitle = sound.title;
$(".playlist").append("<div id='" + rowNum + "' >" + rowNum + " " + trackTitle + "</div>");
});
} else if (trackType == "spotify") {
inc = inc + 1;
var spotifyLink = "https://api.spotify.com/v1/tracks/" + spotify_track_uri;
$.getJSON(spotifyLink, function(data) {
trackTitle = data.name;
$(".playlist").append("<div id='" + rowNum + "' >" + rowNum + " " + trackTitle + "</div>");
});
} else if (trackType == "itunes") {
inc = inc + 1;
var iTuensLink = "https://itunes.apple.com/lookup?id=" + itunes_id + "&callback=?";
$.getJSON(iTuensLink, function(data) {
trackTitle = data.results[0].trackName;
$(".playlist").append("<div id='" + rowNum + "' >" + rowNum + " " + trackTitle + "</div>");
})
}
});
}
<script src="https://connect.soundcloud.com/sdk/sdk-3.1.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="playlist"></div>
If you look at the result of the code, the the number next to each row shows the order in the original XML file, but they are not loaded exactly one after each other.
Any way to sort the loaded files just like how they are written in the XML file?
You can use deffered object which are an extension of promise and can resolve it self.So they can act as a trigger when used with resolve
Crate an array that would hold our deffered objects note that order is important therefore numeric array is used
Just create a deffered
var dfd = jQuery.Deferred();
Define what should be done on
dfd.then(function(){
$(".playlist").append("<div id='" + rowNum + "' >" + rowNum + " " + trackTitle + "</div>");
})
Finally push it on our array
x.push(dfd)
After all api calls are over just call resolve on each
$.each(x, function(){
this.resolve(); //then callback gets called one by one on each deffered
});
https://jsfiddle.net/sanddune/rr7tord6/
You might want to have some mechanism to detect when the slowest call finishes and then call resolve
EDIT:
The latency of individual api varies greatly across geographies for example for me soundcloud was the most "laggy" so it ended up last but for someone else itunes may be the last to finish this is due to many variables like distance from server,ISP,throttling etc. so clearly you can never rely on "last man standing " approach so i could only suggest that use some sort of counter like this to track how many request are outstanding
First get total no. of nodes (inn xml) that have an api involved say you have just soundcloud and shopify so now total = 2 ; count = 0
so when the api request yields increment it by one like
$.getJSON(spotifyLink, function(data) {
trackTitle = data.name;
alert('shopify loaded');
count++;check();
});
or
SC.resolve(soundcloud_url).then(function(sound) {
trackTitle = sound.title;
alert('soundcloud loaded');
count++;check();
});
note that you need to increment on even failed api request (which may result from bad parameter etc.)
call a check function that will check if count == total on every success/fail part of api request
function check(){
if(count==total)
alert('all api request finished');
//resolve all deffereds
}

unable to iterate over json object using jquery

I am new to AJAX/JQuery/JSON, I am using Struts 2 to get a JSON object using AJAX, I can see the object returned but I am unable to iterate over it. The returned object is a list that has just one object(may contain more objects), also every object contains a list of some other object.
This is how the js file looks like:
$.getJSON('GetAllSaleItemsAction', {
customerName : debtorSelection
}, function(jsonResponse){
//alert(jsonResponse);
//populate table
var trHtml = '';
//$("tr:has(td)").remove();
jsonResponse = jsonResponse.saleItemsList;
var responseString = JSON.stringify(jsonResponse);
console.log(responseString);
$.each(jsonResponse, function(i, item) {
var saleEntries = $.parseJSON(item.singleSaleEntries);
var saleEntriesString = JSON.stringify(saleEntries);
console.log(saleEntriesString);
var sseString = '';
$.each(saleEntries, function(n, sse){
sseString += sse.item + ' ' + sse.quantity + ' x ' + sse.price + ' = ' + sse.amount;
});
trHtml+= '<tr><td>' + item.date + '</td><td>' + sseString + '</td><td>' + item.saleAmount + '</td><td>' + item.interest + '</td><td>' + item.totalAmount + '</td></tr>';
});
if(trHtml != ''){
$('#saleRecordTable').append(trHtml);
}
});
Here the first console.log is executed but not the second console.log as javascript inside the each-function is not executed:
[{"customerName":"Tester","date":"2015-02-16T17:36:19","debtorId":1,"interest":0,"saleAmount":14000,"saleId":3,"singleSaleEntries":[{"amount":9000,"item":"DAP_50KG","price":900,"quantity":10,"saleEntry":null,"singleSaleId":4},{"amount":5000,"item":"UREA_50KG","price":500,"quantity":10,"saleEntry":null,"singleSaleId":5}],"totalAmount":14000}]
Please guide me.
The issue was with var saleEntries = $.parseJSON(item.singleSaleEntries);
After changing this statement to var saleEntries = item.singleSaleEntries;
everything works fine, the problem was that the debug point was set to next statement and because of error in this line, the control was never reaching there.

Categories

Resources