Update a div with jQuery [duplicate] - javascript

This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:
page.html:
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('mypage.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('mypage.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<div id="load_tweets"> </div>
</body>
</html>
If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:
http://37.187.90.121:3874/currentsong?sid=1&c=
The output of this source is like this:
Inna - Un Momento
If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?
EDIT1:
ok is a policy problem, how i can resolve it?
EDIT2:+
The proxy php page solution don't work.
I have make this php page:
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong");
?>
But i have this error message:
Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Edit3:
The external service give me a javascript to get the information:
window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('<span title="'+r+'">Unavailable</span>'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++<this.settings.poll_limit)&&setTimeout(this.poll_all,this.settings.poll_frequency)},poll_all:function(){window.centovacast.streaminfo._poll_all()},register:function(e,t,n,r){this.registry[t]||(this.registry[t]={charset:n,mountpoint:r,current_song:"",id:{}});var i=e.match(/^cc_strinfo_([a-z]+)_/);i&&(this.registry[t].id[i[1]]=e)},load:function(){var t=e(this).attr("id");if(typeof t!="string")return;var n=t.replace(/^cc_strinfo_[a-z]+_/,""),r="",i="",s=/_cs-([A-Za-z0-9\-]+)$/,o=s.exec(n);o&&(r=o[1],n=n.replace(s,"")),s=/_mp-([A-Za-z0-9\-]+)$/,o=s.exec(n),o&&(i=o[1],n=n.replace(s,"")),window.centovacast.streaminfo.register(t,n,r,i)},run:function(){e(".cc_streaminfo").each(window.centovacast.streaminfo.load),window.centovacast.streaminfo.poll_all()}}});
You can check it at this link:
http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js
Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.
This script give me an output like:
"Radio Name - Author - Title of song"
and this is a link (if you click on it open another page).
I need to get only "Author - Title of song" with no link. Any idea?
Edit4:
I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var div = document.getElementsByClassName('cc_streaminfo')[0];
document.write("w1" + document.getElementsByClassName('cc_streaminfo')[0]);
document.write("w2" + document.getElementsByClassName('cc_streaminfo')[1]);
document.write("w3" + document.getElementsByClassName('cc_streaminfo')[2]);
var container = document.getElementById ("cc_strinfo_summary_radiowhite");
var spans = div.getElementsByTagName("span");
document.write("il mio script: " + spans[0] + "!");
document.write("il mio script: " + container + "!");
//var first_load =
function firstLoad()
{
$('#load_tweets').load('current_g.php?song=ciao');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('current_g.php?song=' + cc_streaminfo).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<br>
<span id="cc_strinfo_summary_radiowhite" class="cc_streaminfo">sss</span>
<div id="load_tweets"> </div>
</body>
</html>

I think this has something to do with CORS. Basically, unless the webpage at 37.187.90.121 explicitly states that it trusts the sources of the domain under which your website is running, your browser will not make the request.
If you are the owner of 37.187.90.121, you can add custom headers to allow inclusion of your response in other webpages.
Check your javascript console of your browser to get more details.

Using jQuery to get (.load()) the contents from a div on another page ( same domain ) to add to a div on the current page is like :
$("#dividoncurrentpage").load("/otherpage.php #dividonotherpage");
Is this what you need ?

It's because:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
mstaessen has explained on the post above.
The alternative solution is: You can create a file called, for example song.php and add the following code.
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong?sid=1&c=");
?>
And update the script to
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('song.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('song.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>

Its better to use jQuery $.ajax to get the content. Link
By using $.ajax you have many ways to work around this issue like crossDomain or get the result in Json format by setting the dataType that you will receive from the server to JSON or JSONP

Related

Javascript - ajax refreshing a div with an old version of an updated file

I am making a web dashboard and for this I have a javascript function that loops infinitely, updating a particular div at frequent intervals. (it uses ajax/jquery to do this).
I have used a loop with setTimeout:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function updateMain() {
setTimeout(function() {
console.log("updating");
$('#main').load('new-content.php #main', function() {});
updateMain();
}, 3000)
}
updateMain();
</script>
</head>
<body>
<div id="main">
<p>hi there</p>
</div>
</body>
</html>
'new-content.php' is a file that is constantly updated by another part of my program, to show the new content for the dashboard.
it looks something like this:
<div id="main">
<p>Hello i am updated content</p>
</div>
I am sure the loop is working as the "updating" messages appear at regular intervals in the console.
When the program starts, the div is showing "hello there", and in the new-content.php file it has "hello am updated content".
The first time the loop runs, it updates the div to show "hello i am updated content".
But if I further update the new-content.php file, for example to say "hello I am further updated content", it just won't show on my webpage. However I am sure that the loop is still running as the messages appear in console.
It's like ajax has some cached version of the new-content.php file that it loads at the start then keeps using forever.
I am very confused, if you could help me I would be very grateful
Thank you
PS: if it is of relevance, the website is running through flask but I don't think this is the problem.
EDIT: I believe it is actually a flask caching issue
You can try adding a cache buster to see if that helps. Change your code as follows:
function updateMain() {
setTimeout(function() {
console.log("updating");
const cb = new Date().getTime();
$('#main').load('new-content.php?cb=' + cb + '#main',function() {
updateMain();
});
}, 3000)
}
updateMain();
Wasn't able to solve the issue but for anyone who is trying to make a similar project, I decided to use flask-socketio instead which allows me to send data to javascript to be shown on the page, instead of javascript loading the data itself from a file. (the answer by vladtn on this SO post was useful as an introduction to socketio)

How to Parse JSON from a web api in JavaScript

I am trying to parse this HummingBird api with sample url :
http://hummingbird.me/api/v1/search/anime?query=naruto
However, I do not know how to get each id seperately , or each name seperately. For e.g:-
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = //make this display name
</script>
</body>
</html>
I want the demo element to display the title of the first one in the list. Can anyone tell me how I can possibly do this?
If you use jQuery below is the snippet you can use.
var results = "";
$.get("http://hummingbird.me/api/v1/search/anime?query=naruto",function(data){
results = JSON.parse(data);
});
console.log(results);
Download JQuery from here and put the file next to your html.
Add this element between the html tag and the body
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
Replace document.getElementById("demo").innerHTML = with:
$(document).ready(function(){
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null, function (data) {document.getElementById("demo").innerHTML = data[0].title})
})
JQuery is a JS library that makes life easy.
The function below takes 1 function as an argument and executes it after the page has loaded
$(document).ready()
The next function makes an HTTP GET request and parses the response to js object
$.getJSON("http://hummingbird.me/api/v1/search/anime?query=naruto", null,...)
The next function gets the title of the first element of data
function (data) {document.getElementById("demo").innerHTML = data[0].title}
mmm try this fiddle i don't know exactly how you read the file but if you get a string do the JSON.parse(STRING) before.
https://jsfiddle.net/79a1abbL/3/

Get a javascript derived dom-tree element

My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192&currentMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp

How to refresh a div content in JavaScript when the page has not loaded completely?

I have a small web page with a single div whose content needs to be updated periodically. The server sends JavaScript with a function that contains the new data to be updated in the div. Here's the first part of the code that the server sends:
<html>
<head>
<script>
function bar() {
document.getElementById("foo").innerHTML = "0";
}
</script>
</head>
<body onLoad="bar()">
<div id="foo"></div>
</body>
After a delay (2 seconds), the server sends in the remaining code below:
<script type="text/javascript">
function bar() {
document.getElementById("foo").innerHTML = "1";
}
</script>
</script>
</html>
The trouble is that I never see the div show "0" in it - the browser waits until the entire page is loaded, and straightaway displays "1" in the div. How do I get the div to show "0" in it while the server has not sent the entire page?
I am not looking at using any jQuery or AJAX code - please limit your answers to JavaScript only.
You can not use onload -> that gets fired only after the whole page has completely loaded.
Also you have to add some more bytes to the first response, because most browsers only start incremental rendering of the page after a certain ammount of data being received.
This should work:
<html>
<head>
<script>
function bar(x) {
document.getElementById("foo").innerHTML = x;
}
</script>
</head>
<body>
<!-- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA -->
<div id="foo"></div>
<script type="text/javascript">
bar(0);
</script>
</body>
--- DELAY ---
<script type="text/javascript">
bar(1);
</script>
</script>
</html>
Here is a working example in node.js:
var http=require('http');
var server=http.createServer(function(req,res){
res.write('<html><head> <script> function bar(x) { document.getElementById("foo").innerHTML = x; }</script> </head> <body><!-- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA --> <div id="foo"></div><script>bar(0);</script> </body>');
setTimeout(function(){
res.end('<script type="text/javascript"> bar(1); </script></html>');
},2000);
});
server.listen(8080);
it first shows "0" then after 2 seconds "1"
I'm not sure it's possible to do it the way you're trying. The browser will always wait till the page has fully loaded, so it will always wait till you send that second batch.
If you don't want to use AJAX or jQuery, you could try a hacky version to get what you want.
What you can do is specify a callback function on your page to populate the div with a parameter, so something like
callback = function(data) {
document.getElementById('foo').innerHTML = data;
}
Then, you set a timeout on your page to send a request to your server to dynamically load a javascript file that calls that function. So again:
myTimeout = function() {
var script = document.createElement('script');
script.src = "http://myserver.com/mydynamicscript";
document.getElementByTagName('head').appendChild(script);
}
setTimeout(myTimeout, 2000);
The script that you're loading can either be static, or some servlet/php file that returns a javascript file, i.e. it sets it's content-type header to "text/javascript".
In that script, you would then generate this:
callback("whatever I want to put in my div...");
Once that has been loaded, it will call the previous function you declared earlier, and load the content in that div.
It's effectively a hacky form of AJAX, but not AJAX.

Javascript Redirect Timeout

I am trying to start opera from command line and redirect it to a page in 30 seconds. What I'm trying now is:
C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='http://localhost/';}setTimeout('func1()',30000);
Which is returing a page with as content "1". Func1 is never called. Is there a good way to solve this inline? Or should I create a page with this content?
Just found a better solution:
1.) change the command line to:
C:\Programme\Opera\opera.exe -newpage file://localhost/C:/redirect.html
2.) create the file redirect.html with the code for a redirect:
<html>
<head>
<title>Startup</title>
<script>
function redirect()
{
window.location.href = 'http://localhost/startup.php';
}
setTimeout('redirect()',60000);
</script>
</head>
<body>
<p>Loading...</p>
</body>
</html>
Regarding the original example, you should have put void() around the setTimeout() call. setTimeout() returns a timeout identifier (in this case the number 1) which becomes the output of the javascript: URL. Whatever a javascript: URL 'returns' is used as the source for a document.

Categories