I would like some content to be loaded into my div on page load, but then I would like to have buttons which will load up new content, and replace the content in the DIV currently.
This is my HTML:
<a id="aboutlink" href="#">About</a>
<a id="infolink" href="#">Info</a>
<div id="contentbox">Starting content</div>
This is my Javascript:
$(document).ready(function(){
$('#aboutlink').click(function(){
$('#contentbox').load('/includes/about-info.html');
});
$('#testlink').click(function(){
$('#contentbox').load('/includes/test-info.html');
});
})
http://jsfiddle.net/spadez/GCg4V/1/
I just wondered what I have done wrong, because when I tried this on my server it didn't load up any content. I was also wondering if there is a better way to achieve something like this, because it doesn't seem like I can do any loading binding to it.
Thank you for any help or advice you can give.
The load method will only set the html of the first matched element if the status is (200 OK).. If it is something other than this, like (404 Not Found) or (403 Forbidden) , then it won't set the html..
To set it regardless of the response, try this jsFiddle I edited.
First try something like this:
$.get('/includes/test-info.html', data, function(data){alert(data);})
And then you'll be able to see exactly what is being returned.
I think its something to do with how you have specified the urls for the load.
Try something like
$(document).ready(function () {
$('#aboutlink').click(function () {
$('#contentbox').load('includes/about-info.html');
});
$('#infolink').click(function () {
$('#contentbox').load('includes/test-info.html');
});
})
without the leading "/"
Okay then run this code to check what happening out there:
<script src="http://code.jquery.com/jquery-latest.min.js"type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#aboutlink').click(function () {
$('#contentbox').load('/includes/about-info.html', function(response, status, xhr){
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
});
$('#infolink').click(function () {
$('#contentbox').load('/includes/test-info.html', function(response, status, xhr){
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
});
})
</script>
<a id="aboutlink" href="#">About</a>
<a id="infolink" href="#">Info</a>
<div id="contentbox">Starting content</div>
<div id="error"></div>
Related
I want to load external url in a div without using iframe/embed/object tag. I already used examples but it is not working
For example:
$("#testDiv").load("//localhost:8000/cities/Mountain%20View/521/bottle-service/new");
or
$("#testDiv").load("//www.xyz.com");
Could anyone please help me fix this issue?
Based on your comment I think you need something like this:
$('#mydiv').load('http://localhost:8000/cities/Mountain%20View/521/bottle-service/new #testDiv', function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
});
For better insight I'm linking this question with this SO post
I'm trying to load the contents of a php file into a script using AJAX with the following code:
<button onclick="changeText3()"><img border='0' alt='More Options' src='tmpls/media/images/icons/cog.png'></button>
<script> function changeText3(){
$("#test").click(function(){
$("#test").load("file.php");
}
}
</script>
<div id='test'>test</div>
Nothing happens when I click anything. I'm brand new to AJAX and am likely missing something simple. I've tried a number of different methods I've seen and I've had no luck.
<button id="showOutput">
<img border='0' alt='More Options' src='tmpls/media/images/icons/cog.png'>
</button>
<script>
$(document).ready(function(){
$("#showOutput").click(function(){
$("#test").load("file.php");
});
});
</script>
<div id='test'>test</div>
Here we can see that as you tried JQuery so I removed JS function and catch JQuery event.
You should try to specify file.php's whole address in your ajax call like this -
$("#test").click(function(){
$("#test").load('url to home.php');
});
If that won't solve the case, you should log a bit more of your ajax response and you'll be able to easily observe and solve it by yourself, like this:
$("#test").load("home.php", function(response, status, xhr) {
if (status == "error") {
console.log(msg + xhr.status + " " + xhr.statusText);
}
});
Check your console for errors.
Corrected your code. You don't need a Event listener, cause you already use onclick="changeText3()"
function changeText3(){
$("#test").load("test.php", function(response, status, xhr) {
if (status == "error") {
console.log(msg + xhr.status + " " + xhr.statusText);
}
});
}
When I run this:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
try {
$("#div1").load("demoddd.txt"); //there is no demoddd.txt
}
catch (err)
{
alert("Error: " + err); //this never runs
}
finally {
alert("Finally");
}
});
});
</script></head>
<body>
<button id="btn">Load file</button>
<div id="div1"></div>
</body>
</html>
I get "Finally" but no error. In the debug console, I see the 404. Can I trap 404 errors when using the load() function?
Use the complete function as shown in the documentation:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
You need to get the httprequest status, you can't catch an 404 with that catch.
Use this:
$("#div1").load("/demoddd.txt", function(responseText, statusText, xhr){
if(statusText == "success")
alert("Successfully loaded!");
if(statusText == "error")
alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
});
The first thing I would try is to set the full URL, and not a relative one. See if that works first.
I have created an html page which renders differently depending on the parameter 'resourceType'.
ResourceType can be IO/CPU/STORAGE etc . I have adopted this design for reusability as we have same layout for all the charts except that the inputs to chart differs based on resourceType.
<script>
require(['../js/viewmodel/db-resource-analyze']);
</script>
<div class="oj-row" id="pageContent">
<div class="topchartRegionDiv">
.....
</div>
</div>
Now I am loading this page from my HOME page which have vertical tabs (like a left side menu)
On click of a tab ,I load my page dynamically using jquery load
window.paramObj =
{
resType: "cpu"
};
$('#cpuContent').load("db-analytics-resources-home.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
The next time user click on IO tab ...i do same operation but with different parameter
window.paramObj =
{
resType: "io"
};
$('#ioContent').load("db-analytics-resources-home.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
The first load happens without any issues , but subsequent load do not happen and page comes as blank.
I am suspecting the page is cached and not loaded. How to enforce reload skipping cache using JQUERY load. Any pointers ?
Try this Stop jQuery .load response from being cached
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
As the guy mentions if the convenience functions like .load, .loadJSON, etc don't do what you need, use the .ajax function and you can find a lot of configuration options in there that will likely do what you need
you can try this methode. this will prevent all caching
$('#ioContent').load("db-analytics-resources-home.html?"+Math.random(), function(){})
Many Thanks for all response . I could get this resolved by passing JS script as parameter to JQUERY load callback and invoking it there on successfully load of html doc .
smthing like this :
$('#' + resType + 'Content').load(url, function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
{
alert("External content loaded successfully!...calling JS");
new self.dbResourceAnalyze();
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
I need to create a javascript function that will write a page based on the url, so basically I am trying to create a javascript function that will check the url, and find the corresponding xml item from there.
The reason behind this is so that the html page can just be duplicated, renamed, and the xml updated, and the page will fill in everything else from the xml sheet.
please let me know whether this is the completely incorrect way to do it, of it there is a better way. thanks!!!
XML CODE::
<!--XML INFORMATION-->
<channel>
<design>
<motion><!--design content-->
<item><!--//////////POST//////////POST//////////POST//////////-->
<tag>/portfolio_dec.html</tag>
<!--RSS INFORMATION-->
<title>Decoze</title>
<link>http://payamrajabi.com/portfoliotest.html</link>
<description><img src="http://payamrajabi.com/thumbs/small_jump.png" title="JUMP!." /></description>
<!--PROJECT CONTENT-->
<project><!--project start-->
<titl>TITLE</titl><!--project title-->
<dsc>PROJECT DESCRIPTION</dsc><!--project description-->
</project><!--project end-->
</item><!--//////////END//////////END//////////END//////////-->
</motion>
</design>
</channel>
JAVASCRIPT:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "code/content9.xml",
dataType: "xml",
success: function(xml) {
var xpathname = window.location.pathname;
var xproject = $(xml).find('tag').text();
if (xpathname == xproject) {
$(xml).find('item').children('tag').text(xpathname).each(function(){
var ttl = $(this).find('titl').text();
$('<p>'+ttl+'</p>').appendTo('h1#ttl');
});
$(xml).find('item').children('tag').text(xpathname).each(function(){
var dsc = $(this).find('dsc').text();
$('<p>'+dsc+'</p>').appendTo('h1#ttl');
});
} else {
PUT ERROR MESSAGE HERE
}
}
});
});
and THE HTML:
<html>
<head>
<script type="text/javascript" src="code/jquery-1.3.1.js"></script>
<script type="text/javascript" src="code/project/project_design.js"></script>
</head>
<body>
<h1 id="ttl"></h1>
<p id="dsc"></p>
</body>
</html>
any help would really be appreciated, i am frairly new to javascript/jquery/xml, and am really having trouble with this. The primary thing I want to do is have an xml file that populates a site, with each item being the content for a new page, in this case of a portfolio item.
cheers!
willem
Hmm... I'm afraid you don't quite understand how jquery works.
Your code should look something like this:
var xpathname = window.location.pathname;
var xitem = $(xml).find('tag:contains(' + xpathname + ')').parent();
if (xproject.length != 0) {
$('#ttl').append('<p>' + xitem.find('titl').text() + '</p>');
$('#dsc').append('<p>' + xitem.find('dsc').text() + '</p>');
}
else {
$('#err').text('The page you requested does not exist');
}
Demo 1
Here's a quick demo. Take a look at the source to see the XML and the JavaScript.
http://jsbin.com/ujiho#itemOne
http://jsbin.com/ujiho#itemTwo
http://jsbin.com/ujiho#itemThree
Demo 2
I've created another demo that uses $.get to retrieve the XML from a separate URL.
http://jsbin.com/aqefo#nov
http://jsbin.com/aqefo#dec
The XML: http://jsbin.com/afiwa
Here's the JavaScript. Let me know if you need help understanding anything.
$(function(){
$.get(
'http://jsbin.com/afiwa',
function(xml){
var hash = window.location.hash.substring(1);
if ($.trim(hash) === '') {
showError();
return;
}
var xitem = $(xml).find('urlname:contains(' + hash + ')').parent();
if (xitem.length != 0) {
$('#ttl').append(xitem.find('titl').text());
$('#dsc').append( xitem.find('dsc').text());
}
else {
showError();
}
function showError() {
$('#err').text('The page you requested does not exist');
}
}
);
});