How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div
Related
Here is the java script :
<script type="text/javascript">
function SendInfo(){
var req;
alert("hello");
var subject=document.libform.txt.value;
var dept=document.libform.dept.value;
var url="Lib.jsp?sub="+subject+"&dept="+dept;
if(window.XMLHttpRequest)
{
req=new XMLHttpRequest();
alert("hello");
}
else
{
req= new ActiveObject("Microsoft.XMLHTTP");
alert("hello");
}
try{
alert("hello");
req.onreadystatechange = getInfo();
req.open("GET",url,true);
req.send();
}catch(Exception e){
alert("hi");
}
}
function getInfo(){
if(req.readyState==4){
var result=req.responseText;
document.getElementById('myDiv').innerHTML=result;
}
}
</script>
</head>
The code for the button is as follows:
button type="button" value="search books" onclick="SendInform()"
what am i doing wrong here?
I see alerts if the function is reduced to this :
function SendInform(){
alert("hello");
var req;
var subject=document.libform.txt.value;
var dept=document.libform.dept.value;
var url="Libservlet.jsp?sub="+subject+"&dept="+dept;
if(window.XMLHttpRequest)
{
req=new XMLHttpRequest();
alert("object created");
}
else
{
req= new ActiveObject("Microsoft.XMLHTTP");
}}
the problem is in the onreadystatechange function
Change:
onclick="SendInform()"
To:
onclick="SendInfo()"
change
function SendInfo(){
to
SendInfo = function(){
and it should work
I recommend you put your sendinfo function in a script on windows load and not add it to your button like you have in your code currently.
Try
Window.onload = function(){
button =. document.getElementById('urbuttonid');
button.onclick = function(){
Sendinfo();
}}
Alternatively, console.log() at various points in ur code to see the point at which error occurs as I current do not fully understand ur code because of the several alerts
its working now :
<script type="text/javascript">
function SendInform(){
alert("hello");
var req;
var subject=document.libform.txt.value;
var dept=document.libform.dept.value;
var url="Libservlet.jsp?sub="+subject+"&dept="+dept;
if(window.XMLHttpRequest)
{
req=new XMLHttpRequest();
alert("object created");
}
else
{
req= new ActiveObject("Microsoft.XMLHTTP");
alert("hello");
}
req.open("GET",url,true);
req.onreadystatechange = function () {
if(req.readyState==4){
alert("in function");
var result=req.responseText;
alert(req.responseText);
document.getElementById('myDiv').innerHTML=result;
}
};
req.send();
}
</script>
I am trying to get HTML source with JavaScript:
Why this does not work?:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function MyGetHTML()
{
$.get("www.example.com/test1.html", function(data){
return data;
});
}
</script>
</head>
<body>
test 30.9.2015
<script>
alert(MyGetHTML());
</script>
</body>
</html>
(Below, i'm assuming that you need to get content from filen IN your source, from the same origin of your page.)
Your code doen't works because the the return of your MyGetHTML method is the get request itself, and the success callback of your request returns the data.
You could do:
function MyGetHTML(){
$.get("www.example.com/test1.html", function(data){
//alert(data);
//or use console.log() instead.
console.log(data);
});
}
And then
MyGetHTML(); //This will log your data after the succesfull request.
Further reading: https://api.jquery.com/jquery.get/
Hint on your use case:
A simple tutorial from Tuts+ on making simple ajax requests.
With pure JS:
load('test.html', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Or with jquery library
$('#container').load('test.html');
Because you're returning to the get not the function itself. Try like this:
function MyGetHTML()
{
var datum = '';
$.get("www.example.com/test1.html", function(data){
datum = data;
});
return datum;
}
I've been trying to add a loading text that would display while an AJAX function is being executed for a long while now, and all of my attempts (which includes using the ajaxStart and ajaxStop, among other things) haven't been working at all. Any help is appreciated!
Here is the webpage that the script in question is located on, if you want to see it in action. The way it works is that you enter in a url and the function will grab the meta tags of that URL.
Meanwhile, here is the relevant HTML, Javascript, and PHP:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Keywords Grabber</title>
<script src="ajax.js"></script>
<script>
function display(content) {
document.getElementById("displaydiv").innerHTML = content;
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var url = document.getElementById("txt1").value;
doAjax("metatags.php", "url=" + url, "display", "post", 0);
}
}
</script>
</head>
<body>
http://<input type="text" id="txt1" value="" />
<input type="button" id="btn1" value="Get Keywords" />
<h3>Keywords Received:</h3>
<div id="displaydiv"></div>
</body>
</html>
JavaScript
function getXMLHttpRequest() {
try {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return new ActiveXObject("Msml2.XMLHTTP");
}
}
catch(e) {
return new XMLHttpRequest();
}
}
function doAjax(url, query, callback, reqtype, getxml) {
var myreq = getXMLHttpRequest();
myreq.onreadystatechange = function () {
if (myreq.readyState == 4) {
if (myreq.status == 200) {
var item = myreq.responseText;
if (getxml == 1) item = myreq.responseXML;
eval(callback + '(item)');
}
}
}
if (reqtype.toUpperCase() == "POST") {
requestPOST(url, query, myreq);
} else {
requestGET(url, query, myreq);
}
}
function requestGET(url, query, req) {
var myRandom = parseInt(Math.random()*99999999);
if (query == '') {
var callUrl = url + '?rand=' + myRandom;
} else {
var callUrl = url + '?' + query + '&rand=' + myRandom;
}
req.open("GET", callUrl, true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(query);
}
PHP
<?php
$tags = #get_meta_tags('http://'.$_REQUEST['url']);
$result = $tags['keywords'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No keywords metatag is available.";
}
?>
something like this
<div id="loading" style="display:none;">loading</div>
Javascript
$('#loading').css('display', 'block');
$.post(url, {}, function(data){
$('#loading').css('display', 'none');
});
I am having some troubles today. I am trying to get Javascript to load content into a <div>. Now, this is my JavaScript source code:
function loadXMLDoc(filename) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
after_load_function(xmlhttp.responseText);
}
}
xmlhttp.open("GET", filename, true);
xmlhttp.send();
}
function after_load_function(responseText) {
document.getElementById("right").innerHTML = responseText;
}
window.onload = function () {
loadXMLDoc("welcome.html");
}
And my div:
<div id="right"></div>
Does anyone know the problem?
Is there any reason you aren't using an abstraction like the JQuery load method?
$( document ).ready(function() {
$("#right").load( "welcome.html" );
})
looks pretty good to me.
Just had a similar issue, here is what I have and it seems to be working really well,
HTML:
<html>
<head>
<title> pageOne </title>
<script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<input class='loadBtn' type='submit' value='Load a Different Page!:'>
<div id="page"></div>
</body>
</html>
JS:
//click function:
$(".loadBtn").click(function(){
//div to hide/replace
$('#page')
//fadeOut div content:
.delay(200).fadeOut('slow')
//load method:
.load
//url #divToReplace
('pageTwo.php #page')
//fadeIn new div content:
.hide().delay(300).fadeIn('slow');
//prevent default browser behavior
return false;
});
I am having a javascript scope issue I want to take the responce text from the ajax call and place it into a global variable. Then process the JSON in another function here is my code.
var JSONDATA = "not gatherd";
var ajaxCalls = (function(){
var ajaxer = {
defaults:{
url:"test.php",
DirectHTML: true,
element:"#ajaxerizer"
},
setup:function(setup){
var defaulLengther = this.defaults
for (var key in defaulLengther)
{
if(setup.hasOwnProperty(key))
{
this.defaults[key] = setup[key];
}
}
if(this.defaults.DirectHTML === false)
{
if (window.XMLHttpRequest) {
this.ajaxRequester = new XMLHttpRequest();
}
if (window.ActiveXObject) {
this.ajaxRequester = new ActiveXObject("Microsoft.XMLHTTP");
}
this.ajaxRequester.open('POST', this.defaults.url, true);
this.ajaxRequester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.ajaxRequester.send();
}
this.callIt();
},
callIt:function(){
if(this.defaults.DirectHTML === true)
{
$(this.defaults.element).load(this.defaults.url);
}
if(this.defaults.DirectHTML === false)
{
this.ajaxRequester.onreadystatechange = function(){
if (this.readyState == 4) {
//This is where I have trouble
alert(this.responseText);
JSONDATA = this.responseText;//This is the data I want to process and use
alert(JSONDATA);
}
}
}
}
}
return ajaxer
})();
Here is the Index
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="simpleHtmlAjax.js"></script>
</head>
<body>
<div id="ajaxerizer">
<script>
ajaxCalls.setup({
url:"json.php",
DirectHTML: false,
});
alert(JSONDATA);
</script>
</div>
</body>
</html>
and the JSON data
<?php
$json = array("one" => 1,"two" => 2,"three" => 3,"four" => 4);
echo json_encode($json);
?>
Thank you for any help.
You're already including jQuery in your HTML, so why not just use jQuery's AJAX helper functions to automatically process the JSON data?
$.post("json.php", function (data) {
// do something with data, which should be a plain JS object:
// {"one":1, "two":2, "three":3, "four":4}
}, "json");