I'm developing a script but I mustn't use jQuery library so I need the equivalent of .load() in JS.
I need to do this without jQuery:
$(document).ready(function(){
$('#a').click(function(){
$('body').append('<div id="b"></div>')
$('#b').load('x.html')
});
});
Thanks!
UPDATE:
Using Fetch API with .then()
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
Old XMLHttpRequest
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
Usage
load("x.html", document.getElementById("b"));
The simple answer is you're doing things that are fairly complicated to get done correctly without a library like jQuery. Here's something that "works", but with no error checking or cross-browser perfection. You really probably don't want this... but here it is.
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('a').addEventListener('click', function (e) {
e.preventDefault();
var div = document.createElement('div');
div.id = 'b';
document.body.appendChild(div);
var xhr = new XMLHttpRequest();
xhr.onload = function () {
div.innerHTML = this.response;
};
xhr.open('GET', 'x.html', true);
xhr.send();
}, false);
}, false);
</script>
</head>
<body>
<a id="a" href="#">load</a>
</body>
</html>
If you want to do it without JS, I think this will help you, add this inside #b
<iframe src="x.html"></iframe>
UPDATE:
Using Fetch API with .then()
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
Old XMLHttpRequest
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
Usage
load("x.html", document.getElementById("b"));
This will load "x.html" and put it inside the element.
<object type="text/html" data="my.html">
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
/* If you wanted post too */
// xmlhttp.open("POST", "/posturl", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// xmlhttp.send("email=" + "value" + "&message=" + "value" + "&name=" + name"value");
xmlhttp.open("GET", "file_to_get.xml", true/* async, setting to false will block other scripts */);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.alert(xmlhttp.responseText);
}
}
I found that jquery load run scripts from loaded file, which setting innerHTML to something doesn't do the trick... don't test if you can call an init() function afterwards...
Related
I use jquery to auto scroll blog post.. They normally works fine but it doesn't scroll or work at all when I load that page via AJAX.. The problem could be how I'm calling ajax to load the page..may be callback function issue which I'm not getting right? here is the ajax code I'm using:
function loadme() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("loadcontent").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://xxxyyy.com/blogs/", true);
xhttp.send();
}
They all work but jquery post auto scroll will not work.. Is that due to callback function? I'm not sure.. Someone suggest or correct the code... Would appreciate volunteered help
Addition
I did alternative callback function but that too doesn't work either..
<div id="loadcontent"> Content to load/replace</div>
<button onclick="loadDoc('http://xxxyyy.com/blogs', myFunction)">Browse
Blogs</button>
//ajax with callback function
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("loadcontent").innerHTML =
xhttp.responseText;
}
Since you have tagged jquery and you also mentioned jquery in your anwser,
I am providing a jquery solution.
//bind click event to the button, set an id for the button to make it just for that particular button
$(button).click(function() {
ajaxRequest("url", loadcontent);
});
// this will be the function for ajax, with the callback as parameter
function ajaxRequest(url, callback) {
$.ajax({
url: url,
method: "get",
success: function (response) {
callback(response);
},
error: function (jqXHR, exception) {
// handle errors
}
});
}
// this will be passed as callback to the ajaxRequest function
//you just need to set the innerHTML and the use animate to scroll to the bottom or to whatever height you would like
function loadcontent(message) {
$("#loadcontent").html(message);
$("#loadcontent").animate ({ scrollTop: $("#container").prop("scrollHeight") }, 10);
}
I'm trying a way to open a page after that I know the page resolution.
I wish to load the correct page on mobiles phone
Here the code which does not work as expected:
<script type="text/javascript">
var width = screen.width;
var height = screen.height;
function loadXMLDoc() {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch(e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","prova.php?width="+width+"&height="+height+"&data="+(Math.random()*1000),true);
xmlhttp.send();
}
window.onload = loadXMLDoc();
</script>
</head>
<body>
<div id="myDIV"></div>
</body>
1. You need to remove the () from loadXMLDoc();
window.onload = loadXMLDoc;
Assigning an event handler using a function like you do, assumes that the function you call returns a function. If you remove the () you replace the event handler with your function.
Alternatively use an anonymous function:
window.onload = function() {
// here is the code you want to execute on load
}
2.
You really need to look at CSS media queries as mentioned by Yani in a comment
I'm using an ajax script to show a loading animation in an iframe while a php script runs. Once the php script finishes running the ajax loading script loads the finished php scripts output.
Update: I have resolved this by replacing:
url='action.php?run=go';
http.open("GET",url, true);
with:
http.open( "GET", "go.php?random=" + Math.random(), true);
I read that IE caches each request and doesn't like sending the requests more than once.
<!DOCTYPE html>
<script type="text/javascript">
document.write('<link rel="stylesheet" href="../css/loading.css" type="text/css" /><div id="loading"><br><center>Please Wait...<br><br><img src="loader.gif"/><center></div>');
//Ajax Function
function getHTTPObject() {
var xmlhttp;
if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
} else {
xmlhttp = false;
}
if (window.XMLHttpRequest) {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction() {
url = 'action.php?run=go';
http.open("GET", url, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
//Change the text when result comes.....
document.getElementById("loading").innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
Try the xmlhttp = new XMLHttpRequest(); stuff before you test for the ActiveXObject. The latter is used for compatibility with older versions of IE (IE 5 & 6 I believe). However, newer versions of IE support the use of the XMLHttpRequest object. You might also try indenting properly to make your code readable.
Additionally, since you mentioned you're new to JS & AJAX, you really should look into using jQuery which makes using AJAX incredibly easy. I personally use jQuery as well as my own AJAX function, so, in practice, what you're doing is perfectly fine. But if you would rather do without the hassle then jQuery is the way to go.
Can you use jQuery? It has all the boiler plating for ajax you need in $.ajax
The data will not display in Chrome, unless i open an IE tab in Chrome go to the site then close it back to Chrome (sorry, if that doesn't make much sense).
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
Im just starting to learn JavaScript so I really don't know much about it.
You should use some modern Javascript library. It guards you from many of those small differences between browsers. I like jQuery.
So, with jquery your code
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
becomes
$(document).load(function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
$.get(url, {}, function(data) {
$('#sales').html(data);
});
});
Shorter, cleaner and works in all browsers!
I think you want to use:
request.onreadystatechange = function() {
instead of:
request.onload = function() {
And change the way you check the return value.
See the asynchronous request code example here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest for more details.
Just find that only the first form tag is removed so you can put an empty form () and the next one is keep in the code.
I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.