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);
}
});
}
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
Very often it is necessary to load contents from files that are stored in server into a Javascript variable or display it in a HTML element in order to accomplish some task inside a webpage.
How can I do that without relying in JQuery?
One of the easiest ways I have found of doing that is by creating a function that gets a file and call's back another function when the download is ready.
So in the example below, when the "test.txt" file content is loaded, it is displayed in a pre element.
<html>
<body>
<pre id="output"></pre>
</body>
<script type="text/javascript">
function get_file(url, callback)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.send();
}
get_file("test.txt", function(response)
{
document.getElementById("output").innerHTML=response;
});
</script>
</html>
IMPORTANT
If you want to make your XMLHttpRequest synchronous, just change the line
xmlhttp.open("GET", url, true);
To
xmlhttp.open("GET", url, false);
But it will come at the expense of hanging your webpage until the data is loaded.
Try using fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
It's much easier to use than XMLHttpRequest.
Then, once you've fetched the resource, use insertAdjacentHtml to add it to the document body: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
i.e.
fetch("test.json")
.then(function(response) {
return response.json();
})
.then(function(json) {
document.body.insertAdjacentHtml("afterbegin", "<p>" + json + "</p>);
});
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
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 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>