Need help with Javascript....I think - javascript

I'm trying to bypass going through a bunch of menus, to get to the data I want directly.
Here are the links I want to go to:
http://factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53053072904&tree_id=4001&context=dt&_lang=en&_ts=288363511701
factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53025981400&tree_id=4001&context=dt&_lang=en&_ts=288363511701
factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53067011620&tree_id=4001&context=dt&_lang=en&_ts=288363511701
Notice, if you pull that up right now, you simply see a GIF outline of the map, however there is no map data "behind" it.
However, if you go to: factfinder.census.gov/servlet/DTGeoSearchByListServlet?ds_name=DEC_2000_SF1_U&_lang=en&_ts=288392632118
Select Geographic Type: ..... ..... Census Tract
Select a State: Washington
Select a County: Pierce
Select one or more geographic areas: Census Tract 729.04
Hit "Map It"
The map will load perfectly. Also, until you close your browser, any of the other links will work perfectly. What I want to do, is be able to bypass these 5 steps, but obviously something is preventing this. Is there a feasible workaround? I have my own domain that I would be able to upload new Javascript or HTML files or whatever is needed.

Looking at the relevant code, there's only a few functions that are needed. The "Map it" button calls the mapit function with a string literal of '/servlet/MapItDrawServlet'.
function launchMapItServlet(mapItServlet) {
context = document.form1.context.value;
lang = "en";
url = mapItServlet + "?geo_id=" + geo + "&" + "tree_id=" + tree_id + "&context=" + context + "&_lang=" + lang;
url = getAFFWindowLocation(url, true);
windowCtr++;
window.open(url, "identify" + windowCtr, "menubar=yes,scrollbars=yes,resizable=yes,top=10,left=10,width=750,height=550");
}
function mapItMulti(servlet) {
if (numberOfSelections(document.forms["form1"].search_results) == 0 || numberOfSelections(document.forms["form1"].search_results) > 1) {
alert(ALERT_MSG1);
}
else if (canMapItMulti(document.forms["form1"].search_results)) {
index = document.forms["form1"].search_results.selectedIndex;
geo = document.forms["form1"].search_results.options[index].value;
tree_id = document.form1["tree_id"].value;
launchMapItServlet(servlet);
}
else {
alert(ALERT_MSG1);
}
}
function mapit(mapItServlet) {
geo = "";
mapItMulti(mapItServlet);
}
Notice the window.open function which will be the relevant information that you will want to use, especially the 'url' variable.

Related

Handling random number of links by using AJAX Jquery

I am new at AJAX and JQuery and trying to use them in the part of my website. Basically the website that I have, has this kind of design and currently it is functional (Sorry for my poor paint work :)
The items in the website are created by user. This means item number is not constant but can be fetched by db query.
Each item has a unique URL and currently when you click an item, all page is refreshing. I want to change the system to let the user have a chance to navigate quickly between these items by only chaning middle content area as shown above. However I also want to have a unique URL to each item. I mean if the item has a name like "stack overflow", I want the item to have a URL kind of dev.com/#stack-overflow or similar.
I don't mind about the "#" that may come from AJAX.
In similar topics I have seen people hold constant names for items. For instance
<a href="#ajax"> but my items are not constant.
WHAT I HAVE TRIED
Whats my idea is; while fetching all item's links, I'm holding links in $link variable and using it in <a href="#<?php echo $link; ?>">.
Inside $link it is not actual URL. it is for instance a name like "stack-overflow" as I ve given example above. Until this part there is no problem.
PROBLEM
In this topic a friend suggested this kind of code as an idea and I ve changed it for my purpose.
<script>
$(document).ready(function() {
var router = {
"<?php echo $link ?> ": "http://localhost/ajax_tut/link_process.php"
};
$(window).on("hashchange", function() {
var route = router[location.hash];
if (route === undefined) {
return;
} else {
$(".content-right").load("" + route + " #ortadaki_baslik");
}
});
});
</script>
I'm trying to post the value of $link to the link_process.php and at link_process.php I will get the value of $link and arrange neccessary page content to show.
The questions are;
- How should I change this code to do that?
- I couldnt see someone doing similar to take as an example solve this
issue. Is this the right way to solve this situation?
- Do you guys have a better solution or suggestion for my case?
Thanks in advance.
WHEN your server side AJAX call handler [PHP script - handling AJAX requests at server side] is constant and you are passing item_id/link as GET parameter...
For example:
localhost/ajax_tut/link_process.php?item_id=stack-overflow OR
localhost/ajax_tut/link_process.php?item_id=stack-exchange
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/link_process.php?item_id=";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route );
}
});
});
</script>
WHEN you are passing item_id/link as URL part and not parameter...
For example:
localhost/ajax_tut/stack-overflow.php OR
localhost/ajax_tut/stack-exchange.php
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route + ".php");
}
});
});
</script>
WHEN Your server side AJAX handler script url is not constant and varies for different items...
For example: localhost/ajax_tut/link_process.php?item_id=stack-overflow OR localhost/ajax_tut/fetch_item.php?item_id=stack-exchange OR localhost/ajax_tut/stack-exchange.php
Then I suggest to change PHP script which is generating item's links placed on left hand side.
<?php
foreach($links as $link){
// Make sure that you are populating route parameter correctly
echo '<a href="'.$link['item_id'].'" route="'.$link['full_ajax_handler_route_url_path'].'" >'.$link['title'].'</a>';
}
?>
Here is Javascript
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/"; //Base url or path
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
route = $('a [href="'+.slice(1)+'"]').attr('route'); //Fetching ajax URL
$(".content-right").load( ajax_handler + route ); //Here you need to design your url based on need
}
});
});
</script>

Code behind Content editor button for Experience editor button

Is it possible to use a code behind of a command used for ribbon button in content editor as a request for experience editor button? We want to stick to SPEAK and not make any changes to Sitecore.ExperienceEditor.config.
After creating new button in Experience editor, telling .js to call NewCommand request by
Sitecore.ExperienceEditor.PipelinesUtil.generateRequestProcessor("ExperienceEditor.NewCommand");
that was referenced in Sitecore.ExperienceEditor.Speak.Requests.config as
<request name="ExperienceEditor.NewCommand" type="Sitecore.Starterkit.customcode.MyCommand,MyProject"/>
nothing happens and logs say
ERROR Could not instantiate speak request object,
name:ExperienceEditor.NewCommand,
type:Sitecore.Starterkit.customcode.MyCommand,MyProject`
Do we have to import PipelineProcessorRequest as suggested by some tutorials or is there a way to use our existing code?
Have you seen this blog post on adding custom SPEAK command buttons to Sitecore 8 Experience Editor?
https://doc.sitecore.net/sitecore%20experience%20platform/the%20editing%20tools/customize%20the%20experience%20editor%20ribbon
Otherwise if that doesn't achieve what your looking for, it might be worth trying to standard SPEAK application way of triggering a button, In a SPEAK application you can call a JavaScript function from a button click using this code.
javascript:app.FunctionName();
In the core DB update the click field on your button to call JavaScript with the javascript: prefix. Does this allow you to trigger your JavaScript?
I was able to use my existing control using guidelines from:
http://jockstothecore.com/sitecore-8-ribbon-button-transfiguration/
Relevant pieces of the old command:
if (args.IsPostBack)
{
// act upon the dialog completion
if (args.Result == "yes")
{
Context.ClientPage.SendMessage(this, "item:load(...)");
}
}
else
{
// trigger the dialog
UrlString url = new UrlString(UIUtil.GetUri("control:CopyLanguage"));
url.Add("id", item.ID.ToString());
url.Add("lang", item.Language.ToString());
url.Add("ver", item.Version.ToString());
SheerResponse.ShowModalDialog(url.ToString(), true);
args.WaitForPostBack();
}
The redressed command:
define(["sitecore"], function (Sitecore) {
Sitecore.Commands.ScoreLanguageTools = {
canExecute: function (context) {
return true; // we will get back to this one
},
execute: function (context) {
var id = context.currentContext.itemId;
var lang = context.currentContext.language;
var ver = context.currentContext.version;
var path = "/sitecore/shell/default.aspx?xmlcontrol=CopyLanguage" +
"&id=" + id + "&lang=" + lang + "&ver=" + ver;
var features = "dialogHeight: 600px;dialogWidth: 500px;";
Sitecore.ExperienceEditor.Dialogs.showModalDialog(
path, '', features, null,
function (result) {
if (result) {
window.top.location.reload();
}
}
);
}
};
});

Basic Calling Function Troubleshooting

How do I get the function checkViewers(); to work properly? I believe I am calling it wrong within the JS document file and therefore the JS is not reading the function properly.
The current code:
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
The function is called towards the bottom of the remaining JS, after the JSON Data has been called.
Ideally, the JSON Data should be inputted into the HTML and the function should catch the number of viewers. This should then effect how the viewers are being shown in the HTML, upon how many viewers are being listed.
View the Plunker.
Making my comment an answer:
Ajax is Asynchronous. You ordered a pizza off the internet and you try to eat the pizza before it gets to your house. You have to wait for the pizza to show up before you eat it. AKA, you can not call your function until the data is there. So when you set the html, you call your function
xhr.onload = function() { //<--Function is called when the Pizza shows up at your door and the doorbell rings
... //removed a bunch of code....
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.html(newViewers); //You open up the pizza box
checkViewers(); //<--- MOVE IT HERE, The pizza is here!!!!
}
};
xhr.open('GET', 'data.json', true); //<-- You set up your pizza order
xhr.send(null); //<--You make the pizza purchase
//checkViewers(); <-- PIZZA IS NOT HERE!!!!

Speed up multiquery with Instagram api

I'm getting the images with the media/search endopoint passing a lat and lon like this
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
and then I'm gettin only the pics with a certain tag #instabeachpro,if the pic is not found I go trough the next set of pics adding the last pic created_time to the url with the max_timestamp parameter, here is the code I'm using
(function(){
var url,tags,menos,photos = new Array(),i=90;
function search(){
generateResource(tag;
$.getJSON(url, toScreen);
}
function init(){
bindEventHandlers();
}
function generateResource(){
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
return url;
}
function toScreen(){
var next_url=url+"&max_timestamp="+data.data[data.data.length - 1].created_time;
$.each(data.data, function(index, photo){
i--;
tags=photo.tags;
menos=jQuery.inArray( "instabeachpro", tags );
if(menos!=-1)
{
$('div#photos-wrap').append("<div id='"+i+"' ><a href='"+photo.link+"'><img src='"+photo.images.low_resolution.url+"'/></a></div><div><img class='second' src='"+photo.user.profile_picture+"'/></div>");
}
else{
i++;
}
});
if(next_url!=undefined+"&callback=?" && i>=0){
console.log(i);
pagination(next_url);
}
}
function pagination(url)
{
$.getJSON(url, toScreen);
}
Instagram.App = {
search: search,
init: init
};
function bindEventHandlers(){
$('body').on('click', '#loadObject', function(){
url=$(this).attr('data-next-url');
i=90;
if(url=='undefined')
{
alert("undefined");
}
else{
pagination(url);
return false;
}
});
}
}());
$(function(){
Instagram.App.init();
Instagram.App.search();
});
This works but it's extremely slow and I have no idea what to do to speed it up, because the api doesn't support searching like I want to do, and i need to get al the pcitures with a certain tag IN a certain location, I have been told a number of times this is the only way to do it, but there has to be a faster way.Thank you.
Your method is extremely inefficient, since the tag you are searching is not popular and very small percentage of people use it, so getting API around location and then filtering by tag is expensive on number of API calls.
Search the other way round, make API call for the tag and then check for location for that photo. Check this implementation: http://www.gramfeed.com/instagram/tags#instabeachpro
You can get the tag photos and maps it on Google Maps, scroll to load more photos and see that very few of the #instabeachpro photos are tagged with location

Bitly API - JavaScript function to open new window

I am using a script i found here to dynamically generate short link for my Tweet buttons and it works perfectly well, but the only thing i cant seem to do is create the link to open in either a new tab or preferably a popup window.
I have tried several variations of the window.location section of the script but so far I've had no luck. If anybody could point me in the right direct I'd be very grateful.
This is the script I am using...
<script>
var TweetThisLink = {
shorten: function(e) {
// this stops the click, which will later be handled in the response method
e.preventDefault();
// find the link starting at the second 'http://'
var url = this.href.substr(this.href.indexOf('http:', 5));
BitlyClient.shorten(url, 'TweetThisLink.response');
},
response: function(data) {
var bitly_link = null;
for (var r in data.results) {
bitly_link = data.results[r]['shortUrl'];
break;
}
var tweet_text = "Text for the Tweet goes here"
window.location = "http://twitter.com/home?status=" + encodeURIComponent(tweet_text + ' ' + bitly_link + " #Hashtag1 #Hashtag2");
}
}
jQuery('.tweetlink').bind('click', TweetThisLink.shorten);
</script>
Many thanks in advance :)
Normally you could just do window.open:
window.open("http://twitter.com/home?status=" + encodeURIComponent(tweet_text + ' ' + bitly_link + " #Hashtag1 #Hashtag2");
BUT, since you are doing an ajax call before this happens, chances are that this window popup will be blocked by the browser, since the window.open command is no longer associated with the click (browsers allow a certain time before a window.open command falls under non-initiated "popup").
A solution would be to first open the window on click (in your shorten function):
var win = window.open('about:blank');
And then redirect in your response function:
win.location = 'http://twitter.com/etc...';
Demo: http://jsbin.com/usovik/1
Perhaps you're looking for
window.open("http://example.com");

Categories