I'm trying to use jQuery to load external pages into the current page without the user seeing the page load.
When I call the page 'info.php' it is loaded into the #content div. That's what the script is supposed to do. The problem is that in the main page, which contains the script and the #content div, I already have some code that I want it to be executed when someone visits the page and not to be called from any external page. This is working but when I click on one of the links in the menu, I can't go back to the initial content.
Here is an except of my code:
<script>
$(function() {
$('#nav a').click(function() {
var page = $(this).attr('href');
$('#content').load(page + '.php');
return false;
});
});
</script>
<ul id="nav">
<li>Page1</li>
<li>About</li>
<li>Contact</li>
<li>Info</li>
</ul>
<div id="content">
Here I have some code that I wanted to be attributed to the "Page1"
</div>
I'm not very familiar with load(), but in this case, I think you should be using ajax to load the page without refresh.
var page = $(this).attr('href');
$.ajax({
url: page + '.php',
success: function(data)
{
$('#content').html(data);
}
})
EDIT: with you said "when I click on one of the links in the menu, I can't go back to the initial content", did you mean you have some code within the div #content and onclick you've overwritten its contents?
Here is example:
$(function()
{
var content = $('#content');
$('#nav a').click(function(e) {
e.preventDefault();
var page = $(this).attr('href');
content.children().hide();
var pageContent = content.find("#" + page);
if(pageContent.length > 0)
{
pageContent.show();
}
else // put ajax here
{
content.append($('<div>').attr('id', page).text('New page ' + page));
}
});
});
Demo: jsfiddle.net/3jLjw/
Related
I have some jquery which checks if a particular element is visible on a page and passes a parameter to be appended to the url, so the element can be shown/hidden on the next page.
I want to see if it is possible to store this value in a coldfusion variable and then pass it via the navigation, as this seems to be a more robust method to me.
Here is my basic html:
<nav>
<ul id="mainNav" class="clearfix">
<li>Main</li>
<li>Work</li>
<li>About</li>
<li>News </li>
<li>Blog</li>
</ul>
<ul id="subNav">
<li>Effort, We Cried!</li>
<li>Why Do We Do This</li>
<li>Guests & Hosts</li>
<li>Pretty Girls Doing Horrid Things</li>
</ul>
</nav>
#subNav is set to hidden by default in the css.
I think have some basic jquery to toggle the visibility of the subNav:
var toggleSubNav = (function(){
trigger.on('click',function(){
subNav.toggleClass('visible', function(){
subNavLength = subNav.is(':visible');
});
return false;
});
}());
And then a second function which checks the visibility of the subNav and appends the url:
merge.on('click',function(){
var url = $(this).attr('href');
subNavLength = subNav.is(':visible');
if(subNavLength){
window.location = url + '?subnav=true';
}else{
window.location = url;
}
return false;
});
Finally a function which checks the url for the content of '?subnav=true' to display this on the next page:
var subNavProp = (function(){
if(href.indexOf('?subnav=true') > 0){
subNav.addClass('visible');
}else{
subNav.removeClass('visible');
}
}());
The variable subNavLength is global and gets updated via these various functions.
I realise I am posting an awful lot of jquery and I don't really know how (or if) there is a way to convert this to a backend solution for coldfusion. My thought was that I could toggle a class on the subNav element that is wrapped in a coldfusion if, something like:
<ul id="subNav" class="<cfif var IS true">className</cfif>">
But I am wondering if that still requires something of a Front End solution. Or even if there is another better way to do this?
To be honest, you have a few options, but it's not necessary to involve server-side in this. It's not even beneficial.
One, and probably the route I'd take, is to use a javascript cookie or localStorage to store the setting and that way maintaining clean urls.
Another route is using jQuery something like this.. I'm using a checkbox to toggle the addition, but it can be any variable, such as your subNavLength
I have this example designed to affect urls that begin with /, so that # urls and external urls are safe.
Demo: JSFiddle
$(document).ready(function () {
$(document).on("click","a",function(e) {
// This is just to demonstrate the change without trying to leave
// JSFiddle, you can remove this whole function (a.click)
alert($(this).attr("href"));
e.preventDefault();
});
$(document).on("change","#navChanger",function(e) {
$("a").each(function () {
if($(this).attr("href").charAt(0) == "/") {
if(document.getElementById("navChanger").checked) {
if ($(this).attr("href").split("?").length > 1) {
$(this).attr("href",$(this).attr("href") + "&subnav=true");
} else {
$(this).attr("href",$(this).attr("href") + "?subnav=true");
}
} else {
$(this).attr("href",$(this).attr("href").replace(/.subnav=true$/i,"g"));
}
}
})
});
});
Alternatively, here's how you can use localStorage to achieve a cleaner result, as it doesn't alter urls. Rerun the script to see the change after you click a set-button. (demo)
var defaultOptions = {NavDisplay: true};
var options;
$(document).ready(function () {
options = (JSON.parse(localStorage.getItem("options"))||defaultOptions)
alert("NavDisplay set to: " + options.NavDisplay)
$(document).on("click", '#sFalse', function(e) {
options.NavDisplay = false;
localStorage.setItem("options", JSON.stringify(options))
});
$(document).on("click", '#sTrue', function(e) {
options.NavDisplay = true;
localStorage.setItem("options", JSON.stringify(options))
});
});
I wanted to use ajax to make my website open links without refreshing whole webside (only content in 1 div is changing, header/footer/navigation is always the same).
In header I added js:
<script type="text/javascript" src="js/general.js"></script>
Index.php looks like this:
<?php
include '/gui/header.php';
include '/gui/nawigacja.php';
?>
<div id="content"></div>
<?php include '/gui/footer.php'; ?>
And the general.js looks like this:
$(document).ready(function(e) {
$('#content').load('content/main.php');
$('ul#slider li a').click(function() {
var page = $(this).attr('href');
$('#content').load('content/'+ page + '.php');
return false;
});
$('ul#menu li a').click(function() {
var page = $(this).attr('href');
$('#content').load('content/'+ page + '.php');
return false;
});
});
It worked well on localhost (xampp), but when I wanted to move it to remote free server to tests, the load function didn't work (website didn't won't to load at all, but when I deleted "$('#content').load('content/main.php');" it started to load, but then my ajax didn't load content, because there were no ajax).
Is there any way to solve this problem?
Would be gratefull for any kind of help.
Your JS looks fine, I guess that the URL path is not proper. Make it relative to the root directory by adding / in front of content.
$(document).ready(function(e) {
$('#content').load('/content/main.php');
$('ul#slider li a').click(function() {
var page = $(this).attr('href');
$('#content').load('/content/'+ page + '.php');
return false;
});
$('ul#menu li a').click(function() {
var page = $(this).attr('href');
$('#content').load('/content/'+ page + '.php');
return false;
});
});
Maybe the problem is with cache. ?
Try it:
var d1 = new Date();
var cache = d1.getTime();
$('#content').load('/content/main.php?cache=' + cache);
I am trying to Ajaxify a normal page redirect.
ASPX (View: Parent.aspx):
<a id="GetContent" href="#">Go to Content Page</a>
ASPX (View: Content.aspx):
<div id="content">
...
</div>
Controller (ContentController.cs):
public ActionResult Index(id)
{
var content = _db.GetContent(id);
return View("Content");
}
JS:
$(document).on("click", "#GetContent", function () {
location.href = "/Index/3";
});
I tried this. This works, however, the url in the URL bar does not change.
$(document).on("click", "#GetContent", function () {
$("#content").load("/Index/3");
});
So when you click on the link, currently it posts back normally and then redirects to ~/Content/3 (i.e. no ajax). What I want is to immediately go to the Content page, and then display a loading indicator while the content is being fetched. I know I probably have to use jQuery.load() to do this, but not quite sure how to put things together.
Any help is appreciated!
I think this is what you are looking to do...
Index.aspx:
<div id="content">
...
</div>
<script>
$(document).ready(function() {
$.ajax({
url: '/Content/Details/3', // <-- Can use #Html.ActionLink here, to utilize routing a bit.
success: function(data) {
$('#content').html(data);
}
});
});
</script>
ContentController.cs:
public ActionResult Index(id)
{
return View("Index");
}
public ActionResult Details(id)
{
var content = _db.GetContent(id);
return PartialView("_Details", content);
}
If you put a loader.gif in the div initially I think you'll get the behavior you are looking for. You'll also need to make sure you have the _Details view created, and displaying whatever is in your model (var content).
i would link jquery (through
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
) and then use
var checking = "<img src='ajax-loader.gif'/>";
$("#content").innerHTML=checking
$("#content").load("/content/3");
to load it in the page
I have simple content loader, where I load content of html file into element. That is working fine. But when I load content, then JS in content is not loaded because it is defined in main (index.html) document ready function.
Question:
How to load content where after page refresh it will remain in div?
Note: Prefer JS solution.
HTML:
index.html
<ul id="debug_menu">
<li>content1</li>
<li>content2</li>
<li>content3</li>
</ul>
<div id="zone"></div>
JS:
/* Content loader */
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery('#zone').load('content/' + $content + '.html');
});
});
//Edit:
jQuery(".dial").knob();
content1.html:
<input value="90" class="dial">
Note: using http://anthonyterrien.com/knob/ plugin
try something like this
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery('#zone').load('content/' + $content + '.html', function() {
jQuery(".dial").knob();//initialize new one
});
});
});
jQuery(".dial").knob();
EDITED CODE
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery('#zone').load('content/' + $content + '.html', function() {
initial_loader();//initialize new one
});
});
initial_loader();
});
function initial_loader(){
jQuery(".dial").knob();
}
When you load content, you should also manipulate the current page URL in a way that does not cause a reload. This basically means changing the hash part (#something). On page load, you only have to check the current hash and load the right content.
You can also use the history API with the same logic, it gives you more options to manipulate any part of the URL without a reload. Browser support is not the best yet though, but you can use history.js as a wrapper.
Advantages: both methods will make your content linkable and make the browser history usable (back, forward buttons will work) other than fixing your reload problem.
Not possible. You have to store which div is loaded etc.
Solutions where you can store something:
Cookie
Localstorage
Hashtag
I use this plugin: https://github.com/AlexChittock/JQuery-Session-Plugin
to store content variable into session.
/* Content loader */
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery.session.set('content', $content);
jQuery('#zone').load('content/' + $content + '.html',
function() {
initial_loader();
}
);
});
$s = jQuery.session.get('content');
jQuery('#zone').load('content/' + $s + '.html',
function() {
initial_loader();
}
);
});
function initial_loader() {
jQuery(".dial").knob();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to display jquery page(inside a div) using javascript?
here is my javascript code
function loginPostData(jsonRequest)
{
alert("hello");
$.post("http://localhost:8080/edserve/MobileServlet",
JSON.stringify(jsonRequest),
function(data)
{
var obj = JSON.stringify(data);
alert(obj);
if(data.status=="success")
{
<!--problem lies here-->
$.mobile.changePage( "#mainMenu");
//$('#result').load('index.html#mainMenu');
// . load also give the same result
}
else
{
if(data.message=="user not verified")
{
//display verification page
}
}
}, "json");
}
PROBLEM: the jquery loads the main menu page, but nothing is displayed, untill i refresh the page
just a quick reference of my page
<div data-role="page" id="login">
// other page content
<div id="divrightButton">
<!-- calling loginSubmit which calls loginPostData method/function-->
<a class="bluebutton" href="#" onclick="loginSubmit(); return false;">Login</a>
</div>
</form>
</div>
<!--main page-->
<div data-role="page" id="mainMenu">
Main menu
</div>
i also came to know that there is some issue in jquery with same page transition
https://github.com/jquery/jquery-mobile/issues/2529
but how to fix these issue, i dont have any clue on this node
just in case, i have also tried the following for redirection/loading
$.mobile.changePage("#mainMenu",{allowSamePageTransition: true });
$('#result').load('index.html#mainMenu');
$.mobile.changePage( $("#mainMenu"));
none is working, what i mean is it works but results are same, nothing is displayed
Try Using this Should Work
function loginPostData(jsonRequest)
{
alert("hello");
$.post("http://localhost:8080/edserve/MobileServlet",
JSON.stringify(jsonRequest),
function(data)
{
var obj = JSON.stringify(data);
alert(obj);
if(data.status=="success")
{
$('#mainmenu').children().remove(); //clears div
$('#mainmenu').html(data); //Loads data
}
else
{
if(data.message=="user not verified")
{
//display verification page
}
}
}, "json");
}
try this..
if( data.status == "success" ) {
window.location = 'index.html#mainMenu';
return;
}
After refresh your page only html can run and only display your html not your server responce after refresh your page..And if you want to show your server response on your mainMenu div so you need to use Ajax call and after getting response so you write the code to display data in html..
use this code to redirect/display the particular div element
$.mobile.changePage("#mainMenu",{allowSamePageTransition: true });
and also download following css file, its a must for transitioning between pages/div elements
jquery.mobile.transitions.css