Difficulty Loading New Page w/ Javascript - 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 = '';

Related

Loading page with pathname when a button is clicked in javascript

I am a little bit confused here.
I have a url locahost/product-location/agro-product and want when a user clicks on a button on this page it takes the user to locahost/product/agro-product. After some research i figured out i could change the pathname this way
<script type="text/javascript">
function loadPage(){
var theURL = window.location.pathname;
return theURL.replace("/product-location/", "/product/");
}
</script>
The above works because if I add this alert(loadPage()); outside the function: it alerts the new URL path.
Now how do I write the code from here so when a user clicks the button it takes the user to the new URL?
You can use window.location.href:
function loadPage(){
var theURL = window.location.pathname;
var newURL = theURL.replace("/product-location/", "/product/");
//Set URL
window.location.href = newURL;
}
OK.got it. Just had to do a little rewriting
function loadPage(){
var theURL = window.location.href;
return window.location = theURL.replace("/product-location/", "/product/");
//Set URL
}
I'd recommend using window.open because you can choose what window it opens in (not to mention a variety of different options).
function loadPage(){
var newURL = window.location.pathname.replace("/product-location/", "/product/");
window.open(newURL);
//LOAD IN NEW WINDOW/TAB INSTEAD:
//window.open(newURL, "_blank");
}
Your button HTML would look like this:
<button onclick="loadPage();">Visit new page</button>

Can't load JSON when loading pages with Ajax and hash url

I'm currently working on a project using jQuery and Ajax to load in content from local html files to my single page site. I've also got a JSON file that I'm trying to incorporate into the files being loaded in with jQuery and Ajax.
I'm using hash urls to keep the pages separate. This is the code I'm using:
//other cached links
var pageLinks = $(".pageLink");
if(window.location.hash) {
var hash = window.location.hash.replace("#", "");
loadPage(hash + ".html");
} else {
loadPage("index.html");
}
pageLinks
.click(function(){
var iid = $(this).attr("id");
loadPage(iid + ".html");
});
function loadPage(resource) {
window.location.hash = resource.replace(".html", "");
$.get("pages/" + resource, function (data) {
content.html(data);
});
}
//this makes sure the contents of hash in the url is loaded in the page
if(window.location.hash) {
var hash = window.location.hash.replace("#", "");
loadPage(hash + ".html");
} else {
loadPage("index.html");
}
This is how I'm putting my JSON data into the page:
function FooBar() {
this.foo;
this.barLinkTemplate;
}
var fooBar = new FooBar();
$(document).ready(function (){
fooBar.contentDiv = $("#fooContent");
fooBar.barDiv = $("#bars");
$.when(
$.getJSON('data/music.json'),
$.ajax('components/components.html')
).done( function(data, templateData) {
var templateHTML = $(templateData[0]);
fooBar.barLinkTemplate = Handlebars.compile( templateHTML.find("#barLinks").html() );
fooBar.data = data[0].foo;
fooBar.barDiv.html( fooBar.barLinkTemplate( data[0].bars ));
));
});
The Ajax loads just fine, hashes and all. However, nothing from my JSON file is loaded into the page. I think I've narrowed my problem down (at least I hope) to one bit of code. If I comment out the last if/else statement (above), the JSON is loaded in the first page (only the first page). If I click on any link, and I navigate back to that page, the JSON data is gone. I have to actually reload the page for the data to reappear.
Without that if/else statement, I lose the ability to load the page content from the hash in the url--though the links still work fine.
I've been googling, but I haven't seen anything similar to the problems I'm having. Any help is appreciated. Thanks!

Using History API for Ajax div load

In my WP site I have post content loaded into a div with ajax on a click event.
I need it now to change the url for the current post, would prefer not using hashes.
How would I implement this using my js?
JS:
jQuery(document).ready(function() {
jQuery('#main-content').on('click', '.page a', function(e) {
e.preventDefault();
var url = jQuery(this).attr('href');
jQuery('#main-content').html('<h4>Loading...</h4>').load(url+ ' #main-content');
});
});
I have researched History API but I'm not sure how to implement it with my js.
I haven't done this yet myself, but this should be very simple using the pushState: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
var stateObj = { foo: "bar" };
history.pushState(stateObj, "New Page Title", "newPath.html");
Here's an extended example, where you would replace the content, path, and title with the results from your WordPress query that would grab the next post.
<!doctype html>
<html>
<head>
<title>Push State Testing</title>
<script type='text/javascript'>
var i = 1;
function goToPage( pageNumber, pushState ) {
var content = "Hello World " + pageNumber,
path = "hello_world_" + pageNumber,
title = content,
stateObj = {"content":content}
;
document.title = title;
document.getElementById('content').innerHTML = content;
if( pushState ) {
history.pushState({index:pageNumber}, title, path);
}
i = pageNumber;
}
function nextPage() {
goToPage( i+1, true );
}
window.onload = function() {
goToPage(1);
history.replaceState({index:1}, "Hello World 1", "hello_world_1");
}
window.onpopstate = function(event) {
goToPage(event.state.index, false);
}
</script>
</head>
<body>
<div id='content'>Push State Testing</div>
<button type='button' onclick='nextPage()'>Next</button>
</body>
</html>
In answer to the question in the comments. No, you don't need to know the path of the URL until you know the content. You replace the content and do the pushState at the exact same time:
$('#mainContent').html( contentFromWp );
history.pushState( state, titleFromWp, pathFromWp );
Okay, so to take the above and try to write it for you, which I can't test, so I can't guarantee that this will be working like my above examples...it would be something like this:
jQuery(document).ready(function() {
jQuery('#main-content').on('click', '.page a', function(e) {
e.preventDefault();
var url = jQuery(this).attr('href'),
title = jQuery(this).attr('title')
;
jQuery('#main-content').html('<h4>Loading...</h4>').load(url+ ' #main-content');
document.title = title;
history.pushState({url:url,title:title}, title, url );
});
});
window.onpopstate = function(event) {
document.title = event.state.title;
jQuery('#main-content').html('<h4>Loading...</h4>').load(event.state.url+ ' #main-content');
}
Note the need for onpopstate to make the back button work. You will also want to call a history.replaceState when your webpage first loads like I did in my example so that when users go back to the very first page the first page they were on will reload...otherwise, the user will only be able to go back to the second page they navigated to since going back to the first won't have a stateObj.

AngularJs function returns wrong window.location

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;

jQuery/Javascript: HTML pulled in by AJAX request does not include <script> elements

I have a dynamic page which uses an AJAX request kicked off by jQuery to pull in HTML elements from the server and insert them into the DOM.
The problem is that when I have elements within the response, they are stripped out.
For instance, if I request the following from the server:
<!-- content.html -->
<div>
There is some content here!
<script>
manipulateContent();
</script>
</div>
What actually gets injected into my dynamic page is the following:
<!-- content.html -->
<div>
There is some content here!
</div>
I have tested in Chrome, Firefox, and Safari with identical results.
The relevant Javascript which creates the AJAX request is here:
function loadContent(url){
var a = document.createElement('a');
a.href = url;
if (a.search == ""){
url = url + "?trim=true";
} else {
url = url + "&trim=true";
}
var ch = $('#content-container').height();
// var wh = $(window).height();
$("#content").animate({top: '-='+ch+'px'}, 500, function(){
$.get(url, function(data){
$("body").scrollTop(0);
$("#content").html(data);
$("#content").css({top: ch+'px'});
$("#content").animate({top: '0px'}, 500);
});
});
}
$(document).ready(function(){
// get the current path and save it for later
var currentPage = location.pathname+location.search;
$(".content-link").live("click", function(){
// using the HTML5 history API, add the requested path
// to the browser history, then load the new content
history.pushState({ path: this.path }, '', this.href);
// because the page is not reloaded, $(document).ready()
// is not called, so the currentPath must be updated manually
currentPage = this.href;
loadContent(currentPage);
return false;
});
window.addEventListener('popstate', function() {
// compare the current path to the one being loaded
// if they are different, then load the content
// else, nothing happens
if (currentPage != location.pathname+location.search){
// because the page is not reloaded, $(document).ready()
// is not called, so the currentPath must be updated manually
currentPage = location.pathname+location.search;
loadContent(currentPage);
}
});
});
How can I tell jQuery to include the tags in the response? I've tried browsing through the jQuery docs without much luck, or even mention of the fact that the tags are stripped out. Perhaps I'm just not looking in the right places.
You need to use load, since the whole purpose here is to load hml content to a element.
function loadContent(url) {
var a = document.createElement('a');
a.href = url;
if (a.search == "") {
url = url + "?trim=true";
} else {
url = url + "&trim=true";
}
var ch = $('#content-container').height();
// var wh = $(window).height();
$("#content").animate({
top : '-=' + ch + 'px'
}, 500, function() {
$("#content").load(url, function() {
$("body").scrollTop(0);
$("#content").css({
top : ch + 'px'
});
$("#content").animate({
top : '0px'
}, 500);
});
});
}
According to jQuery documentation (http://api.jquery.com/jQuery.ajax/) if dataType option is html:
Returns HTML as plain text; included script tags are evaluated when
inserted in the DOM.
By default this option is set to Intelligent Guess, so you may want to check the type of response from the server.

Categories