I'm using this code:
<script type='text/javascript'>
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#ajax').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + document.location.hash.replace(/^.*#/, '');
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('slow');
}
});
}
</script>
So I have to use: page to run the ajax ... However, I am using in some places:
Go to some <a href='#1'> notices </ a> for example ... And when you click, instead of just driving to the id = '1 ', is doing the ajax code to run.
How do I add an exception and not when you run the code number in the hash?
If you want to check the existence of a digit in your hash string, you can easily use RegExp.
This way you can create a pattern and check a string :
var pattern = new RegExp(/.*[0-9].*/);
pattern.test(hash); // Will return TRUE if it contains any digit.
You can add an exception by adding a check to see if the hash is an integer or not. See code below. (I've only adjusted the $('a[rel=ajax]') section, the rest of the code is fine as is.)
//Search for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
// test if hash is not an integer
if(parseInt(hash) != hash){
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#ajax').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
}
});
Related
I'm using the following to auto refresh the contents of a div.
$(document).ready(function() {
$("#log").load("test.php?q=" + $('#sq').val());
var refreshId = setInterval(function() {
$("#log").load("test.php?q=" + $('#sq').val());
}, 1000);
$.ajaxSetup({ cache: false });
});
This seems to work fine. I have a text field with the name 'sq' and anything entered in there is searched for by test.php.
My page also has 2 other form fields.
A checkbox and another text field. The checkbox has the id 'chk' and the text field 'txt'.
What I would like to do is change the URL being used by load() if the checkbox is ticked and a value is entered in the text field. Obviously this will also need to include 'sq'.
Can some one point me in the right direction.
The URL with out the check box being ticked is : ( is it is now )
test.php?q=VALUE_FROM_sq
With the checkbox ticked it needs to be :
test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq
Then test.php can use $_REQUEST to get the values passed.
My network box only supports php4 so that does limit me some..
Can some one point me in the right direction. Thanks
Just add some logic in the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
var refreshId = setInterval(LoadLog, 1000);
LoadLog();
});
function LoadLog() {
var sq = $('#sq').val();
var text = $("#txt").val();
var url = "test.php?q=" + encodeURIComponent(sq);
if ($("#chk").is(":checked") && text.length > 0)
url += "&s=1&txt=" + encodeURIComponent(text);
$("#log").load(url);
}
You could save the URL in a separate variable and update it on the changed event of the checkbox.
var url = "test.php?q=VALUE_FROM_sq"
$(document.body).on('change', '#chk', function (event) {
if ($(this).is(':checked')) {
url = "test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq"
} else {
url = "test.php?q=VALUE_FROM_sq"
}
}
on http://zentili.koding.com i've got this javascript that loads the content of the linked menu item inside the main #content div of the index page, and applies an hash with the name of the loaded page minus the '.php', otherwise it loads the hash + '.php' if it's entered in the url. works very good. On other hand, the ENG/ITA entries add ?locale=lang_LANG inside the url, right before the hash, so that localization is also working fine. If you look well, you may notice that when you switch between ENG and ITA, the index-content appears just for one moment before going to the hash. I know this is because the page is first loaded, then taken to the hash but i was wondering if there some way for hiding the homepage and going directly to the hash location when it's loaded.
Here the code for my menu:
<script type="text/javascript">
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#menubar a.item').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php';
$('#content').load(toLoad);
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
}
});
$('#menubar a.item').click(function(){
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
var toLoad = $(this).attr('href');
$('#content').fadeOut('fast',loadContent);
function loadContent() {
$('#content').load(toLoad,'',showNewContent) }
function showNewContent() {
$('#content').fadeIn('fast'); }
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
return false;
});
});
function goENG(){
var hash = window.location.hash;
var eng = '?locale=en_EN';
window.location.replace(eng+hash) ;
};
function goITA(){
var hash = window.location.hash;
var ita = '?locale=it_IT';
window.location.replace(ita+hash) ;
};
</script>
the functions goENG() and goITA() are called via onclick on the ENG and ITA a's. I hope to find some solution into this.
The page cannot directly go to the link. It will load in its natural order and then it will go to the hash. For what you want to achieve, there is a simple solution i believe.
Hide the main content div until the document loads. use css rule "visibility:hidden" for this
If there is any hash, load it and then make the content visible.
If there is no hash in url, make the content visible on dom load.
$(document).ready(function() {
var hash = window.location.hash.substr(1);
if ($('#menubar a.item').length > 0) {
var href = $('#menubar a.item').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php';
$('#content').load(toLoad, function(){
$('#content').attr('visibility', 'visible');
});
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
} else {
$('#content').attr('visibility', 'visible');
}
});
} else {
$('#content').attr('visibility', 'visible');
}
});
--UPDATE--
If you are setting #content as "visibility:hidden"
$('#content').attr('visibility', 'visible');
should always fire, else your #content div will be invisible. The trick here is to set it to visible after we are done with checking for hash. You can keep loading the content in the div and make it visible. Making the #content div visible need not be done after entirely loading the hash.
I am using jquery + the hashchange plugin from ben alman. Below is a standard way to grab the hash name and load in content
$(window).hashchange(function() {
var hash = location.hash;
var array_url = hash.split('#');
var page = $(array_url).last()[0];
$('#content').load( page + '.php', function(){
});
});
But is there any way to do this by grabbing some other variable assigned on a click function or sorted through php, perhaps?
I am working with a multi-artist portfolio site that hands out unique three-four letter codes to images
I'd like to serve these images up through unique urls. This has to be through ajax for many reasons.
I had difficulty adding other ajax history options because this page is already using ajax pagination (to load this content) and lots of htaccess url modrewrites.
I am thinking this might just be impossible.
Here is my current code
$('a.photo').click(function () {
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
return false;
});
$(window).hashchange( function(){
var hash = location.hash;
var url = ( hash.replace( /^#/, '' ) || 'blank' );
document.title = url;
})
$(window).hashchange();
and my html / php :
$thethumb = customuniqueidfunc();
<a href="[IMG URL]"
class="photo gotdesc nohover" rel="<?php echo $row['description'] ?>"
id="<?php echo $thethumb; ?>">
This works insofar as the image from the href attr loads into the #content div and the hash from the id attr is added as a hash to the url and to the title of the page, but I am lacking any mechanism to combine the click and the hashchange function, so that each hash actually corresponds to the image.
One method I've used for this before is to run a hash polling function. You can see it in action at this page:
http://www.webskethio.com/#services
Here is the javascript for that page:
http://www.webskethio.com/ws.js
Relevant code:
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
$(document).ready(function(){
/* code removed for readability */
setInterval('pollHash()',100); // Important piece
/* code removed for readability */
});
and
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
}
[EDIT :] Here is the full code for your page that should work, provided you can create a page that just outputs the image's location from the database.
var recentHash = "";
var image_url ="";
$(document).ready(function() {
$('a.photo').click(function (event) {
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
event.preventDefault();
});
setInterval('pollHash()',100);
});
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
if(pageId != ""){
var temp_url = 'http://whitecu.be/user/mountain/'+pageId+'.html';
$.get(temp_url, function(data) {
image_url = data;
image = new Image();
image.src = image_url;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
});
}else{
window.location = "http://whitecu.be/user/mountain";
}
}
Hey guys. I'm usign a js/ajax script that doesnt work with internet explorer. Firefox its ok.
Btw the head tag, im using this:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "http://pathfofolder/js/loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
The loader.php contain the php code to get pages, something like:
switch($_GET['page']) {
case '#link1' : $page = 'contenthere'; break;
}
echo $page;
So, on the links, i'm using Link 1 to load the content into the div content.
The script does works well with firefox, but with internet explorer it doesnt load the content. Could someone pls help me to fix this?
It not go into the success function at all on IE, and i'm getting no html error from IE too.
Best Regards.
Make sure your html is sounds. FF tends to auto fix the syntax.
Hi I am new to Jquery. I want to add two variables. Both are gloable variables.
Please see the "Add the variables" in the end of this code. The "cashupfirst" variable displays the value corectly but the "cashupsecond" variable says "undefined". But I can display the correct value of "cashupsecond" before this code. Please help.
jQuery(function($) {
var cashupfirst, cashupsecond;
var a, parent, input, doneLink, b, i, eq, c, z;
$(".Cashups").delegate("td:eq(3) > a", "click", function(event) {
//Index reading(not used here)
//var eq = $(this).parent().children("a").index(this);
// The `a` has been clicked; cancel the action as
// we're handling it
event.preventDefault();
event.stopPropagation();
// Remember it and its parent
a = $(this);
parent = a.parent();
// Insert an input in front of it, along with a done link
// because blur can be problematic
input = $("<input type='text' size='10'>");
input.insertBefore(a);
input.blur(doneHandler);
doneLink = $("<a href='#'>done</a>");
doneLink.insertBefore(a);
doneLink.click(doneHandler);
// Put the text of the link in the input
input.val(a.text());
// Temporarily detach the link from the DOM to get it
// out of the way
a.detach();
// Give the input focus, then wait for it to blur
input[0].focus();
// Our "done" handler
function doneHandler() {
// Replace the content of the original link with
// the updated content
a.text(input.val());
cashupfirst = a.text();
alert(cashupfirst);
//Set cookie to pass the text value to update it to table permanently
$.cookie('demoCookie',cashupfirst,{expires: 7, path: '/'});
// Put the link back, remove our input and other link
a.insertBefore(input);
input.remove();
doneLink.remove();
}
});
$(".Cashups").delegate("td:eq(9) > a", "click", function(event) {
// The `a` has been clicked; cancel the action as
// we're handling it
event.preventDefault();
event.stopPropagation();
// Remember it and its parent
a = $(this);
parent = a.parent();
// Insert an input in front of it, along with a done link
// because blur can be problematic
input = $("<input type='text' size='10'>");
input.insertBefore(a);
input.blur(doneHandler);
doneLink = $("<a href='#'>done</a>");
doneLink.insertBefore(a);
doneLink.click(doneHandler);
// Put the text of the link in the input
input.val(a.text());
// Temporarily detach the link from the DOM to get it
// out of the way
a.detach();
// Give the input focus, then wait for it to blur
input[0].focus();
// Our "done" handler
function doneHandler() {
// Replace the content of the original link with
// the updated content
a.text(input.val());
cashupsecond = a.text();
alert(cashupsecond);
//Set cookie to pass the text value to update it to table permanently
$.cookie('demoCookie1',cashupsecond,{expires: 7, path: '/'});
// Put the link back, remove our input and other link
a.insertBefore(input);
input.remove();
doneLink.remove();
}
//Add the variables
if (cashupfirst!= '' && cashupsecond!= '') {
alert(cashupfirst);
alert(cashupsecond);
var xyz = (parseInt(cashupfirst) + parseInt(cashupfirst));
jQuery('td#cashcalculator_total a').html(xyz);
}
});
//alert(cashupsecond);
});
Try
var xyz = parseInt(cashupfirst) + parseInt(cashupsecond);
The alert function does not return what has been alerted.
EDIT:
Okay, I see what's wrong. You must move the adding of the variables to inside the second doneHandler function, otherwise it won't wait until you have received a value for cashupsecond:
// Our "done" handler
function doneHandler() {
...
//Add the variables
if (cashupfirst!= '' && cashupsecond!= '') {
alert(cashupfirst);
alert(cashupsecond);
var xyz = parseInt(cashupfirst) + parseInt(cashupsecond);
jQuery('td#cashcalculator_total a').html(xyz);
}
}
// Don't add the variables here.