HTML read javascript and put result into a div - javascript

I'm new to HTML/javascript and I want to make something that displays Last.FM current playing songs, into a div on html, which displays it in text, I have a code that sends the current song through a chat on www.irccloud.com, and I was wondering If you could change it so that It could get received and put into a DIV on a page, the code is below:
and var r is the completed code, so how would I do something in the div that picks up the source as the link above and then grabs var r from it? If so, how would I do it??
I have tried the following code here
Sorry if I do not make sense.
(function () {
var e = "DeviousRunner";
window.lfmRecentTrack = function (t) {
var n = (new Array).concat(t.recenttracks.track)[0];
var album, spurl;
if (n.album["#text"]) {
album = " (from " + n.album["#text"] + ")";
} else {
album = "";
}
try {
var spotify = new XMLHttpRequest();
spotify.open("GET", "https://ws.spotify.com/search/1/track.json?q=" + encodeURIComponent(n.artist["#text"] + " - " + n.name), false);
spotify.send();
var spotresp = JSON.parse(spotify.responseText);
if (spotresp["tracks"].length > 0) {
//var urisplit = spotresp["tracks"][0]["href"].split(":");
//spurl = " https://open.spotify.com/" + urisplit[1] + "/" + urisplit[2];
spurl = spotresp["tracks"][0]["href"];
} else {
console.log("spotify: couldn't get url");
spurl = "";
}
} catch(e) {
console.log("spotify: " + e.message);
spurl = "";
}
var r = "is listening to " + n.name + " by " + n.artist["#text"] + " " + album + " (" + spurl + ")";
}
var n = document.createElement("script");
n.setAttribute("type", "text/javascript");
n.setAttribute("src", "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + e + "&api_key=dd5fb083b94a7196cf696b9d7d11bc63&limit=1&format=json&callback=window.lfmRecentTrack");
document.body.appendChild(n)
})();

I updated your FIDDLE,
by moving this:
var element = document.getElementById("rss");
element.innerHTML = r;
inside the function...
hope this is useful for you

Related

how to get form element in javascript

I will try work in javascript, I'm not getting form element data
function sendInfo(params) {
var p = event.target;
Message("Welcome " + p.fname.value + " " + p.lname.value);
}
function Message(m) {
document.getElementById("wrapper").innerHTML = m;
}
I am getting an error message when I will run the script
any suggestion.
look :
function sendInfo(params) {
var p = event.target.parentElement;
Message("Welcome " + p.fname.value + " " + p.lname.value);
}
function Message(m) {
document.getElementById("wrapper").innerHTML = m;
}
try this if possible

Javascript object set to another object is undefined

For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}

Resolve 'Parsing Error: Please check your selector. (line XX)' Javascript/AWQL

First off, let me say that I am not a developer, nor do I really code beyond basic HTML. So I appreciate your patience. :)
I'm working with a script that is for AdWords, but I believe it's more or less written in Javascript. (I've included the script below.)
Basically, I'm receiving the error message 'Parsing Error: Please check your selector. (line XX)' when I preview the script.
I've searched all around for hours and have yet to find a solution.
I think it may be that a query being returned contains either a single or double quote, and may be messing up the code? Though I can't actually prove that.
Also, yes, I was sure to update lines 17-21 with the correct details.
Any help would be much appreciated!
Thanks!
John
/*
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "example#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query); //THIS IS LINE 103 WITH THE ERROR
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
The area between SELECT and FROM is the selector. You're not selecting any fields with that query. That's happening because the headerNames array is empty. Verify the value of REPORT_SHEET_NAME

Using casperjs and phantomjs to scrape multiple pages

I'm trying to scrape a number of pages that have a standard format. I've been able to use Phantomjs to successfully scrape a single page, but when I try to iterate over multiple ones, the asynchronous processing makes things hang up. What's the proper way to tell Casper/Phantom to wait?
var page = require('webpage').create();
var fs = require('fs');
page.onConsoleMessage = function(msg) {
phantom.outputEncoding = "utf-8";
console.log(msg);
};
// this overwrites the previous output file
f = fs.open("lat_long.txt", "w");
f.write("--");
f.close();
// this is the unique identifier for the locations. For now, I just have three datapoints
var EPAID = ["KYD980501076","ME8170022018", "MEN000103584"];
/// this code will be used to loop through the different locations. For now, set to look at only one.
for (q= 0; q < 1; q++) {
var processing = false;
//we construct the target url
var url = "http://iaspub.epa.gov/enviro/efsystemquery.cerclis?fac_search=site_epa_id&fac_value=" + EPAID[0] + "&fac_search_type=Beginning+With&postal_code=&location_address=&add_search_type=Beginning+With&city_name=&county_name=&state_code=&program_search=1&report=2&page_no=1&output_sql_switch=TRUE&database_type=CERCLIS" ;
page.open(url);
page.onLoadFinished = function(status) {
if ( status === "success" ) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
var str = page.evaluate(function() {
$value = [];
$Object = $(".result tr");
for (i =0 ; i < 10; i++) {
$value.push($Object.find('td').html(),$Object.find('td').next().next().html() );
$Object = $Object.next();
}
$string = "{ EPAID: "+ $value[0] + ", " +
"Name: "+ $value[1] + ", " +
"City: "+ $value[4] + ", " +
"State: "+ $value[6] + ", " +
"ZipCode: "+ $value[8] + ", " +
"Latitude: "+ $value[14] + ", " +
"Longitude: "+ $value[16] + " }" ;
return $string;
});
f = fs.open("lat_long.txt", "a");
f.write(str);
f.close();
processing = true;
console.log("writing to file");
phantom.exit();
});
}
// right here it should delay until the previous page is completed
// while (!processing) {
// setTimeout(function(){ console.log("waiting....");},1000);
// }
};
}
console.log("finished all pages");
If you switched to using casperJS, it is as simple as changing your page.open() into page.thenOpen(). (This CasperJS - How to open up all links in an array of links question looks very similar to yours?)
If you wanted to stick with PhantomJS you need to start the next page load in the onSuccess callback of the previous load. This is tedious, and needs care to avoid large memory usage. (I did it once or twice, but now simply use CasperJS.)
An alternative approach is to create the page object inside the loop. However that is not quite answering your question, as then they will run in parallel. But you could use setTimeout to stagger each once to avoid a burst of activity if you have hundreds of URLs!
Here is the code that ultimately works (using the timeout approach since I wasn't able to get the success callback to work better).
With casperjs installed, I named this file "process.js" and was able to run it from the command line as "casperjs process.js"
var page = require('webpage').create();
var fs = require('fs');
page.onConsoleMessage = function(msg) {
phantom.outputEncoding = "utf-8";
console.log(msg);
};
// this overwrites the previous output f
// this is the unique identifier for the locations.
var EPAID = ["NED981713837",... , "FLD049985302", "NJD986643153"];
f = fs.open("lat_long.txt", "w");
f.write("-<>-");
f.close();
var count = 0;
var target = 1400;
var written = [];
function yourFunction(){
if (count < target) {
process(count);
count++;
setTimeout(yourFunction, 5000);
} else {
console.log("exiting");
phantom.exit();
return;
}
}
function process(counter){
var processing = false;
console.log("Beginning record #" + counter);
//we construct the target url
var url = "http://iaspub.epa.gov/enviro/efsystemquery.cerclis?fac_search=site_epa_id&fac_value=" + EPAID[counter] + "&fac_search_type=Beginning+With&postal_code=&location_address=&add_search_type=Beginning+With&city_name=&county_name=&state_code=&program_search=1&report=2&page_no=1&output_sql_switch=TRUE&database_type=CERCLIS" ;
page.open(url);
page.onLoadFinished = function(status) {
if ( status === "success" ) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
var str = page.evaluate(function() {
$value = [];
$Object = $(".result tr");
for (i =0 ; i < 10; i++) {
$value.push($Object.find('td').html(),$Object.find('td').next().next().html() );
$Object = $Object.next();
}
$string = "{ \"EPAID\": \""+ $value[0] + "\", " +
"\"Name\": \""+ $value[1] + "\", " +
"\"City\": \""+ $value[4] + "\", " +
"\"State\": \""+ $value[6] + "\", " +
"\"ZipCode\": \""+ $value[8] + "\", " +
"\"Latitude\": "+ $value[14] + ", " +
"\"Longitude\": "+ $value[16] + " }," ;
return $string;
});
if (written[counter] === undefined) {
f = fs.open("lat_long.txt", "a");
f.write(str);
f.close();
written[counter] = true;
console.log("Writing to file #"+ counter);
}
});
}
};
}
console.log("Start...");
yourFunction();

Turning dynamic div content into a link

I am working on Longtail's JW Player and I am stuck with some basic stuff. I don't know what it is called in the programming language thats why I will write it step by step:
There is a javascript code to show title and description of the playing video, as shown below
<script type="text/javascript">
var player = null;
var playlist = null;
function playerReady(obj)
{
player = gid(obj.id);
displayFirstItem();
};
function displayFirstItem()
{
try
{
playlist = player.getPlaylist();
}
catch(e)
{
setTimeout("displayFirstItem()", 100);
}
player.addControllerListener('ITEM', 'itemMonitor');
itemMonitor({index:player.getConfig()['item']});
};
function itemMonitor(obj)
{
gid('nowplaying').innerHTML = 'Playing: ' + playlist[obj.index]['title'] + '';
gid('author').innerHTML = '<p>Author: ' + playlist[obj.index]['author'] + '</p>';
gid('description').innerHTML = '<p>Description: ' + playlist[obj.index]['description'] + '</p>';
};
function gid(name)
{
return document.getElementById(name);
};
</script>
Code returns the video title in to a div:
<div id="nowplaying"></div>
What I want is to display video title also in the tweet this button:
href="http://twitter.com/home?status=SONG TITLE"
How can I do this? Best regards
Edit the itemMonitor() function:
function itemMonitor(obj)
{
gid('nowplaying').innerHTML = 'Playing: ' + playlist[obj.index]['title'] + '';
gid('author').innerHTML = '<p>Author: ' + playlist[obj.index]['author'] + '</p>';
gid('description').innerHTML = '<p>Description: ' + playlist[obj.index]['description'] + '</p>';
gid('tweetLink').href = 'http://twitter.com/home?status=' + encodeURIComponent(playlist[obj.index]['title']);
};
This requires that a link be present in the document with id="tweetLink", this doesn't alter the link's text, however, if you want to update the link's text:
function itemMonitor(obj)
{
gid('nowplaying').innerHTML = 'Playing: ' + playlist[obj.index]['title'] + '';
gid('author').innerHTML = '<p>Author: ' + playlist[obj.index]['author'] + '</p>';
gid('description').innerHTML = '<p>Description: ' + playlist[obj.index]['description'] + '</p>';
gid('tweetLink').href = 'http://twitter.com/home?status=' + encodeURIComponent(playlist[obj.index]['title']);
gid('tweetLink').innerHTML = 'Tweet this song: ' + playlist[obj.index]['title'] + '.';
};

Categories

Resources