I'm trying ajax (and to a degree a lot of js) for the first time so I'm not sure what I'm doing wrong.
The goal is that a series of thumbnails in a sidebar will change the content of a centrally located div when selected. The link currently looks like this:
<img src="images/thumbs/elon-scissors-logo.jpg" onclick="reloadMiddleWith('about','about','test')"/>
When clicked it runs the below function and changes the background and calls a php source.
function reloadMiddleWith(theme, page, content) {
var new_url = "http://www.chrisjohndesigns.com/" + page + ".php/#" + content;
$('#live-area').addClass(theme);
$.ajax({
url: new_url,
dataType: 'html'
})
.done(function(data) {
// Assuming the request returns HTML, replace content
$('#area-loader').html(data);
});
}
I tested that and it worked fine when it was just the background and the new php page, but rather than making 50 pages to call in (and not even trying arrays or databases at the moment for lack of proper understanding) I thought I would just make 1 or 2 new page that repeat the same container style and just call the one I want to display by id tag. Currently when I try it, it just changes the background but does not change the php content.
The jQuery itself has a handy function jQuery(...).load, using it jQuery would handle all the necessary points:
function reloadMiddleWith(theme, page, content) {
var new_url = "http://www.chrisjohndesigns.com/" + page + ".php/#" + content;
$('#live-area').addClass(theme);
jQuery("#area-loader").load(new_url);
}
for more information check documentation page out.
Related
Ok. I am making a website on github using html and javascript. Earlier, I was using a template to make simple, formatted webpages. I got it to work, but it has an annoying bug: the unformatted webpage shows up before the formatted one. I am using the latest version of jquery (2.1.4) hosted from google and the javascript below:
var heading = document.getElementById("heading").innerHTML;
var pghead = document.getElementById("pghead").innerHTML;
var pgtext = document.getElementById("pgtext").innerHTML;
var template = function () {
var tmp = null;
$.ajax({
'async': false,
'dataType': 'html',
'url': "https://jediguy13.github.io/template.html",
'success': function (data) {
tmp = data;
}
});
return tmp.split("derp");
}();
document.write(template[0] + heading + template[1] + pghead + template[2] + pgtext + template[3]);
document.getElementById("heading").innerHTML = "";
document.getElementById("pghead").innerHTML = "";
document.getElementById("pgtext").innerHTML = "";
And here's a sample webpage:
<div id="heading">Test</div>
<div id="pghead">Test</div>
<div id="pgtext">This is some text in the main body of the webpage</div>
As you can see from the 'async': false. line, Jquery is requesting the template webpage at the same time as the main thread. However, there is always a slight delay in the formatting. I'm betting it is because the document.write is called near the end. What is a better way to get the browser to display just the formatted page?
Example page: website
Don't use document.write(). Ever. If you have an HTML snippet, just attach it to the desired node like this:
$("body").html(template[0] + ...);
If the page is originally empty and all the content is loaded with AJAX, then you'll see a white page that then is filled with your code.
In your case it will NOT be empty as I can guess, so you have to clear the HTML immediately after you fetch it:
heading = $("#heading").html();
$("#heading").html("");
This will minimize the original exposure of the HTML.
At this point you may want to fade it in slowly, like this:
$("body").hide();
// ... make AJAX call and attach it as shown above
$("body").fadeIn();
The fadeIn() is a touch of class you might as well replace with show().
Make the AJAX call asynchronous and put all of this into the AJAX success() method.
This is all together in a complete rewrite. Just copy+paste and tell me if it's working:
var heading, pghead, pgtext;
$("body").hide();
heading = $("#heading").html();
pghead = $("#pghead").html();
pgtext = $("#pgtext").html();
$("#heading").html("");
$("#pghead").html("");
$("#pgtext").html("");
$.ajax({
'async': true,
'dataType': 'html',
'url': "https://jediguy13.github.io/template.html",
'success': function (data) {
template = data.split("derp");
$("body").html(template[0] + heading + template[1] + pghead + template[2] + pgtext + template[3]);
$("body").fadeIn();
}
});
Okay, so first off I'm going to say you shouldn't rely on JS to format your entire page unless you're hosting a single-page application, and even then... probably not the entire page.
To answer your question, the only way to not show the unformatted page is to hide your content until the page loads. Give your body tag or container style='display:none;' and then when your JS has finished executing, show the content with by calling something like $('body').show().
one of my favourite tricks is to place a loader div and keep the content hidden and the loader visible until all JS based layout changes are completed. provided you have the luxury of using Jquery (or CSS3) you can use an easing effect on the opacity to give it a much better feel.
Im currently struggling with an AJAX related problem on a website.
The goal is as follows:
There is a "simple" HTML page containing some links and content.
If you click on a link I want to open the file that gets includes with the link (from href) within a new div overlayed to the page. The content from the page is of course loaded with AJAX into the new div (the overlayed one).
Within this new overlayed div I want to add some JS code which in general already works.
The problem anyway is that the DOM elements within the page loaded per AJAX cannot be accessed in a way that is comfortable to work with, in my specific case.
I got following piece of code so far:
$$('.add-exercise').addEvent('click', function(e) {
var request_exercise_add = new Request.HTML({
'method' : 'post',
'url' : e.target.get('href'),
onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I know I can access the elements returned within responseElements but the logic on the included website is somehow quite complex and therefore it should be
possible to add the JS within the HTML code in the dynamically loaded page.
Notice that the JS also cannot be added to the head section because it would not know the elements that are loaded after the dom-ready event.
have you tried iframe ?
or the website that you are trying to add does not have PPP cookie and AllowContentInIframe .. ?
If you want to add the script inside the ajax request you need evalScripts: true and you should remove the quotes around the request options.
$$('.add-exercise').addEvent('click', function (e) {
var request_exercise_add = new Request.HTML({
method: 'post',
url: e.target.get('href'),
evalScripts: true,
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I don't know what is the content of the response but you might also want to use Mootools's .set() instead of innerHTML to append new elements (if you are not doing that yet). Maybe worth to check Dimitar's answer here about that.
I'm working on a website platform that doesn't allow for any server sided scripting, so jquery and javascript are pretty much all I have to work with. I am trying to create a script to work with the site that will update a div that contains an inbox message count every 10 seconds. I've been successful with making the div refresh every ten seconds, but the trouble lies in the page views count. My script is refreshing the whole page and counting for a page view, but I only want to refresh just the one div. An example of the trouble my script causes is when viewing anything on the site that has a page view counter (forum posts, blog posts, ect...), the page views go crazy because of the script refreshing. I'm pretty new to Javascript, so I'm not entirely sure there is a way around this.
What I'm working with is below:
<div id="msgalert" style="display: none"; "width: 100px !important">
You have $inbox_msg_count new messages.
</div>
$inbox_msg_count is a call that grabs the message count, and provided by the platform the site is on. It displays the message count automatically when used.
Then the script that does all the work is this:
<script>
setInterval(function(facepop){
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
}, 1000);
facepop();
</script>
<script>
setInterval(function() {
$("#msgalert").load(location.href+" #msgalert>*","");
}, 1000); // seconds to wait, miliseconds
</script>
I realize I've probably not done the best job of explaining this, but that's because I'm pretty confused in it myself. Like I mentioned previously, this code function just how I want it, but I don't want it to refresh the entire page and rack up the page views. Any help is much appreciated.
You might try to look into iframe and use that as a way to update/refresh your content (div). First setup an iframe, and give it an id, then with JS grab the object and call refresh on it.
well your prob seems a little diff so i think submitting a from within the div might help you so ...
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../member/uploadTempImage',//serverURL
type:'post',
beforeSend:function()
{
alert(" if any operation needed before the ajax call like setting the value or retrieving data from the div ");
},
success:function(e){
alert("this is the response data simply set it inside the div ");
}
});
});
I think this could probably be done without a form, and definitely without iframes (shudder)..
Maybe something like this?
$(document).ready(function()
{
setInterval(function(facepop)
{
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
$.ajax({
type: "POST",
url: location.href,
success: function(msg)
{
$("#msgalert").html(msg);
}
});
},1000);
It's not entirely clear exactly what you're trying to do (or it may just be that I'm ultra tired (it is midnight...)), but the $.ajax() call in the above is the main thing I would suggest.
Encapsulating both functions in a single setInterval() makes things easier to read, and will extinguish the 1 second gap between showing the msgalert element, and "re-loading" it.
I have a div which contains a series of design projects. When the user scrolls to the bottom of the page, the javascript detects this and loads new page content into that div.
You can see the website at
http://www.jb-design.me/marchupdate/
The problem I have is that the new content just pauses then loads below. With no feedback for the user that new content is being loaded etc.
What I would like is a div to appear between the current content and the new content (Where the 'spacer' div normally is on my website. And display a loading gif/png. Which would fade out once the new content has loaded. The new content would then appear below fading in...?
Is this possible at all?
I have tried to implement a 'var pageLoadisloaded' but to no use.
I am literally a newbie and have been trailing the web for a solution for the past couple of days and now I thought I would just ask for help!
Thank you in advance
Javascript code below...
alreadyloading = false;
nextpage = 2;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (alreadyloading == false) {
var url = "page"+nextpage+".html";
alreadyloading = true;
$.post(url, function(data) {
$('#newcontent').children().last().after(data);
alreadyloading = false;
nextpage++;
});
}
}
});
After you set the alreadyloading variable to true, append a bit of html to the end of the div#newcontent which contains an image that indicates that new content is being loading. Use $(window).ScrollTop() to scroll further down to ensure that this is visible. When the content arrives via Ajax, you can remove the little piece of code you added, and append the new stuff.
Alternatively, use 3 div tags as follows:
1) The already loaded content is kept in the first division.
2) When the scroll-bar reaches the bottom, your function is triggered, which calls a jQuery FadeIn effect for the second division which contains the loading image. Scroll down a bit using the aforementioned function to ensure that it is visible.
3) When the content arrives, put it in the third div and then call a simultaneous FadeIn effect for that, and FadeOut effect for the second division.
4) Once the effect is complete, append the contents of the third division to the first one, and reset the third one.
What if you were to have a fixed div to the bottom of the page, and when you were in the conditional to load a new page - you fade it in, and when the new content has been loaded in - you fade it out?
Additional assistance
You could try something like this to check if more pages are available - set this up to run after the first ajax - perhaps in the success part of the function:
var url = "page"+nextpage+".html";
$.ajax({
url: url,
type:'HEAD',
error:
function(){
// No more pages exist - remove loading
$('#loading').remove();
},
success:
function(){
// Good to load another page
}
});
Where I found this:
http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06
I wrote one script which gets an image url through JSONP, and then I needed to write that to browser, this is a status image which is onling.png, offline.png and so on
my script looks like this.
<div id='STATUSDIV'></div>
<script language=javacsript type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
<script type="text/javascript">$(document).ready(function()
{
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(),
function(res)
{
document.getElementById('STATUSDIV').innerHTML = ("<img src='"+res.img+"' />");
});
});
</script>
using this code, I am able to get an image inside div statusdiv, however I can not use same code block twice on single page as both will point to same div.
quick thing I can do is that I can ask end user who will copy this code multiple time on each page to change div id so that that image will load on differnt div.
But I wanted to have same code wherever copied just writes image inline. kind of createelement and write in that element. but thats not working. document.write does not work either as it replaces everything.
Is there a way that when this code block called, Instead of writing innerhtml, code creates a dynamic div right there on the page and writes image in that. and this image writing and creating div happens where script block is called. so that If same script is called in header and footer, status image will appear on both header and footer.
The cleanest way I know of is to create a function for your code that should get included very early in the page so it's available everywhere:
function insertStatusHere() {
var thisId = "status" + insertStatusHere.myDivCntr++;
document.write('<div class="statusContainer" id="' + thisId + '"></div>');
$(document).ready(function() {
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(), function(res) {
document.getElementById(thisId).innerHTML = ("<img src='"+res.img+"' />");
});
});
}
insertStatusHere.myDivCntr = 0;
Then, any place in the page where someone wants a status image, they can put this inline script:
<script type="text/javascript">
insertStatusHere();
</script>
This dynamically inserts a div with a unique div ID at the place that the function call is made and it keeps track of each ID that is used in the closure.