HI,
I am nearly there I think but am struggling to put the final bits in place.
I am trying to look up the the subdomain of a number of different envoronments and pass the subdomain as a variable to prefix a url called via an onclick event. This is all delivered through an xsl transformation.
I am just getting the domain passed to the link at present. Any tips on how to make this work or write the code in a better way greatly appreciated.
<xsl:text disable-output-escaping="yes">
<![CDATA[
<script type="text/javascript">
function enironment()
{
if (window.location.host.toLowerCase() === 'www.mydomain.com') {
SsoServer = "https://sso.mydomain.com";
}
else{
var sub_domain = window.location.split('.')[0].split('//')[1];
SsoServer = "https://" + sub_domain + "sso.mydomain.com";
}
top.location.replace(SsoServer);
}
</script>]]>
</xsl:text>
<a href="#" onClick="javascript:enironment()" title="Sign in">Sign
in</a>
Might be because you have three equals signs instead of two here:
if (window.location.host.toLowerCase() === 'www.mydomain.com') {
Should be:
if (window.location.host.toLowerCase() == 'www.mydomain.com') {
Related
I want to add a thumbnail picture to a book's details, derived from the google books api, on the webpage. The code below will place the source code (api) for the appropriate book, first into the text field bookCover and then into the var copyPic, and then it should be copied into imgDisp, but it doesn’t. I can see that bookCover holds the right text, and have checked that copyPic holds the correct content.
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
Does anyone know why not? Or can I put the api details directly into imgDisp (can’t find such code syntax anywhere on the net)? Everything else is working fine. If I put a src in directly, then it works e.g.
document.getElementById("imgDisp").src = “http://.....api”
but not with a variable.
Without more info - eg, I can't see where the getJSON() function ends or what the URL's are, I can't see what the issue may be (except, perhaps, as in my last comment).
I idea seems ok, as I can replicate it (in a cut-down version of course):
function copyImageSource() {
let d = document.getElementById("bookCover").innerHTML;
document.getElementById("imgDisp").src = d;
}
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div>
<img id="imgDisp" src="">
I assume that this is the sort of thing you are trying to achieve?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
Version using jquery:
function copyImageSource() {
let d = $("#bookCover");
d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api");
let dCopy = d.html().replace(/&/g, "&");
$("#imgDisp").attr("src", dCopy);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover"></div>
<img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>
If you have jQuery you can easily do the following:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');
I am trying to load 2 scripts (or more) on one page and Only the 1st one is working. I do not have access to edit the javascript so I cannot make changes to it.
Here is the code:
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269"></script>
<noscript></noscript>
</div>
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175270"></script>
<noscript></noscript>
</div>
When I run the page, the 1st one loads fine but the second one does not. Any help is greatly appreciated.
Jsfiddle links:
Not working: http://jsfiddle.net/6E6ZC/
Working seperately 1: http://jsfiddle.net/5LZ8d/
Working seperately 2: http://jsfiddle.net/SQ778/
DO NOT REMOVE CACHE.
What is happening is that the browser thinks it is being asked to retrieve the same file on each request.
I had the same issue and here is how to resolve it.
Add one more querystring paramater like I have. I added the '&t='+ new Date().getTime()
'/api/drawings?a=e&f=img&id=' + eID + '&t=' + new Date().getTime()
Will work like a champ!
Here is a way to dynamically add the scripts to the page, and this is a FOR SURE WILL WORK WAY.
<script type="text/javascript">
setTimeout(function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script');
script1.setAttribute('type', 'text/javascript');
script1.setAttribute('id', 'script1');
script1.setAttribute('src', 'http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269&t=' + new Date().getTime());
script1.setAttribute('type', 'text/javascript');
script1.setAttribute('id', 'script2');
script1.setAttribute('src', 'http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269&t=' + new Date().getTime());
document.getElementsByTagName("head")[0].appendChild(script1);
document.getElementsByTagName("head")[0].appendChild(script2);
},500);
</script>
**With the script above you do not have to add the scripts statically. Just let the script that I've provided run.
This is all assuming that you're not attempting to load two JS files with the same exact script in each file. If your trying to continually check for changes you only need one file and an interval. "setInterval(function(){//this would be something totally different and a lot more work})"
You may have a caching problem. Try setting headers on the JavaScript so that it doesn't allow browser caching.
There is no caching problem and both scripts load correctly with a http 200 status message. When used separately, they produce results but when used together the 2nd one doesn't produce any result.
This could be happening as 2nd script expects something in the page where it can put its contents, but it doesn't find there s it was removed by 1st script. This looks to me as the most probable cause.
Example:
http://jsfiddle.net/6E6ZC/
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269"></script>
<noscript></noscript>
</div>
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175270"></script>
<noscript></noscript>
</div>
Okay, I feel bound to answer this one after seeing so many wrong turns.
Cache or not is a non-issue. Even if the browser does cache the request (and it most likely will, since the URLs are exactly the same), it all depends on what the loaded code is supposed to do.
Unless the code changes the name of its functions and/or variables on the fly or does other very smart things, including basically the same code a second time will very likely overwrite the first copy, thus doing nothing more than if the file had been included only once.
I would be very surprised if the guys at http://tickettransaction.com did design an interface relying on the user adding some random junk at the tail of the URL to allow a second execution of the very same request result on the same page.
Would they have wanted to support such an usage, they would simply have added a cache-control: no-cache or equivalent directive in their response headers.
But after all, I've seen weirdest things in my programmer's life.
Maybe the guy at tickettransaction.com was badly hungover the day he coded that or something?
To get rid of this cache false problem, simply open your dev tools and watch the network traffic. You will most likely see the request being fetched twice from the cache (or once from the server and once from the cache if you hit Ctrl+F5).
If you really want to have your request fetched twice from the server, simply disable the cache, and make sure you get a full server transfer twice.
Having jumped through all these hoops, you will very likely witness the same result, namely the second response code overwriting the first.
Last update.
Just to get rid of this caching non-issue, I added a variable parameter in the URL.
I used the dev tools to make sure the browser was NOT caching the second request.
Cache being dealt with once and for all, I did have a look at the code of this mysterious script:
document.write('<!--MA-WS-C23-->');
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/jquery_tn.js"></' + 'script>');
document.write('');
var TN_ticketResults = null;
function TN_populateTicketData(data) {
TN_ticketResults = data;
if(typeof TN_tryCreateTicketTable == "function")
TN_tryCreateTicketTable();
}
(function() {
var cysct = document.createElement("script");
cysct.type = "text/javascript";
cysct.src= '//tickets.tickettransaction.com/Tickets/ByEvent/?' +
'eventId=2175270&websiteConfigId=669&sort=retail&callback=TN_populateTicketData';
cysct.async = true;
var pnode = document.getElementsByTagName('script')[0];
pnode.parentNode.insertBefore(cysct, pnode);
})();
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/swfobject_tn.js"></' + 'script>');
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/maincontrol_tnservice_tn.js" ></' + 'script>');
document.write('');
// ppcsrc
var cookie_tn_ppc_src ='';
var tn_cookies = '; '+document.cookie + ';';
var cookie_ppc_src_start =tn_cookies.indexOf('; tn_ppc_src=') + 13;
if(cookie_ppc_src_start != 12)
cookie_tn_ppc_src = '&ppcsrc=' + tn_cookies.substring(cookie_ppc_src_start, tn_cookies.indexOf(';', cookie_ppc_src_start));
var acct_start =tn_cookies.indexOf('; rcaid=') + 8;
if(acct_start != 7)
cookie_tn_ppc_src +='&rcaid=' + tn_cookies.substring(acct_start, tn_cookies.indexOf(';', acct_start));
//map css suppliment
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute('href', 'http://seatics.tickettransaction.com/tnservice_map_suppliment_tn.css');
document.getElementsByTagName('head')[0].appendChild(fileref);
//maps
var webParms = {
swfMapURL : "http://seatics.tickettransaction.com/FenwayPark_Baseball_2013-04-24_2013-04-24_1120_tn.swf",
staticMapURL : "http://seatics.tickettransaction.com/FenwayPark_Baseball_2013-04-24_2013-04-24_1120_tn.gif",
mapShellURL : 'http://seatics.tickettransaction.com/mapshell_tn.swf'
};
webParms.vfsFilterAnimate = 'vertical-list';
webParms.vfsImageAnimate = 'vertical-list';
webParms.vfsEnable = 'selected-hover';
var TN_docFinishedLoading = false;
window.onload = function() {
ssc.EH.buyTickets = function(buyObj) {
var purchaseUrl = 'https://tickettransaction2.com/Checkout.aspx?wcid=669&e=' + escape(buyObj.tgSds) + cookie_tn_ppc_src + '&treq=' + buyObj.buyQty + '&SessionId=' + makeGuid();
if (typeof AppendToPurchaseUrl == "function") {
try {
purchaseUrl = AppendToPurchaseUrl(purchaseUrl);
} catch(e) {
}
}
if (typeof PopupCheckOut == "function" && PopupCheckOut())
window.open(purchaseUrl, '_blank', 'location=no,scrollbars=yes,resizable=yes,menubar=yes,toolbar=yes');
else
location.href = purchaseUrl;
};
TN_docFinishedLoading = true;
TN_tryCreateTicketTable();
};
var TN_onEmptyEvent = TN_onEmptyEvent || function(title) {
$("#tn_loading").css("display", "none");
$("#ssc_listAndMapDiv").css("display", "none");
$("#tn_tblNoResults").css("display", "");
};
function TN_tryCreateTicketTable() {
if (TN_docFinishedLoading && TN_ticketResults) {
if (TN_ticketResults.TicketsAvailable) {
$("#tn_loading").css("display", "none");
ssc.loadTgList(TN_ticketResults.TicketData, webParms);
} else {
TN_onEmptyEvent('Boston+Red+Sox+vs.+Tampa+Bay+Rays+on+Tue%2c+Apr+29+2014');
}
}
}
function makeGuid() {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var guidLength = 5;
var guid = '';
for (var i = 0; i < guidLength; i++) {
var rnum = Math.floor(Math.random() * chars.length);
guid += chars.substring(rnum, rnum + 1);
}
return guid;
}
function GoToOtherGame(eventid) {
if (eventid != '')
document.location = 'ResultsTicket.aspx?evtid=' + eventid;
}
document.write('<table class="tn_results_header"> <tr class="tn_results_header_title"> <td class="tn_results_header_title"> Boston Red Sox vs. Tampa Bay Rays </td> <td class="tn_results_header_venue"> Fenway Park <br /> Boston, MA </td> <td class="tn_results_header_datetime"> Tue, Apr 29 2014 <br /> 7:10 PM </td> </tr> <tr class="tn_results_header_divider"> <td colspan="3" class="tn_results_header_divider"> </td> </tr></table> <div id="tn_loading" style="text-align:center;"><img src="//s3.amazonaws.com/TNService/Images/spinner.gif"/></div><div id="ssc_listAndMapDiv"></div><table style="display: none;" id="tn_tblNoResults" class="tn_results_notfound" cellspacing="0" cellpadding="4"> <tr class="tn_results_notfound"> <td class="tn_results_notfound"> There is currently no online inventory available for this event. <br /> <br /> Please contact <span class=\'tn_results_notfound_name\'> TicketSociety.com</span> at <span class="tn_results_notfound_phone"> (866) 459-9233</span> or <a class="tn_results_notfound_email" href="mailto:CustomerSupport#TicketSociety.com"> CustomerSupport#TicketSociety.com</a> to check availability for this event. </td> </tr> <tr valign="middle" class="tn_results_divider"> <td class="tn_results_divider"> </td>');
document.write(' </tr></table>');
As expected, it does some inline Javascript that actually WORKS twice. You can see it when looking at the 2 lines header before the big table. They indeed appear twice.
You can also inspect the DOM and you will see that your second div is populated with a skeleton table, but the table is never filled.
Unfortunately, the code also defines some variables and functions that are overwritten by the second include. The result is an Ajax request that cannot succeed (basically because the code was not designed to handle the same Ajax request twice on the same page).
If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Running a function by typing in URL
On my website I have several functions that when a hyperlink is clicked on example.php page, the main content changes accordingly. Now I want to direct people from a single URL to that example.php page with the function already called. Example - www.example.com/example.php?AC ( which will call a function named AC and the content changes before the page loads)
I had already asked the same question, but forgot to tag javascript and tagged php.
Thanks in advanced.
You can use JavaScript to get the querystring, and call the functions accordingly.
How to get querystring in JavaScript: JavaScript query string
What I would do is read the query string by using something like this to figure out if the key is there
function doesKeyExist(key) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
return qs != null;
}
Then
if(doesKeyExist(AC)) {
// run my code
}
You could do:
var query = document.location.search;
var func = window[query];
if (func && typeof(func) == "function")
func();
<script language="javascript">
var k = document.location.toString().split('?');
if(k.length > 1)
{
if(k[1] == "AC")
AC();
}
</script>
You can add a window.onload handler, check the query string of the page and act accordingly.
For example:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>
You run a JS funciton like this.
<script type="text/javascript">
function test()
{
alert('test');
}
</script>
Now if you type javascript:test() in the url it will execute test function.