Dynamically Change Page Content and Set Hash with AJAX/jQuery - javascript

I am trying to create a webpage that will dynamically fill a div using AJAX. I have been able to simply update the div content with the following AJAX code:
$(document).ready(function(){
$("#projects-list a").click(function(e){
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
$('#content').fadeOut(300, function() {
$('#content').html(data).delay(200).fadeIn(300);
});
}
});
});
});
However, I also am hoping to find a way to update the page URL or change the hash. So for instance, when a user is given the link to /projects.html they will be sent to a page of links, and then when a link is clicked the content is changed using AJAX and the url will change to /projects.html#first. This way then a user navigates to /projects.html#first they will see the content for the first project rather than the original list of projects to choose from.

I would recomend to use a library to handle URL and paths
http://github.com/flatiron/director
http://balupton.github.com/history.js/demo

if you want to use standard # then you can use via js, on a function call do :
window.location.hash = valueYouWantToSet, some ID mostly,
and then you can check on page load if there is a # in there then call a particular function like :
handleHash: function () { if (!isNaN(parseInt(window.location.hash.replace('#', '')))){ this.showDetails(window.location.hash.replace('#', '')); }

Related

How to acces an external link without opening it, just loading it

Maybe is a strange title but all I want is to do so:
I have an arduino webserver and an webserver
My arduino server can receive data via url like
192.168.1.2?light=1 - light on
192.168.1.2?light=0 - light off
It is working just fine, but the problem is when I put that link anywhere on an website (in button or just normal links) the arduino server is opening in browser, is there possible to just load it using ajax, js or jquery or just simply using html?
Assuming you have a webpage with jQuery.
HTML
<a class="access-only" href="http://192.168.1.2?light=1">Turn on the light</a>
<a class="access-only" href="http://192.168.1.2?light=0">Turn off the light</a>
JS
$(document).ready(function() {
// Attach click handler to all "access-only" links.
$('a.access-only').click(function() {
// Once the link is clicked, access its URL with a GET request.
$.get($(this).attr('href'), function(response) {
// Do nothing here, the URL has been accessed.
});
// Return false to prevent the browser's default click action.
return false;
});
});
If want to use this link from a webpage then (requires jQuery):
$.get('http://192.168.1.2?light=1', function(response) {
console.log(response);
});
You can try this.
$(".yourAtag").click(function(e){
e.preventDefault();
$.ajax({url: this.href, success: function(result){
alert('success!');
}});
});

Display Proper URL in Address Bar

I'm using Jquery/Ajax to load html pages into a div on my website. I get links certain class to open up in the specified div. When doing this the address bar remains www.example.com. Due to the fact that I do have several pages that I will like to be able to share; so when people visit the links it will take them to the website but with the specific page loaded into the div container.
Here's a few lines of my code
$( document ).ready(function() {
$.ajax({
method: 'GET',
url: "pages/promo.html",
success: function(content)
{
$('#contentarea').html (content);
}
});
});
$('.menu_nav') .click (function () {
var href = $(this) .attr('href');
$('#contentarea').hide() .load(href).slideDown( 'very slow' )
return false;
});
Unless the other pages are on your domain, you cannot do this. If the other pages are, see this StackOverflow question: Updating address bar with new URL without hash or reloading the page.
Here's the deal: since you are loading a new page and you want the URL of the browser to point to that page, you should just give users a link. They know how to use the back button. (You could use the information in the linked answer to to change the URL to something like this: http://www.trillumonopoly.com/other-website.com.)
You can use the history object.
$('#contentarea').html(content);
history.pushState({url: "pages/promo.html"}, "", "pages/promo.html");
With the use of the state {url: "pages/promo.html"} you can load your page into your div when your users navigate back/forward.
$(window).on("popstate", function(e) {
if (e.originalEvent.state != null)
{
// AJAX load e.originalEvent.state.url
}
})

How to make sure hashtag attach the ajax updated content?

I had created a pagination with ajax. When user click the page number, it called the ajax function. I want to remember the previous ajax html data when user hit the back button. Therefore, I am trying to add the hash to each page. eg. when user click page 3, url is www.site.com/#3, page 4, is www.site.com/#4. It works OK so far. However, when I click the back button, it always load the second last page no matter the hash is 3 or 4. So, how can I make sure each hash attach to the ajax's update content? if the url is www.site.com/#4, it will always load the page 4 content. Appreicate.
$('#pagination a').click(function(e){
e.preventDefault();
$this = $(this).attr('href');//href is the page number
var data = {
action: 'post_pagination_ajax',
post_num : $this,
};
$.ajax({
url: ajax_front_gallery.ajaxurl,
type:'POST',
data: data,
success: function(data){
$('.post-content').html(data);
}
});
window.location.hash = $this;
return false;
});
You have a click event, however when you hit back button there is no any click event, browser just loads previous page from history. So what you have to do is to make also a load event. Final result will look something like this:
function loadContent ( url,data ) {
$.ajax({
url: url,
type:'POST',
data: data,
success: function(data){
$('.post-content').html(data);
}
});
}
$('#pagination a').click(function(e){
e.preventDefault();
var hash = $(this).attr('href');
var data = {
action: 'post_pagination_ajax',
post_num : $(this).attr('href')
};
loadContent( ajax_front_gallery.ajaxurl,data );
window.location.hash = hash;
return false;
});
$( window ).load(function() {
var data = {
action: 'post_pagination_ajax',
post_num : window.location.hash
};
loadContent( ajax_front_gallery.ajaxurl,data );
});
Edit:
Even though this solves your problem i would recommend doing it other way. Since you change hash and want to load content based on hash. There is a hashchange event for that. So you could do:
$(window).hashchange( function(){
var data = {
action: 'post_pagination_ajax',
post_num : location.hash
};
loadContent( ajax_front_gallery.ajaxurl,data );
});
//Trigger hash-change if page laoded with existing hash
$(window).hashchange();
And you won't need any click event on a preventing the default behaviour, because default behaviour of changing hash in url is what you want.
So I am not really sure if there is a standard how browser handle the url fragment (hash). The problem is that setting the hash is originally used for saying the browser where to scroll (with anchors etc.: http://www.w3schools.com/jsref/prop_loc_hash.asp). So when you set the hash most browser will put a new state in the history but will not use the current state of the DOM but use the old one before the hash was set.
But I can say, when ever I implement asynchrone paging with Javascript I do it similiar like you do, but I check the hash on the page load and load the specific page, so you always have the result you want.
I think this is the way the Google search works and it was the source of my idea.

Using PushState/PopState to keep div content when navigating to another page

I was learning some about this html5 concept and i was trying to integrated in my project .
I have a page called chat_wnd.aspx wish is a chat page between two client programmed by Signalr, and a masterpage having a div like so :
<script type="text/javascript">
function OpenChatwnd() {
$("#ifrm").attr("src", "/chat_wnd.aspx");
}
</script>
Open chat wnd
<div id="dv_chat">
<iframe id="ifrm"></iframe>
</div>
Is there any way to use the push/pop state to prevent the iframe from reloading inside the div every time i navigate to another page in my website
PushState only changes URL and adds the URL into history without change content, so you should use ajax to change your content.
Note that if you want to use <a> to navigate another page, your javascript may like below:
$('a').click(function(e) {
e.preventDefault(); // prevent default action of navigating to another page
// ajax load data
$.ajax({
url: $(this).attr('href'),
type: "GET",
success: function(html){
$('#content').(html);
},
error:function(xhr, ajaxOptions, thrownError){
console.error(xhr.status);
console.error(thrownError);
}
});
// change the current URL
window.history.pushState('', document.title, $(this).attr('href'));
});
Also, here is a jQuery plugin PJAX provides the integration of AJAX and pushState, you can see there demo at here.

How to handle every link click on a page in JS or jQuery?

People create their own websites using WYSIWYG creator i give them. These websites have links inside of them. Also they can explore the HTML of the website and put there their own links.
I would like now to handle every link click occurring in website created with my creator and log it to my server. I know how to pass the data from JS or jQuery to PHP server. But what i need to know is how to handle the moment when person clicks a link, postpone the redirection for some moment, and in this time get the url and title of this link and send to my PHP server.
So how to handle every link click (or location change) on website that structure i don't know and get the link and title of the link clicked?
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var title = $(this).attr('title');
// Send your data to php
if ($(this).attr('target') === '_blank') {
window.location.href = href; // redirect to href
} else {
window.open(href);
}
});
jQuery("a").click(function(){
var href = $(this).attr('href');
$.post('/', {link: href}).then(function(){ document.location = href; });
return false;
});
just a try
To intercept every link, just place this function somewhere that every page has access to (header/footer/etc.):
$('a').click(function(event) {
event.preventDefault();//To prevent following the link
//Your logic. attr('href') and attr('title')
});
You can use jQuery to do this. Use the on event and bind to the click event of a element. You can then do an event.preventDefault(); do your logic and then continue as normal by getting the href from the target.
Why you want to wait till logging is completed for the redirection. Let it be an asynchronous call so that user don't need to wait. If you want to have your server page in a different domain, to tackle the cross domain ajax issue, use jsonp datatype.
$('a').click(function() {
$.ajax({
url:"yourwebsite/loggingpage.php?data="+$(this).attr("href"),
dataType: 'jsonp' // Notice! JSONP <-- P (lowercase)
});
});
and in loggingpage.php, you can read the request data and log it to your persistent storage or wherever you want.

Categories

Resources