I've used pace.js but the problem with pace was, the loading animation was shown after the page was completely loaded.
So, i have tried and made a solution, onclick every link on the page, jquery grabs and stops the event from the browser going direct to the link, and sends a ajax get request to that link. While the page is loading, it shows an animation on the current page. After the page is completely loaded, it replaces the whole current document with the received data and replacing the page url in the address bar.
<script type="text/javascript">
$( document ).ready(function() {
$('a').click(function() {
var dt;
if (/#/.test(this.href)) {
return true;
}else{
document.getElementById("before-loader").style.display= "block";//show loading animation
var that = this;
$.ajax({
type: "GET",
url: that.href,
success: function(response){
document.open();
document.write(response);
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", that.href);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";//hide loading animation
}
});
return false;
}
});
});
</script>
The problem is on clicking browser back button, the url in the address bar is changing but the page content still remains the same.
How can i overcome this problem?
Update
se0kjun's answer didn't solved my problem(i was expecting it to work after copy/paste the code provided) but put me in the right direction. After some study and rewriting the flow, it works, but i am still confused why it works.
$( document ).ready(function() {
$('a').click(function() {
if (/#/.test(this.href)) {
return true;
}else{
window.history.pushState(null, 'Production Workflow & Sales Management', this.href);
loadContent(this.href);
return false;
}
});
});
function loadContent(href) {
document.getElementById("before-loader").style.display= "block";
$.ajax({
type: "GET",
url: href,
success: function(response){
document.open();
document.title = response.pageTitle;
document.write(response);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";
}
});
}
window.onpopstate = function(event) {
link = location.pathname.replace(/^.*[\\/]/, ""); // get filename only
loadContent(link);
};
Maybe i should study more.
I think you want to popstate event.
When you click a link, ajax request to that.href. After that, if request is successful, you would get response and call pushstate.
When you click a back button, popstate event is triggered. you can load previous page in popstate event handler.
Following to usage example of popstate
window.onpopstate = function(event) {
//you add a path in pushstate
$('.container').load(event.state.path);
alert('popstate');
};
Here's a fiddle
Related
In some AJAX query, in response.done I refresh some div and it works fine, the problem is this refresh doesn't refresh also another function(this function fill the content html() of another div inside the refreshed one). I'm thinking for a trick to add an event to listen when that div is reloaded, I lunch my getAmount() function.
I tried to add that function after reloading part in AJAX but it doesn't work.
file1.phtml
ajaxRequest = jQuery.ajax({
...
ajaxRequest.done(function (response, textStatus, jqXHR) {
jQuery("#shopping-cart-table").load(location.href + " #shopping-cart-table"); //Here I reload my div.
});
file2.phtml
function getAmount() {
var some = jQuery(this).attr('data-subtotal');
jQuery('#shopping-cart-table .data').each(function(){
jQuery('.ship-cart-vendor-header').each(function(){
jQuery(this).find('.not-reached').html(some);
});
});
}
You've to call your getAmount function in the load callback, what mean after the complete reloading :
jQuery("#shopping-cart-table").load(location.href + " #shopping-cart-table", function(){
getAmount();
});
I have a link which invokes an API which saves a session. Suppose my API be present on http://www.example.net and my link is as below :
<a href="http://www.example.net" >Click here </a>
Now i don't want to refresh the page. Just use JQuery or Javascript to simply execute the link and give an alert like "Action Succesfull". I don't see the point of using AJAX as I don't require any database actions from my side. Thanks
The point of AJAX is not to do database actions, its to comunicate with the server without needing to reload the page. I think your description qualifies for the use of AJAX, since you do expect a answer from the server, and you do not want to reload the page.
You could also open a iframe, or a new window, but ajax might be the solution here.
Keep in mind you need to cancel that event when you click on the anchor.
So, with ajax you could so something like:
$('a').on('click', function(e) {
e.preventDefault;
var href = this.getAttribute('href');
$.ajax({
url: href,
success: function(text) {
alert(text);
}
});
});
You will need an ajax call. Something like this:
$.ajax({
cache: false,
type: "Post",
url: "http://www.example.net",
success: function () {
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
finaly: function () {
alert("Finish");
}
});
You can simply use onclick event if you don't want to use AJAX
Click here
Try to use an ajax call when click on button submit or the link. Here is the code :
$("a").click(function(e){
$.ajax({
url: "http://www.example.net",
type: "POST",
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data,textstatus,jqXHR)
{
alert("Success");
}
});
e.preventDefault();
});
you need to do something like this:
$('a').click( function(e) {
e.preventDefault();
var url = "your link";
$.ajax({
url: url,
success: function(data)
{
alert(data); // show response.
}
});
return false;
});
I already asked some questions about ajax, but I still don't get it.
I took a script that I found on the internet and made some modifications, but it didn't work!
HTML:
<a data-toggle="team" id="times">TEAM</a>
ORIGINAL SCRIPT:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>
MODIFIED SCRIPT:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('#times').click(function(e) {
$("#loading").show();
var href = $(this).attr("data-toggle");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
$.ajax({
url: 'ajaxcontdent/ajax'+url,
type: 'GET',
error: function(){
// always good to have an error handler with AJAX
},
success: function(data){
$('#content').html(data);
}
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
};
</script>
What is wrong with my script? Nothing happens. I click in my <a> link and nothing. I already tried to put the file location on a hrefattribute, but then e.preventDefault(); doesn't work and my website runs like there is no AJAX.
In the original code, the author use some content.php file. But I don't know JSON, so I have no idea what did he put in that file.
There are no errors in the console.
My ajaxcontent/ajaxteam.php file content:
<p style="color:#fafafa;">Team</p>
It's just one line indeed. Just a test.
I think that may be a cause syntax error, I have regenerate one of your function so please use below code.
function loadContent(url){
$.ajax({
url: 'ajaxcontdent/ajax'+url,
type: 'GET',
error: function(){
// always good to have an error handler with AJAX
},
success: function(data){
$('#content').html(data);
}
});
};
Then use your operation, whatever you want, in your success block of above function.
I hope thin will help you.
Thansk
In your code if I am not wrong
url: 'ajaxcontdent/ajax'+url,
this is the main culprit.
Try this one:
url: 'ajaxcontent/ajax'+url,
I have a list of thumbnails of recipe names and i want to track which recipes people are clicking on. I problem is that i can strictly do this using jQuery and nothing else. I dont have access to any other pages of the website.
What i did so far is i checked on the names of recipe and images and added a common class using .addClass() in jquery and just after that i declared an onclick function on that name.
Then i a taking the tile of the tag(Which is the recipe name) and sending this information of my other website where it stores this info in database.
The problem is my clicks are not getting all of the time. The behavior looks random to me till now and i don't know how some of the clicks are getting stored and how some are not!! I researched on net and only related thing i found was to keep cache to false. I also tried that but the behavior remained the same. Clicks got stored sometime only.
I am doing this on local host right now and i need to store this info on other website of mine.
jQuery(window).load(function(){
jQuery('.del-space .thumbnail a').addClass("recipeLinks");
$(".recipeLinks" ).on("click",function(event) {
var user=jQuery('loggedinuser').attr('title');
//alert(user);
if(typeof(user)==="undefined"){
user='Guest';
}
var recipeName=$(this).attr('title');
var data='recipeName='+recipeName+'&user='+user;
$.ajax({
url: "http://myotherwebsite.com/tracking/storeClick.php",
cache: false,
type: 'POST',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//alert('done');
//window.location = location.href;
},
error: function(xhr, textStatus, errorThrown) {
//alert("error");
}
});
});
Apart from this i am also wondering, that when i will put this code on live, where there would be a hell lot of clicks at a time, will i be able to log all the clicks?
use event.preventDefault() to stop the click from changing the page right away so that your ajax request has time to complete, and use window.location to change the page once ajax is complete
jQuery(window).load(function(){
jQuery('.del-space .thumbnail a').addClass("recipeLinks");
$(".recipeLinks" ).on("click",function(event) {
event.preventDefault(); //stop the default action
//the action will take place after
//ajax is complete
var href = jQuery(this).attr("href"); //get the location to goto
var user=jQuery('loggedinuser').attr('title');
//alert(user);
if(typeof(user)==="undefined"){
user='Guest';
}
var recipeName=$(this).attr('title');
var data='recipeName='+recipeName+'&user='+user;
$.ajax({
url: "http://myotherwebsite.com/tracking/storeClick.php",
cache: false,
type: 'POST',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//alert('done');
window.location = href; //now goto the links href
},
error: function(xhr, textStatus, errorThrown) {
//alert("error");
}
});
});
Apologies, a total newb here. How can I load other plugins, and let other separate scripts function after loading an ajax generated page? This is my curent code:
jQuery(document).ready(function($) {
var $mainContent = $("load-content"),
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='"+siteUrl+"']:not([href*='/wp-admin/']):not([href*='/wp-login.php']):not([href$='/feed/'])", "click", function() {
if($.browser.msie){
var myie="/"+this.pathname;
location.hash = myie;
//alert(location.hash);
}else{
location.hash = this.pathname;
}
return false;
});
$("#searchform").submit(function(e) {
$search = $("#s").val();
$search = $.trim($search);
$search = $search.replace(/\s+/g,'+');
location.hash = '?s='+$search;
e.preventDefault();
});
$(window).bind('hashchange', function(){
url = window.location.hash.substring(1);
if (!url) {
return;
}
url = url + " #content";
$('html, body, document').animate({scrollTop:0}, 'fast');
$mainContent.fadeOut(500, function(){$('#content').fadeOut(500, function(){
$("#loader").show();});}).load(url, function() {
$mainContent.fadeIn(500, function(){
$("#loader").hide(function(){ $('#content').fadeIn(500);});});});
});
$(window).trigger('hashchange');
});
How can embedded objects on pages retain their functionality? Mainly videos, slideshows and other media that use javascript like
video js (html5 video player)
vimeo
and
portfolio slideshow for wordpress
When you load ajax-generated markup it will not retain the functionality it had before. In your example above, you're initialising things when the DOM is ready to be acted upon. In order to make sure any plugins, etc, are running after you perform the ajax request you need to reinitialise them.
Given your code sample above, I'd recommend a little restructuring. For example, you could create a function called init which you could call to initialise certain plugins:
function init () {
$("#plugin-element").pluginName();
}
jQuery(document).ready(function () {
// Initialise the plugin when the DOM is ready to be acted upon
init();
});
And then following this, on the success callback of you ajax request, you can call it again which will reinitialise the plugins:
// inside jQuery(document).ready(...)
$.ajax({
type: 'GET',
url: 'page-to-request.html',
success: function (data, textStatus, jqXHR) {
// Do something with your requested markup (data)
$('#ajax-target').html(data);
// Reinitialise plugins:
init();
},
error: function (jqXHR, textStatus, errorThrown) {
// Callback for when the request fails
}
});