Detect page resolution and load specific page - javascript

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

Related

Turning an OnClick Event Into A Timed Event with JavaScript & AJAX

Im currently in the learning process with AJAX & JavaScript..
I have a quick question to the wise..
How can i turn the code below into a timed event instead of an OnClick event.
**For Example i would like to refresh the "showlist" DIV every 5 seconds...
I understand that this is working code and goes against the rules of the site but if i were to post my non working code it would just confuse things as it has me..
I am trying to slowly understand the basics :)
Any guidance would be greatly appreciated
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showlist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>
</html>
You can change loadXMLDoc function to make use of setTimeout. Consider this example:
function loadXMLDoc() {
var xmlhttp,
timer;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("showlist").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.onerror = function() {
clearTimeout(timer);
};
xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
xmlhttp.send();
timer = setTimeout(loadXMLDoc, 5000);
}
Function issues AJAX request and set up a 5s timeout. I also added basic onerror callback to clear timer just in case.
I once made a kind of tv, which automatically changed the 'screen' after 3 seconds.
Maybe you can re-use my code?
// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
if(i > (totalPics - 1)){
i = 0;
}
myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
i++;
loopTimer = setTimeout('loop()',3000);
}
loop();
I hope you can re-use this for your project, and I hope you kind of understand what I mean, if I need to clarify, just ask me :).
So what you need to do, is refresh the array when you got new item in your showlist.
This function (if placed inside the same script tag after your loadXMLDoc fn) will execute and call your function and then itself again every 5 seconds (recursively). You could call setInterval instead, but that runs the risk of occasionally missing a cycle if the js engine is busy:
(function doMeSelf(){
setTimeout(function(){
loadXMLDoc();
doMeSelf();
},5000);
})();
Enclosing the function def inside parens, and then followed by () is called an immediately invoked function expression.
See this question for some background: What do parentheses surrounding a object/function/class declaration mean?

Ajax iframe request only works once in Internet Explorer

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

I need the equivalent of .load() to JS

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...

How do I use ajax to auto refresh a section of page without manually invoking a function within javascript?

var xmlhttp;
//Set up ajax first so he knows which guy to play with
function loadXMLDoc(url,cfunc)
{
//Code to catch modern browsers
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//Code to catch crap browsers
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//Set up
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
//Set a function to deploy when something calls myFunction()
function myFunction()
{
loadXMLDoc("../../../support/ajaxTest.txt",function()
{
//Fires off when button pressed
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText;
setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 );
}
});
}
I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.
function autoRefresh()
{
var url = "../../../support/ajaxTest.txt";
var target = document.getElementById("statusRefresh");
var doRefresh = function()
{
loadXMLDoc(url, function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
target.innerHTML=xmlhttp.responseText;
}
}
});
setInterval( doRefresh, 5000 );
}
and
document.onload = autoRefresh;
more information is needed such as what is your goal, what do you currently have......what are you trying to do......If its a script thats triggered by something from example a user viewing your page or click a button then use that button to triiger the function to auto refresh
Another way is to use a crob job

Parse XML data on page load & insert into div using AJAX / Javascript

I am working on a page that uses javascript / AJAX to parse xml from a file. I need to be able to parse a url on the loading of a page and insert it into a div. I have the script written but I need help getting 2 things:
1) having it parse an XML file and load that data into a div on page load
2) the option to click a link and load that data into the same div instead of what was there when the page loaded.
I am using an external script to do this & embeded a link to it in my page
HTML example to request data:
<div id="rightcolumn">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>
How do I change that to load #1 when the page loads & #2 when a link is clicked?
For the script, do I need anything special at the top to make sure it loads properly? jQuery has $(document).ready(function() {//GUTS}, do I need something similar with AJAX?
My Script
function loadXMLDoc(url){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var anno= xmlhttp.responseXML.documentElement.getElementsByTagName("anno");
// Parser Guts
}
document.getElementById('rightcolumn').innerHTML=txt;
}
}
xmlhttp.open("GET","url",true);
xmlhttp.send();
Usage
<!-- when the user clicks -->
<button onclick="ajax('#ELEMENT','cd_catalog.xml')">Get CD info</button>
// when the page loads
window.onload = function () {
ajax('#ELEMENT', 'cd_catalog.xml');
};
or you can place a script tag at the bottom of the page, or use the dom ready event
Code
function getXmlHttpObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlHttp) {
alert("Your browser does not support AJAX!");
}
return xmlHttp;
}
function ajax(el, url, onSuccess, onError) {
if (typeof el == "string")
el = document.getElementById(el);
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function() {
if (this.readyState === 4) {
// onSuccess
if (this.status === 200 ) {
if (el)
el.innerHTML = this.responseText;
if (typeof onSuccess == 'function')
onSuccess(this.responseText);
}
// onError
else if(typeof onError == 'function') {
onError();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}​

Categories