I recently found this gist on how to Ajaxify a Website with the HTML5 History API using History.js, jQuery and ScrollTo: https://github.com/browserstate/ajaxify
I am having a hard time getting a simple version of this working and am not sure I understand everything. First, I loaded all the scripts provided in the gist, then set up a really simple nav and content section:
<ul id="nav">
<li id="home-link">Home/</li>
<li id="work-link">Work/</li>
<li id="labs-link">Labs/</li>
<li id="blog-link">Blog/</li>
<li id="contact-link">Contact</li>
</ul>
<div id="content"></div>
Next, I changed the selector variables to match the html:
/* Application Specific Variables */
contentSelector = '#content',
$content = $(contentSelector),
contentNode = $content.get(0),
$menu = $('#nav'),
activeClass = 'active',
activeSelector = '.active',
menuChildrenSelector = 'li',
What I'm supposed to do next is where I get lost. All I want to do is load in html content specific to the nav link selected. So if I clicked "Work", I would like to load a work.html file into the content section and change the url to "mywebsite.com/work". To keep things easy lets say work.html and all other ajaxable content is located in the same directory.
Any help is greatly appreciated! Cheers!
So here is a real bare bones example of how I ended up ajaxifying the website I was working on that inspired this question. Sorry for the really long delay. First the HTML:
<ul id="nav">
<li id="home-link">Home</li>
<li id="work-link">Work</li>
<li id="labs-link">Labs</li>
<li id="blog-link">Blog</li>
</ul>
<div id="content">Home Content</div>
Next the Javascript:
<script type="text/javascript">
var directory = 'content/'; //directory of the content we want to ajax in
var state = History.getState();
//for when they click on an ajax link
$('.ajaxify').on('click', function(e){
var $this = $(this);
var href = $this.attr('href'); // use the href value to determine what content to ajax in
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
e.preventDefault(); // we don't want the anchor tag to perform its native function
});
//for when they hit the back button
$(window).on('statechange', function(){
state = History.getState(); // find out what we previously ajaxed in
$.ajax({
url: directory + state.title + '.html', //create our path
dataType: 'html',
success: function(data) {
$('#content').html(data);
}
});
});
</script>
Essentially all I am doing is intercepting anchor tag clicks with the class 'ajaxify' used to signal what specific content I want to load in. Once I intercept the click and determine what content to load, I then use history.js pushSate() to keep track of what order the user is going through the site and change the url without reloading the page. If they decide to hit the back button, the statechange listener will load in the correct content. If they decide to hit the refresh button, you will need to come up with a method of duplicating your index page with the different url names. This is easy to do in php or you could just copy, paste, and rename the index page as needed.
Here is an example I posted on Github: https://github.com/eivers88/ajaxify-simple-demo
Just a reminder, when working with ajax locally, it is best to run your projects on a personal web server like MAMP or WAMP. This demo will fail in chrome without a server running. However, it should work in firefox without a server.
There are a variety of things you would need to do given those requirements. Here is a function you can use:
function doAjax(htmlpage){
$.ajax({
url:"/"+htmlpage,
type: 'GET',
success: function(data){
$('#content').html(data)
}
});
}
The the simplest way to hook this out would be to adjust your tags above to be like:
<img>
It would however be slightly more "correct" (though functionally the same) to do this with jquery in a script tag at the top:
$(function () {
$('#buttonid1').click(function(){doAjax('work.html')});
$('#buttonid2').click(function(){doAjax('about.html')});
$('#buttonid3').click(function(){doAjax('contact.html')});
});
Note in both cases, these "work.html" pages shouldn't be full html documents, they should just be what goes in your content div.
This ajax will do nothing to change the url that your visitor sees. To get that to work, you'll have to use the html5 history api. It is quite a bit more complicated than the the ajax request I have above. So if you don't have a full mastery of what I wrote above, it may or may not be appropriate.
Related
I am very new to ajax and am really struggling. My end goal is to make a forum software like nodebb. I've already made a php forum but decided not to use it because it just seemed old unlike faster looking forums like nodebb. What I'm trying to understand is how to make multiple tabs that display different information each but keep the same data for the header. I understand this is probably a very simple thing to do, but currently I am unable to accomplish this.
https://dogecraft.net is a great example of what I'm trying to accomplish.
If you click on the different tabs, it loads information in each one. I tried this but I had trouble with the url. When I reloaded, it simply just loaded my new file and that's not what I want.
(Yes, I am using a local jquery file. Jquery isn't the issue.)
I've tried w3schools but didn't find really helpful information
I've also tried many other websites.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$( "#one" ).click(function(){
$("#div1").load("/one/").hide().fadeIn();
window.history.pushState("object or string", "Title", "/one/");
});
});
$(document).ready(function(){
$( "#two" ).click(function(){
$("#div1").load("two.html").hide().fadeIn();
});
});
</script>
</head>
<body>
<button id='one'>Page one</button> <button id='two'>Page two</button>
<h2>This text never changes :)</h2>
<div id="div1"></div>
</body>
</html>
I would like to have a homepage 'index.html/php'
I need a button to load one page of content (one.html/php) and then another button that loads another page of content (two.html/php).
On refresh, I would like it to keep the same content that was on the homepage including the buttons in the header.
You could make an Ajax call to your html/php to retrieve the html code and then inject the content on your div. Here is an example:
$(document).ready(function() {
$("#one").click(function() {
$.ajax({
url : 'http://myserver.com/myhtmlpage.html',
success : function(html) {
$("#div1").html(html);
}
});
});
$("#two").click(function() {
$.ajax({
url : 'http://myserver.com/myphppage.php',
success : function(html) {
$("#div1").html(html);
}
});
});
});
When you click a button, an ajax call is made, and if succesful, the success function will be called. The first parameter has the html code of the webpage you requested. Then you can use the html function of jQuery you can inject it on your div.
A couple of tips:
You might want to use only one onready function, no need to declare it several times
You might consider returning a json object with the data instead of a php page. This will be useful later on if you consider using a framework such as Angular or Vue. If you can generate a JSON file on your php such as this:
{
"name": "John"
}
Then you could do something like this:
$("#two").click(function() {
$.getJSON({
url : 'http://http://myserver.com/myphppagethatservesjson.php',
success : function(json) {
$("#div1").html("<h1>My name is " + json.name + "</h1>");
}
});
});
Then it will render "My name is John".
This could be improved a lot,but I hope it could help you a bit.
Trying to use forum us a comments section on webpage and avoid iframes at the same time.
<script>
$('#test').load('./forum/viewtopic.php?f=13&t=10' function(result) {
var variable = $('#result').html();
$(this).find(".topic-title").remove();
$(this).find(".action-bar").remove();
$(this).find(".postprofile").remove();
</script>
All links that would point to site.com/forum/linkhere.php now point to site.com/linkhere.php this includes all my calls for scripts in the header, so all of the ajax forms are essentially useless as well. I tried a rewrite like so
$('#test a').each(function(){
$(this).prop('src', path + '/' + $(this).prop('src'))
and trying with $('#test script') as well, and also path + '/forum' but no luck. The contents of this just gets pushed to a div with id="test" at the moment.
Anyone got some tips for me?
$(function() {
$('script').each(function() {
$(this).attr('text/javascript', function(index, value) {
if (value.substr(0,1) !== "/") {
value = window.location.pathname + value;
}
return "https://site[dot]com/forum" + value;
});
});
});
});
UPDATE: I had some luck by setting PHPBB_ROOT_PATH : '../forum'; in viewtopic.php, this fixed my relative paths issue and started loading all the headers correct. But now once a post is submitted via the ajax form, the post submits successfully, but there's an error refreshing the ajax page .loaded into a div with jquery. Any ideas what this might be? I think it's a jquery/.load issue because the form works fine on the actual forum page.
use full path URLs like
http://yoursite.com/forum/linkhere.php
for every call in your
viewtopic.php file
-edit:
try using httacces file in your root folder
check this thread :
Using .htaccess to redirect all pages except three
I am currently trying to implement the WordPress Contact Form 7 Plugin into a WordPress-site I created. The theme uses jQuery to overwrite the default link behaviour and AJAX to load the requested page without actually reloading the whole page.
The problem is: The contact form works perfectly when the page where it is used on is loaded directly. However, if the page is loaded via AJAX, there are two strange behaviours: The Google reCAPTCHA widget is not showing up and after submit, instead of showing the div with the success-message, I am redirected to the themes "404" page. The mail gets sent successfully though. I use the plugin/contact-form in AJAX mode - so it makes an AJAX call itself to submit the data and handle the response without page refresh.
I am a bit overwhelmed where to start to solve this problem. Just for testing, I tried to hardcode all scripts from the direct pageload to the theme, so that they are also there when the contact-page is loaded via AJAX. Unfortunately, this didn't have any effect at all. I also tried to call the wpcf7InitForm() function of the plugin, as it was suggested in another question here - also with no success.
This is my ajaxload-script:
jQuery(document).ready(function($) {
// Targeting all internal links
$(document).on('click', 'a[href^="http://' + top.location.host.toString() + '"]:not([href*="wp-admin"])', function(event) {
event.preventDefault();
var url = $(this).attr('href');
$.ajax(url, {
beforeSend: function() {
if ($('#ajax-loader').length == 0) { $('body').append('<div id="ajax-loader"></div>'); }
$('#ajax-loader').fadeIn();
// Dimming static elements during loading
$('#mainbar').animate( { opacity: '0.5' } );
},
success: function(data) {
var data = $('<div />').html(data);
window.history.pushState('...', '...', url);
document.title = $(data).find('title').text();
$('#mainbar').html($(data).find('#mainbar > *'));
// Undoing design modifications to static elements
$('#mainbar').animate( { opacity: '1' }, 150 );
$('body').triggerHandler('reflow');
},
});
});
});
Help on this topic would be really appreciated and thanks in advance!
Couple ideas after reading through some stuff:
Might be a bug with the recaptcha - looks like the latest version specifically fixes recaptcha problems (not sure if they are yours though): http://contactform7.com/2015/11/23/contact-form-7-431/#more-16357
The div not showing up should be easy to debug by using absolute paths. In Wordpress, I usually use the bloginfo(); function. Try putting something like this in your form submit success callback to test path visibility between the AJAX and non-AJAX pages:
<?php
$pathCheck = bloginfo('template_directory');
echo $pathCheck;
?>
The problem with the div not showing up could also be how you are structuring the callback. From this question, it appears that the plugin has specific callback hooks you have to use that aren't in the documentation:
$(".your-form-class").on('wpcf7:mailsent', function(event){
// Show success div code would go in here
});
Great question btw. You used proper english and clearly explained your problem, pretty rare on S.O. Hope some of this gets you going.
So I have a website I am working on just as a personal website that uses jQuery and jQuery UI
Previously I have been using hidden html code and just using jquery to show it.
But its making my html file messy so I wanted to use jquery's .load() to do the same thing but from an external file.
Right now, its set to a .click function.
For my hidden html it shows it every time when I click a particular element.When you click on a different element it. It hides the first one. I am doing it by having a div with 2 classes. The problem is when I tried to load html into a hidden div, and then show it and hide it, it only worked the first time.
Enough talk, here is my code. #1 works , #2 only works on the first click. And leaves imagearea blank every time after.
$(".jquery").click(function(){
clearImageArea();
hideThumbnails(5);
showThumbnails();
$("#1").click(function(){
$(".imagearea").html(js);
$(".jscode").show(1000);
$(".title").text("Extending jQuery");
});
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html");
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
now my hidden stuff in my html file
First my html and js code is loaded into here from jqueryEx.html and is being hidden elsewhere in my javascript via $(".hidden").hide(); and loaded then into into imagearea via .html() and shown via .show()
<div class="jquery2 hidden">
</div>
My other div looks like this which is put into imagearea by clicking on #1
<div class="jscode hidden">
<div class="block">
//lots of js code escaped out into html
</div> <!-- end of block-->
</div>
elsewhere in my JS code at the beginning I have var js=$(".jscode"); to load it into the js variable you saw earlier.
if you want to see an out of date example of what I am working on
go to www.3realsoft.com (only cs and js work on skills)
if you want to see any additional parts of my code, just ask. Most of it is there on my website though.
I got to this item in my search results, when I was trying to have a button both load and refresh the content, and the load was working but the refresh was not working.
Here's a shorter version of the solution, setting Cache to false was the key. Solution found over at this other link, but I'm posting this concept here because if Google dropped me in this item, others looking for the same will also probably find themselves here. Props to John Millikin, make sure to go over to his answer and upvote him: Stop jQuery .load response from being cached
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$('.detail-expand').click(function () {
var detailRowElement = $(this).closest('.session-row-tr').next();
var detailElement = detailRowElement.find('.detail-row-div');
var sessionId = detailElement.data("sessionId");
detailElement.empty();
detailElement.load('/Admin/WebLogPartial/' + sessionId, function () {
$.bootstrapSortable(true, 'reversed');
});
detailRowElement.show();
});
});
</script>
Anything that depends on the HTML being loaded must be done in the callback function, because the first A in AJAX stands for asynchronous.
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html", function() {
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
I'm not really sure what you're trying to do with .html(jquery2), since the argument to .html() is supposed to be a string, not a jQuery object. Maybe you meant:
var jquery2 = $(".jquery2").html();
I'm developing an ajax heavy web app, and would like to have textarea's (with class="ui-richtext") automatically initialize TinyMCE.
This is easy for textarea's that are loaded normally, but how about for content that is loaded AFTER the fact using ajax?
I was thinking something along these lines: (i'm using jquery)
$("textarea.ui-richtext").live("ajaxComplete", function()
{
$(this).tinymce({...});
});
Unfortunately this doesn't seem to work. Any ideas?
This is my first post, let me know if I need to add more info
Live is limited to a small number of events.
You can do something like this though:
$.ajax({
url: 'url/here',
success: function(data){
var $data = $(data).("textarea.ui-richtext").tinymce();
$('#mydiv').append($data);
}
});