JS var declared outside <script> file for use in said file - javascript

I have a bit of JS added to my home page like so-
<script type="text/javascript">
var mm_home;
mm_home = true;
</script>
I have another JS file that is being pulled into the head (below the above) that has the following lines:
baseUrl = $(this).parent().attr("action");
if(mm_home) {
url = baseUrl + 'category/bank-events/' + $('#tribe-events-events-year').val() + '-' + $('#tribe-events-events-month').val();
} else {
url = baseUrl + $('#tribe-events-events-year').val() + '-' + $('#tribe-events-events-month').val();
}
However, when I view my home page, the above conditional is failing and it reverts to the 2nd url var when I want it to use the first.
What am I doing wrong here?

Related

Why does loading a new html page reset javascript variables? How do I save those variables?

So I have this piece of code in an html file called demo.html
<img class="card-img-top" src="src/San_Francisco_Opera_House.jpg"
onclick="buyFunction('src/San_Francisco_Opera_House.jpg',
'SF opera house', 'price: $360,000')" alt="Card image cap">
This runs this javascript function which loads a new HTML page. I want to display the image in the new page,
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
setPicturePriceAndAddress();
});
};
function setPicturePriceAndAddress() {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
But all the values gets reset. Or is there another way to send information to the new html file without having to save variables?
You could potentially store the variables in session storage on demo.html and then call them inside of buy.html
demo.html:
function buyFunction(housePhotoString, addressString, priceString) {
sessionStorage.setItem('housePhoto', housePhotoString);
sessionStorage.setItem('address', addressString);
sessionStorage.setItem('price', priceString);
$(location).attr('href', 'buy.html');
}
buy.html:
$(document).ready(function() {
var housePhotoString = sessionStorage.getItem('housePhoto');
var addressString = sessionStorage.getItem('address');
var priceString = sessionStorage.getItem('price');
setPicturePriceAndAddress(housePhotoString, addressString, priceString);
});
function setPicturePriceAndAddress(housePhotoString, addressString, priceString) {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + housePhotoString + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + addressString + "</h4>" +
"<p class=\"card-text\">" + priceString + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
JavaScript is a client side language. Basically it is run on the web browser when it loads the page. Therefore, when a particular page is unloaded (moving away from the page, going to another page, closing the tab etc), the javascript values used in the page is flushed unless you take measures to save them.
For this, you can look into localStorage which saves the data in the browser and can be reused. Another method you can use is to set cookies which can also allow you to store and retrieve data from the user's browser between page loads.
You can store the variable in the localstorage and access the variables from anywhere under the same domain name , i.e you can use it another html file specified under same domain name
for example for your sample I created a little http server and then made a POC out of that
say your main script is contained in some index.html as your code block like this
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<script type="text/javascript">
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
//pass the houseAttributes object to setPicturePriceandAddress for better use of functions in js
setPicturePriceAndAddress(houseAttributes);
});
};
function setPicturePriceAndAddress(houseAttributes) {
let strHTML = "";
strHTML =
"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
console.log('data',strHTML);
//storing only for one time
var dataToSave = localStorage.setItem('strHtml',strHTML)
//storing for multiple time
var arr = [];
if(localStorage.getItem('arrOfStr')){
arr = JSON.parse(localStorage.getItem('arrOfStr'))
}
arr.push(strHTML);
localStorage.setItem('arrOfStr',JSON.stringify(arr))
$("#housePhotoBuy").html(strHTML);
};
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
</script>
</html>
Then you are accessing if in your file buy.html file
<html>
<head></head>
<body>
<h1>Buy</h1>
<script type="text/javascript">
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
getSavedValue()
</script>
</body>
</html>
and under the same domain name like for example if your index.html is in http://localhost:5000
and your buy.html is in http://localhost:5000/buy.html then you will be able to retrive all values stored in the buy.html in form of array if you want to store all the responses for a particular client or you can just access one single variable.I have made both the example you can use whatever you like according to your choice. If it's less than 5mb or something like that you can use localstorage and it is better to use than in cookie or session storage because they serve different purposes and they should be kept apart for saving extra data like this buy information for a particular client

Jquery or Javascript Redirect to Controller/Action

I have the following code which works on the first time around:
$("#CompDD").change(function () {
//var parts = (window.location.pathname.split("/"));
var ctrlName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var actnName = '#ViewContext.RouteData.Values["Action"].ToString()';
var url = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//delete ctrlName;
// delete actnName;
//window.location = ($(location).attr('href') + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//window.location = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//$(location).attr('href', url);
window.location.href = url;
//alert(ctrlName + "\n" + actnName);
});
However on subsequent changes of the drop down in question (#CompDD) it will add another controller/action to the end of the link, ex. it adds another "Patrons/Index" to the end of the existing "Patrons/Index", thenit adds the searchsrting variables etc.
Please excuse the comments and stuff on my code. How do i get Jquery (or javascript) to redirect without appending the controller name and action names over and over, or whats the best way to do this?
EDIT: Such an easy fix! I had to add the root slash to the URL string, example this worked:
var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
Notice the forward slash at the start of the string I construct....Yikes!
Use the Url.Action helper method to build path to action methods.
$("#CompDD").change(function () {
var baseUrl="#Url.Action("Home","Search")";
alert(baseUrl);
// Now append your query string variables to baseUrl
// Ex : baseUrl=baseUrl+"?searchString=testing";
window.location.href=baseUrl;
});
Assuming you want to navigate to the search action method in Home controller.
function RedirectUrl() {
if (domElement.textfor.val() == "Index") {
window. location.href = E_host.AppVar.AppHost + "/Home/index";
}
}

Replacing a .js File on a Website

So I'm trying to replace a javascript file on a website. I have tried using tamper monkey and developer tools, but none of them work? Thanks.
Original code
getAvatarUrl: function(avatar, type) {
if (!manifest[avatar])
avatar = 'base01';
var version = manifest[avatar][type];
return base_url + "/" + avatar + type + "." + version + ".png";
}
Overridden code
getAvatarUrl: function() {
return "Custom Image url";
}
Add the overridden code after the original code, as javascript interprets line by line. So add below code
getAvatarUrl: function() {
return "Custom Image url";
}
After
getAvatarUrl: function(avatar, type) {
if (!manifest[avatar])
avatar = 'base01';
var version = manifest[avatar][type];
return base_url + "/" + avatar + type + "." + version + ".png";
}
I don't think you have to replace the entire file, if you simply include another file after the other files, like <script src="path/to/script.js"></src> you can override the old function by declaring a new function:
function getAvatarUrl(){
return "Custom Image URL";
}

FB api call in for loop

I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.
In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment.
What am i doing wrong?? Thank you in advance!
var komentarji_length = response.comments.data.length;
for (var i = 0; i < komentarji_length; i++) {
var user_id = response.comments.data[i].from.id;
FB.api("/" + user_id + "/picture", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
var ime = response.comments.data[i].from.name;
var message = response.comments.data[i].message;
$(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '&nbsp says:</div><div class="single_message">' + message + '</div></div>');
}
Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.
But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.
Example
Still if you wish to get the proper image url (not required though), use redirect=0 with your call-
FB.api("/" + user_id + "/picture?redirect=0", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});

Rewrite URL hash to get variable

I am working on a site that has dynamic content.
When you click an article, it changes to address using the push state.
Example:
http://www.some-site.com/news/ - Before clicking a news item
http://www.some-site.com/news/dynamic-url/ - after clicking news item
But as pushstate does not work in IE or older browsers, I've rewritten it to use jQuery.address so it changes the hash in the url instead only for IE.
The problem now, is say someone sends a link to the site to a friend that they copied from Chrome and their friend uses IE, it will start appending the new has to that url.
Example:
http://www.some-site.com/news/dynamic-url/ - URL sent to friend
http://www.some-site.com/news/dynamic-url/#!/dynamic-url - URL after friend visits the site
So, I'm stuck on how to rewrite/redirect them. As, the hash never gets sent to Apache.
I've seen on twitter, they do exactly what I want, but I am unable to figure out how.
https://twitter.com/#!/google gets redirected to https://twitter.com/google and it works in IE.
Any help is much appreciated and if you don't understand please ask me to elaborate.
As suggested by David Thomas, here is the function.
var permalink = function(title, id, permalink){
var current = siteUrl + type + (order ? '/orderBy/' + order : '');
var newUrl = current + '/' + permalink + '/';
if(jQuery.browser.msie){
newUrl = '/' + permalink + '/';
jQuery.address.value(newUrl);
}
else{
stateNum++;
window.history.pushState({state: stateNum}, title, newUrl);
}
jQuery('title').html('SITE - ' + title);
}
What you need to do is either use a plugin (like jquery history) or make an event yourself to check the hash changes. Then, you read the hash (you strip the "!") and then handle the hash how ever you need. You might want to do ajax with it (such as load the domain / hash) and put the content somewhere on the page.
Is that clear?
After thinking it through for a while, I could only find one solution.
I'll post it here in case anyone is in a similar situation.
My solution, was a little hacky. If the browser is IE and has a fragment of url after a certain point, I count that as the name of news item. Once I have the name, I redirect them to the suitable url.
var permalink = function(title, id, permalink){
var current = siteUrl + type + (order ? '/orderBy/' + order : '');
var newUrl = '/' + permalink + '/';
if(jQuery.browser.msie){
jQuery.address.value(newUrl);
}
else{
current = siteUrl + type + (order ? '/orderBy/' + order : '');
newUrl = current + '/' + permalink + '/';
stateNum++;
window.history.pushState({state: stateNum}, title, newUrl);
}
jQuery('title').html('SITE - ' + title);
}
jQuery(document).ready(function(){
jQuery.address.crawlable(true);
if(jQuery.browser.msie){
if(jQuery.address.value() == '/'){
var currentPermalink = window.location.toString();
currentPermalink = currentPermalink.split(type);
if(currentPermalink[1] !== '/'){
window.location = siteUrl + type + '/#!' + currentPermalink[1];
jQuery.address.value(newUrl);
}
}
}
});

Categories