I want to read multiple RSS feeds using jQuery.
I'm trying to write a flexible function that will just take the RSS URL and it will output only its TITLE AND IMAGE how to do that for multiple RSS URLs?
The easiest way would be to use the Google AJAX Feed API. They have a really simple example, which suits what you want nicely:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
<div id="feed"></div>
Of course, you can mix jQuery with the API instead of using native DOM calls.
Have you seen this JQuery plug-in: http://plugins.jquery.com/project/jFeed
A little late to the party but I actually did something similar to this using the deviantART gallery feed and displaying the latest thumbnail. I wrapped it up into a couple of functions for easy use:
function keratin_callback(elem, data)
{
if (!data
|| !data.entries
|| data.entries.length < 1
|| !data.entries[0].mediaGroups
|| data.entries[0].mediaGroups.length < 1
|| !data.entries[0].mediaGroups[0].contents
|| data.entries[0].mediaGroups[0].contents.length < 1
|| !data.entries[0].mediaGroups[0].contents[0].thumbnails
|| data.entries[0].mediaGroups[0].contents[0].thumbnails.length < 1) {
$("<span>Data returned from feed not in expected format.</span>").appendTo(elem);
return;
}
var entry = data.entries[0];
$("<img>").attr("src", entry.mediaGroups[0].contents[0].thumbnails[0].url)
.appendTo(elem)
.wrap("");
}
function keratin(elem, url)
{
//keratin written by adam james naylor - www.adamjamesnaylor.com
if (!elem || elem.length < 1) return; //no element found
$.ajax({
//you could use document.location.protocol on the below line if your site uses HTTPS
url: 'http:' + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url + '&cache=' + Date.UTC()),
dataType: 'json',
success: function(data) {
if (!data || !data.responseData) {
return keratin_callback(elem, null);
}
return keratin_callback(elem, data.responseData.feed);
}
});
}
$(document).ready(function() {
keratin($('#da_gallery'), 'http://backend.deviantart.com/rss.xml?q=gallery%3Adeusuk%2F28671222&type=deviation')
});
Full details here: http://www.adamjamesnaylor.com/2012/11/05/Keratin-DeviantART-Latest-Deviation-Widget.aspx
Related
I am trying to get the URL for all the photos of a facebook page.
How do I get the 'source' URL for this query and JSON structure:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=19292868552%3Ffields%3Dalbums.fields(photos.fields(source))&version=v2.1
I am using this success callback from a JSONP request:
function(response) {
for (i = 0; i < **???response.albums.data.length???**; i++) {
alert(**???response.albums.data[i].photos.data[i].source???**)
}
}
Can you help me find the right structure for the parts with the astericks? Because it has two [i]'s i think i'm getting confused..
You need to make sure that you have this in your head:
<script type='text/javascript' src='//connect.facebook.net/en_US/sdk.js'></script>
<script type='text/javascript' src='workFromPage.js'></script>
Now on workFromPage.js
var pre = onload;
onload = function(){
if(pre)pre();
if(!FB)reload();
var photoURLs = [];
// change userId
// make sure you test for login and wrap around code below, if needed
FB.api('/userId/albums', function(resp){
if(resp && !resp.error){
for(var i in resp){
FB.api('/'+resp[i].id+'/photos', function(r){
if(r && !r.error){
for(var n in r){
photoURLs.push(r[n].source);
}
// access photoURLs here
}
}
}
}
}
}
I'm moderatley new to ASP.NET and very new to Javascript. I'm writing a ASP.NET UserControl. I had the following:
<head>
<title>Select Asset </title>
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CheckThenCloseActiveToolTip(supplierID) {
var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
var selectedItems = radGrid.get_masterTableView().get_selectedItems()
if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
else {
DoPartialPostBack('selectasset', selectedItems[0]._dataItem.Id);
CloseActiveToolTip();
}
}
function PopulateRooms(e) {
var idx = e.selectedIndex;
if (idx > -1) {
var dcId = JSON.stringify({ dataCenterId: e.options[idx].value });
var pageUrl = '/WebService/AVWebService.asmx';
$.ajax({
url: pageUrl + '/GetRooms',
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: dcId,
success: OnRoomsReceived,
error: OnErrorCall
});
}
else {
var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
ddlRooms.disabled = true;
$('#ddlRooms').empty();
ddlRooms.options[0] = new Option('', '-1');
getAssets(0);
}
}
function OnRoomsReceived(result) {
var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
if (result.d.length > 0) {
ddlRooms.disabled = false;
$('#ddlRooms').empty();
ddlRooms.options[0] = new Option('', '-1');
for (var i = 0; i < result.d.length; i++) {
ddlRooms.options[i + 1] = new Option(result.d[i].Name, result.d[i].Id);
}
}
if (result.d.length = 1)
ddlRooms.selectedIndex = 1;
getAssets(0);
}
function resetGridData() {
getAssets(0);
}
function getAssets(startAt) {
var cpId = document.getElementById('hfldCompanyId').value;
var pageUrl = '/WebService/AVWebService.asmx';
var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
var ddldc = document.getElementById('MainContent_SelectAssetGrid1_ddlDataCenter');
var dcIdx = ddldc.selectedIndex;
var dcId = '';
if (dcIdx > -1)
dcId = ddldc.options[dcIdx].value;
var ddlrm = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
var rmIdx = ddlrm.selectedIndex;
var rmId = '';
if (rmIdx > -1)
rmId = ddlrm.options[rmIdx].value;
var ddlStatuses = $find('ctl00_MainContent_SelectAssetGrid1_ddlStatuses';
var rbgAssetClass = document.getElementById('MainContent_SelectAssetGrid1_rbgAssetClass');
var ac = 0;
var rbgInputs = rbgAssetClass.getElementsByTagName('input');
for (var i = 0; i < rbgInputs.length; i++) {
if (rbgInputs[i].checked) {
ac = i;
}
}
var filters = [];
var fbs = document.getElementsByClassName('rgFilterBox');
for (var i = 0; i < fbs.length; i++)
if (fbs[i].value != '')
filters[filters.length] = { field: fbs[i].alt, value: fbs[i].value };
var params = JSON.stringify({ companyId: cpId,
startIndex: startAt,
maximumRows: tableView.get_pageSize(),
filterExpressions: filters,
dataCenterId: ddldc.options[ddldc.selectedIndex].value,
roomId: rmId,
Statuses: ddlStatuses._checkedIndices,
assetClass: ac
});
$.ajax({
url: pageUrl + '/GetSelectAssetData',
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: params,
success: updateGrid,
error: OnErrorCall
});
}
function updateGrid(result) {
var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
tableView.set_dataSource(result.d.gridData);
tableView.dataBind();
tableView.set_virtualItemCount(result.d.count);
}
function gridAssetList_Command(sender, args) {
args.set_cancel(true);
var pageSize = sender.get_masterTableView().get_pageSize();
var currentPageIndex = sender.get_masterTableView().get_currentPageIndex();
if (args.get_commandName() == 'Filter')
currentPageIndex = 0;
getAssets(pageSize * currentPageIndex);
}
function gridAssetList_Created(sender, args) {
var fbtns = document.getElementsByClassName('rgFilter');
for (var i = 0; i < fbtns.length; i++)
fbtns[i].style.visibility = 'hidden';
var fbs = document.getElementsByClassName('rgFilterBox');
for (var i = 0; i < fbs.length; i++)
fbs[i].onkeypress = applyFilter;
}
function applyFilter(args) {
if (args.keyCode == 13)
resetGridData();
}
</script>
This works most of the time, but if I'm loading the UserControl using Page.LoadControl(), it didn't always load the scripts correctly. For a couple of reasons (maybe poor ones) I thought I'd move the scripts to an external file.
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../Scripts/SelectAsset.js" type="text/javascript"></script>
There's no additional code or setup in the .js file, just
function CheckThenCloseActiveToolTip(supplierID) {
var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
var selectedItems = radGrid.get_masterTableView().get_selectedItems()
if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
...
But now I get a RunTime error that "function gridAssetList_Command" us undefined. That function is bound to a grid's OnCommand event in the page .
When I examine the page in Firebug, it doesn't list my .js file in the list of script files.
I'm loading my scripts in the . I didn't change them, just moved them. What am I missing?
MORE INFO:
It appears to be using different ClientIds when adding the functions to the controls. The error I'm getting drops be in a dynamic resource with the following:
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadGrid, {"ClientID":"ctl00_MainContent_ctl03_gridAssetList","ClientSettings": ...
I'm going to try changing referenes to getElementByClass()
The best way to add javascript reference on asp.net web form is using ScriptManager on parent element or parent page such as a Master Page, And use ScriptManagerProxy on content pages and user controls.
Try use ScriptManager or combination of both to resolve your problem. Also use root application alias (~) for refer to file ex. src="~/Scripts/jquery-1.9.1.min.js"
So for simple way change your script reference to become:
<asp:ScriptManager ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery-1.9.1.min.js" />
<asp:ScriptReference Path="~/Scripts/SelectAsset.js" />
</Scripts>
</asp:ScriptManager>
Update:
use for example:
$('table[id*="gridAssetList"]') for table with id = ctl00_gridAssetList_xx
$('input[id*="inputTxt"]') for input with id = ctl100_inputTxt
etc
to call html tag that rendered by asp.net component using jquery selector.
hi steve i think its shows error due to script source path please check that first then to verify the script loaded or not try this below code
if(typeof(yourfunction_name=='function')
{
// this code will make sure that the function is present in the page
//function exits do your functionality.
}else
{
alert('Script not loaded');
}
I have created the following JavaScript function to load images of a vehicle, or load the alternate image if it is not available. The problem is that this page is 1kb, meanwhile it has to load the entire jquery library at 85+kb just for this one function. So my question is, is there some way to accomplish the same without having to load the jQuery library?
function GetImages() {
var Query = location.search;
//If query exists
if ((Query != "") && (Query != "?")){
var chunks = Query.split("=");
//If passed the right parameter
if (chunks[0] == "?unit") {
var Unit = chunks[1];
for (var i=1; i<11; i++) {
var unitimageURL = "/pics/"+Unit+"-"+i+".png";
$.ajax({
type: 'HEAD',
url: unitimageURL,
async: false,
success: function() {
$('.pictures').append("<img src="+unitimageURL+" width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
},
error: function() {
$('.pictures').append("<img src=nopic2.png width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
}
});
}
}
}
else {
alert("No query");
}
}
Yes, there is a way - the good old var oRequest = new XMLHttpRequest(); way!
Don't forget to to set all the needed callbacks, check response statuses and everything will be fine.
To create a HEAD request, just specify "HEAD" as parameter to .open() method.
You will also need document.createElement() to append the results to your page (or you may use .innerHTML property as well.
Also, documentation like this http://www.tutorialspoint.com/ajax/what_is_xmlhttprequest.htm may be handy.
Getting some odd behavior from google custom search that I can't seem to suss out. Maybe someone has a clue.
I'm putting together a Magento site, which has its own internal search engine - but is limited to product only. I want to implement google custom search results on the search results page as well. I figure I should be able to simply execute a search based on the query vars in the url (to return all the non-product content), as such:
<section style="min-height:600px">
<div style="background-color:#DFDFDF; min-height:800px; width:100%;">
<div id="cse">Loading</div>
</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready( function(){
console.log('search initiated');
var t = window.setTimeout( function(){ customSearch(); }, 5000 );
});
function customSearch(){
var q = urlParams()['q'];
if (q != undefined && q != ""){
console.log('q : %s', q); //outputs successfully
google.load('search', '1');
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl(MY CUSTOM ID KEY);
var cseDrawOptions = new google.search.DrawOptions();
cseDrawOptions.setAutoComplete(true); //unknown if this is required...
customSearchControl.draw('cse',cseDrawOptions);
customSearchControl.execute(q);
}, true);
}
}
function urlParams(){
var vars = [];
var hash;
var index = window.location.href.indexOf('?');
if( index != -1 ){
var hashes = window.location.href.slice(index + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1].replace(/\+/g, " ");
}
}
return vars;
}
//]>
</script>
</section>
I'll note that I've pulled all other content out of the logic (but its implementation in magento is identical).
So the behavior goes like this: page loads fine (I'm delaying the google search with a timeout for testing purposes ). Assuming there is a query var in the url the console traces out as expected. Then the page just gets wiped out, with no content back from google. "Wiped out"... meaning all elements on teh page disappear, or are getting overwritten by a new page that google loads. As if the search control isn't creating an iframe - its just replacing the page with a <body>-less html page.
I've ready a number of articles on the subject, and gone over the API - this code looks like it should work. But clearly isn't.
What am I missing?
Cheers -
UPDATE
Continued messing around with this has revealed that for whatever reason :
google.load('search', '1');
google.google.setOnLoadCallback( console.log('loaded') )
Was the cause of the replaced page issue. The responded page, however contained links to the search module that google is hosting. And if I manually linked those files (forgoing a google.load) then I could run a search as expected:
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="http://www.google.com/uds/?file=search&v=1" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
... search logic
Then I found an alternate syntax on the google developers page that seemed to work as expected:
$(document).ready( function(){
google.load("search", "1", {"callback" : customSearch});
});
function customSearch(){
var q = urlParams()['q'];
if (q != undefined && q != ""){
var cseControl = new google.search.CustomSearchControl('MY CUSTOM KEY');
var cseDrawOptions = new google.search.DrawOptions();
cseDrawOptions.enableSearchResultsOnly()
cseControl.draw('cse', cseDrawOptions);
cseControl.execute(q);
}
}
Which works as expected. Only real problem at this point is the host of
Unsafe JavaScript attempt to access frame with URL http://mydomain from frame with URL http://www.google/cse?...
That now gets thrown.
I don't know how the two different versions of load syntax changes anything... but it seemed to of. Whatever the case, I'm unclear as to how to resolve these cross domain errors.
Thoughts would be great.
Nothin huh?
Well - I've basically worked out a good solution, using an alternate method that I think will be more flexible in the long run. Using googles RESTful API and simple jquery .ajax call, I can obtain good, controllable results with no cross-domain errors:
<div id="cse">Loading</div>
<script>
//https://developers.google.com/custom-search/v1/getting_started
//https://developers.google.com/custom-search/v1/using_rest#query-params
//https://developers.google.com/custom-search/v1/cse/list
var _url = "https://www.googleapis.com/customsearch/v1";
var _key = 'AIzaSy... your api key here';
var _cx = '001809... your engine id';
var _q = urlParams()['q']; //query param
jQuery(document).ready(function() {
$j.ajax({
url : _url,
type : 'GET',
dataType : 'jsonp',
data :{
key : _key,
cx : _cx,
q :_q
},
success : function(data, textStatus, jqXHR){ responseHandler(data); },
error : function(jqXHR, textStatus, errorThrown){ console.log('error: %s'), errorThrown},
beforeSend : function(){ console.log('sending request')},
crossDomain : true
});
});
function responseHandler( response, status) {
console.log(response);
var cse = $j('#cse'); // render vars as needed...
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
cse.append( "<br>" + item.htmlTitle);
}
}
function urlParams(){
var vars = [];
var hash;
var index = window.location.href.indexOf('?');
if( index != -1 ){
var hashes = window.location.href.slice(index + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
}
return vars;
}
</script>
And you can too;D
Cheers
I have a script that specifices that a certain element does not be shown when on a specific page. Below is the code I used:
<script type="text/javascript">
function callOnPageLoad()
{
var url = window.location.href;
if(url == "http://www.exampledomain.com")
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
However I need to put a few more url's in the if statement, what is the right way of doing this?
Many thanks
I preffer to generate associative array and then check if string is set. It can be obtained from AJAX, from different script etc. and isn't hradcoded into if
<script type="text/javascript">
var urlArray = { "http://www.exampledomain.com" : true, "http://www.exampledomain.com/foobar.html" : true };
function callOnPageLoad()
{
var url = window.location.href;
if( urlArray[url] )
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
if(url == "http://www.exampledomain.com" || url == "http://www.anotherdomain.com")
{
}
Add more conditions in the if block:
<script type="text/javascript">
function callOnPageLoad()
{
var url = window.location.href;
if(url == "http://www.exampledomain.com" || url == "anotherurl" || url == "andanother")
{
document.getElementById('rolex').style.display = 'none';
}
}
</script>
have an array of urls and iterate
function callOnPageLoad()
{
var urls = [
"http://www.exampledomain.com",
"http://www.exampledomain2.com"
];
var url = window.location.href;
for ( var i=0; i < urls.length; i++ ) {
if(url == urls[i])
{
document.getElementById('rolex').style.display = 'none';
break;
}
}
}
you can create an array of those urls and run for loop thought them, this will be more dynamic approach to your problem.
using long if statements is not advisible because you can loose a character here or a bit of logic there
If your urls point to external urls or match other patterns that you can distinguish them from other urls you can use it without an array.
function callOnPageLoad(type)
{
var url = window.location.href;
var urls=new array("http://www.exampledomain1com","http://www.exampledomain2.com");
if(url in urls){
document.getElementById('rolex').style.display = 'none';
}
}
if(url == "http://www.exampledomain.com" || url =="http://www.url2.com" || url == "http://www.url3.com") and so forth ... ?