AngularJs function returns wrong window.location - javascript

I'm having this angularJs script to pass me to my view where the Url will be: www.mySite.com/blogg/1
It works fine if I am on my startPage (www.mySite.com). When the function gets hit it takes me to www.mySite.com/blogg/1.
But the problem is when I then are on one of my blogPages (www.mySite.com/blogg/1). Then when my function gets hit to take me to another blogPage the Url that renders is for example: www.mySite.com/blogg/blogg/2
Hoq can I remove the extra /blogg part so it renders as i want: www.myPage.com/blogg/2 ?
$scope.goToRequestedPost = function (id) {
console.log(id);
{
$http.post("/Home/SingleBlogPost", { postId: id }).success(function () {
window.location = "blogg/" + id;
});
}
};
//Thanks

Use one of the following:
// similar behavior as using HTTP redirect
window.location.replace("/blogg/" + id);
// similar behavior as when clicking on a link
window.location.href = "/blogg/" + id;

use the service $location (https://docs.angularjs.org/api/ng/service/$location)
$location.path("blogg/" + id);

Just prepend '/' to make the path relative to the domain root instead your current location.
window.location = "/blogg/" + id;

Related

Difficulty Loading New Page w/ Javascript

I'm writing a basic Flask app. I have a page called /searchByCollege that consists of a bunch of buttons, each with a team name as their text, and .college as their class.
I've written some JS so that, when the user clicks on a button, it'll load /searchByCollege/collegeName, where collegeName is the text of the button they just clicked on. Here's what I have:
<script>
$('.college').on('click', function() {
var baseURL = $('#baseURL').text();
var finalURL = baseURL + "/" + this.text();
window.location.href = finalURL;
return false;
})
</script>
I didn't originally include return false; and nothing happened upon clicking a button. Then I added return false; and I got the same result. I've inspected the HTML and the base URL is correct (it's just /searchByCollege). I've looked at the requests as I click on the button and none are being made.
I've loaded jQuery above this through Google's CDN so that's not the issue.
Any other ideas?
Thanks for the help,
bclayman
this.text()
needs to be changed to
$(this).text()
You need to wait for the document to load by using $(document).ready:
<script>
$(document).ready(function(){
$('.college').on('click', function() {
var baseURL = $('#baseURL').text();
var finalURL = baseURL + "/" + this.text();
window.location.href = finalURL;
return false;
});
});
</script>
I could not figure out where you were getting the 'baseURL' Since you are using just JQuery you need to call .value and not .text()
<button class="college" value="CSU">CSU</button>
$('.college').on('click', function(){
var baseURL = "/searchByCollege";
var finalURL = baseURL + "/" + this.value;
return false;
});
you can try this
window.location.hostname = finalURL;
window.location.pathname = '';

How to use onhashchange with dynamic items

So, I have two select boxes on a webpage, but in different anchors (one on the page, the other in an iframe) and I'm trying to get the code to detect which anchor it's in, and then relay the selected value in that box to a link. Here's my code:
function locationHashChanged() {
if (location.hash === "#player") {
function setText(text) {
var selectVal = text;
var url = $('twitter').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}
}
if (location.hash === "#embeds") {
$(function () {
var $twitter = $('twitter');
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val() || 'nothing much';
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}).change();
});
});
}
}
I know this is probably not right, or anywhere near right, but am I on the right track? I'm honestly a complete noob when it comes to javascript. Thanks in advance
Apart from what exactly your function looks like, it's not executed on hash change right now.
You use jQuery, so you can listen for hash change like this:
$(window).on('hashchange', function() {
// your locationHashChanged() function goes here
});
With this, every time the hash changes your function will be executed. The very base of your code is alright:
if (location.hash === "#player") {
// this is executed if hash changed to #player
}
if (location.hash === "#embeds") {
// this is executed if hash changed to #embeds
}
Although, inside your if blocks you declare functions (which doesn't make much sense here).
Also note that if the iframe is not from your domain, you won't be able to get any data from it. If that's the case, read more about same origin policy.

Back button / backspace does not work with window.history.pushState

I have made a solution for my website which includes using ajax to present the general information on the website. In doing this, I am changing the URL every time a user loads some specific content with the window.history.pushState method. However, when I press backspace or press back, the content of the old url is not loaded (however the URL is loaded).
I have tried several solutions presented on SO without any luck.
Here is an example of one of the ajax functions:
$(document).ready(function(){
$(document).on("click",".priceDeckLink",function(){
$("#hideGraphStuff").hide();
$("#giantWrapper").show();
$("#loadDeck").fadeIn("fast");
var name = $(this).text();
$.post("pages/getPriceDeckData.php",{data : name},function(data){
var $response=$(data);
var name = $response.filter('#titleDeck').text();
var data = data.split("%%%%%%%");
$("#deckInfo").html(data[0]);
$("#textContainer").html(data[1]);
$("#realTitleDeck").html(name);
$("#loadDeck").hide();
$("#hideGraphStuff").fadeIn("fast");
loadGraph();
window.history.pushState("Price Deck", "Price Deck", "?p=priceDeck&dN="+ name);
});
});
Hope you guys can help :)
pushState alone will not make your page function with back/forward. What you'd need to do is listen to onpopstate and load the contents yourself similar to what would happen on click.
var load = function (name, skipPushState) {
$("#hideGraphStuff").hide();
// pre-load, etc ...
$.post("pages/getPriceDeckData.php",{data : name}, function(data){
// on-load, etc ...
// we don't want to push the state on popstate (e.g. 'Back'), so `skipPushState`
// can be passed to prevent it
if (!skipPushState) {
// build a state for this name
var state = {name: name, page: 'Price Deck'};
window.history.pushState(state, "Price Deck", "?p=priceDeck&dN="+ name);
}
});
}
$(document).on("click", ".priceDeckLink", function() {
var name = $(this).text();
load(name);
});
$(window).on("popstate", function () {
// if the state is the page you expect, pull the name and load it.
if (history.state && "Price Deck" === history.state.page) {
load(history.state.name, true);
}
});
Note that history.state is a somewhat less supported part of the history API. If you wanted to support all pushState browsers you'd have to have another way to pull the current state on popstate, probably by parsing the URL.
It would be trivial and probably a good idea here to cache the results of the priceCheck for the name as well and pull them from the cache on back/forward instead of making more php requests.
This works for me. Very simple.
$(window).bind("popstate", function() {
window.location = location.href
});
Have same issue and the solution not working for neither
const [loadBackBtn, setLoadBackBtn] = useState(false);
useEffect(() => {
if (loadBackBtn) {
setLoadBackBtn(false);
return;
} else {
const stateQuery = router.query;
const { asPath } = router;
window.history.pushState(stateQuery, "", asPath);
},[router.query?.page]

script to redirect if the url contains a querystring

SHORT: Need a script to remove the parameters on URL IF EXIST. Must be jquery/Script/
LONG: I have a site where I send traffic to with lots of parameters. These are processed instantly with php to cookies. After my cookie set I would like to refresh the same page but WITHOUT parameters. I cannot do it php since the cookies need to be processed by an iframe so I need a jquery/script to do it AFTER cookies are set via the iframe.
Thanks guys! :)
The below code will remove the query string parameter and will reload the page
window.location.href = window.location.protocol+"//"+window.location.hostname+window.location.pathname
The search attribute of window location describes the GET parameters on the url so -
if (window.location.search != "") {
window.location.search = "";
}
You may want to check out this question for a another solution.
And have a look at the MDN Documentation on window.location for more info.
I think you need to use something like:
var url_update= false;
var stripped_url;
function removeparametersFromURL(url_string) {
if (url_string.indexOf("#") > 1) {
URL = url_string.split("#")[0];
url_update= true;
}
if (url_string.indexOf("?") > 1) {
URL = url_string.split("?")[0];
url_update= true;
}
return URL;
}
var stripped_url = removeparametersFromURL(top.location.href);
if(url_update){
top.location.href = stripped_url;
}
setTimeout(function(){
stripped_url = removeparametersFromURL(top.location.href);
if(url_update){
top.location.href = stripped_url;
}
},5000); //will call function after 5 seconds

jQuery/Javascript: How to get anonymous function to reference variable declare outside?

I have some jQuery code that doesn't work as expected.
$('a[href^="http://"]').not('[href^="http://mydomain.com"], [href^="http://itunes.apple.com"]').click(function (e) {
e.preventDefault();
console.log("external: " + this.getAttribute('href'));
var url = this.getAttribute('href');
foo.track(
"External",
{ 'URL': url },
function (url) {
location.href = url
}
);
});
For this example, I'm tracking all external clicks from my domain, except for iTunes apps store. Assume foo.track() is a 3rd party method I'm using to track some events for reporting. The last parameter to it is an anonymous function that is executed once the tracking call successfully returns.
The code above is trying to navigate everything to http://mydomain.com/1 for some reason. However, the console.log statement succesfully logs the expected values. It's as if the url variable isn't referencing the value I expect. I've also tried replacing location.href = url with window.location = url but I get the same result.
What am I doing wrong?
Just remove the parameter from the navigation function. Like this:
$('a[href^="http://"]').not('[href^="http://mydomain.com"],
[href^="http://itunes.apple.com"]').click(function (e) {
e.preventDefault();
console.log("external: " + this.getAttribute('href'));
var url = this.getAttribute('href');
foo.track("External", { 'URL': url }, function (/*url*/) { location.href = url });
});

Categories