dynamically loading javascript fails, but innerHTML does - javascript

i've wrote a script in which javascript file and innerHTML refreshes time to time
setInterval(activeload,1000);
function activeload() {
activediv.innerHTML="";
scriptsrc.src="http://localhost/mypro/pro/activeuser.php";
for(i=0;i<=activeuser.length;i++) {
if(activeuser[i]!=null)
activediv.innerHTML+="<p onclick='dial(' " + activeuser[i] +" ' )'> " + activeuser[i] +"</p><br>";
}
scriptsrc.src='';
}
in the above script, innerHTML is modifying, but src attribute of script is not changing...
the js file loaded is
<script src="http://localhost/mypro/pro/activeuser.php" id="scriptsrc" type="application/javascript"></script>
this php file refreshes every 5 secs and is accurate in information.
need some help in loading the javascript perfectly

Although it's not clear to me what you want to do with the array that comes from activeuser.php, it seems like AJAX will be your best bet to bring it in to your page on a regular interval. Here is a basic example of an AJAX call using jQuery:
<script src="jquery-2.1.4.min.js"></script>
<script>
setInterval(function() {
$.ajax("/mypro/pro/activeuser.php").done(function(data) {
console.log(data);
});
}, 5000);
</script>
The way it works is that the $.ajax() call will request activeuser.php from the server. As soon as the file is delivered, the anonymous function inside of .done() will be called. That function has one parameter, which I've named data, that contains the contents of activeuser.php.
AJAX is a very convenient way to request data from the server without reloading the entire current page when the data is delivered to the browser.

Related

Javascript on webpage not changing text

I have the following script at the bottom of my php page, it runs on pageload, but I need it running every 10 seconds. It only runs on page load.
PHP is running.
I've tested this with a countdown from ten, and the script is actually looping, but for some reason not when i integrate this PHP.
Please help.
<script>
var CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
var x = setInterval(function () {
CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
document.getElementById("CurrentTestBranch").innerHTML = CurrentBranch;
CurrentBranch = "";
}, 10000);
</script>
Edit:
The code does display the file contents the first time around. But does not refresh when I make a change and save it.
Your PHP code is run only when the page loads. It generates string literals when it runs. These do not get updated when the interval function gets called repeatedly (because the PHP does not run again).
If you want to get new data from PHP you need to make new HTTP requests.
You could either reload the entire page, or use XMLHttpRequest (or fetch) to call a web service that gives you the data you want (Ajax is a useful search term).
PHP happens before HTML hits the server.
Look up setTimeout() javascript command. What you need to do is get javascript to call another php script, which checks and echoes your value.
Something like this (could be pseudocode, from memory):
setTimeout(function(){
var CurrentBranch = $.get('/url/that/sends/value');
// do something with your value, call a function, whatever
}, 10000);

changing a js file location only when the source-code is showed

i'm trying to change a js file location when a visitor shows the source-code
, depending on that :
javascript functions don't work when the visitor shows the source-code
.
my idea is creating a file , put a javascript code to delete the file , in this situation the file won't be deleted if someone showed the source-code :
$check="$ip-$views-$id";
fopen("$check.txt","w"); //CREATING A FILE
// DELETING THE FILE ABOVE BY JAVASCRIPT , IT WON'T BE DELETED IF SOMEONE ENTERED VIA THE SOURCE-CODE MODE
?>
<div id="countno"></div>
<script type="text/javascript">
$('#countno').load('del.php?name=<?echo $check;?>&location=' + ' #countno');
</script>
<?
if (file_exists("$check.txt")) { //IF SOMEONE SHOWED THE SOURCE CODE
$new_location="fake_location.js";
}
else{
$new_location=$old_location;
}
?>
<script src="<?echo $new_location;?>"></script>
the problem now , is that the file_exists php function shows that the file still exists even though it was already deleted by the javascript code .
the file_exists function was executed before the javascript code !
any help / solution to make that php function check the file after that javascript code ? i know it's kinda impossible but it worth it !
What you are describing is not possible. php is a server side language while javascript is a client side language. Thus, the PHP on your page will always execute before the Javascript on your page executes. There is no way to make your Javascript execute first when you have it this way.
Instead, what you could do is to separate the PHP and Javascript. Have your file_exists check in another page. e.g. check.php.
if (file_exists("$check.txt")) {
echo "fake_location.js";
} else {
echo $old_location;
}
Then use an ajax call to make a request to check.php, and load your other script depending on what check.php outputs.
<script>
$.ajax({
method: "GET",
url: "check.php"
})
.done(function(script) {
$("#check").attr("src", script);
});
</script>
<script id="check"></script>
However, if your goal is to prevent people from figuring out where your javascript is located, it is not possible. Most browsers nowadays can inspect the HTML as it changes. They can see the loaded script without having to load the source separately.

Reloading page with the html received as a result of AJAX call

I am using AJAX calls and getting JSON as response then it is used to perform various operations. However there are times when I will get HTML response instead of AJAX(a full HTML page), in such cases I want to reload the page with the HTML content (as if a redirection happened). I am able to find out whether a response is HTML or JSON, however I am unable to find a way in which I can reload the page with HTML content received as part of response so that user only sees the HTML content received as part of AJAX response.
Here is the code:
function redirectIfHTML(xhr,data){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
// Need to reload the data on current window
}
}
You can nuke and rewrite the entire content of the page using document.write():
document.write("<html><body><p>Hello world!</p></body></html>");
If you want to keep the <head> (and therefore your CSS and so forth) a cleaner solution is to replace the content of the body:
$('body').html("<p>Hello world!</p>");
I would never want to do something like this, but you can use some data-url to solve:
A data-URI with MIME-type text/html + the html you just received:
var myurl = 'data:text/html,' + <HTML HERE>
Then you do:
document.location.href = myurl
(i didn't really try it)

How to (ajax) post and execute response?

we have the following situation:
in default.aspx we have a link:
test.
and the JS code:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
if(data.indexOf("http://")==0)
window.open(data);
else{
var win=window.open();
with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close();
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The callback can first be an url address or 2nd html code that must be executed.
Option 1 fits, but in option 2, a new window will be opened where the code has been written but not executed.
It's clear, since it happens in the stream, it can't be executed. So the question, how can you fix it? Maybe a refresh(), or similar?
Because of the requirement of the customer, the workflow can not be changed, so it must be solved within doPost().
EDIT
The response in case 2 is HTML like this. This part should be executed:
<HTML><HEAD>
<SCRIPT type=text/javascript src="http://code.jquery.com/jquery-latest.js">
</SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready(function() {
do_something...
});
</SCRIPT>
</HEAD>
<BODY>
<FORM>...</FORM>
</BODY>
</HTML>
Please help. Thanks.
In your JS code it should be something like this:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
//if(data.indexOf("http://")==0)
if (data.type!="url") //i will add a data type to my returned json so i can differentiate if its url or html to show on page.
window.open(); // I dont know why this is there. You should
else{
var win=window.open(data.url); //This data.url should spit out the whole page you want in new window. If its external it would be fine. if its internal maybe you can have an Action on one of your controllers that spit it with head body js css etc.
/* with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close(); */ // No need to write data to new window when its all html to be rendered by browser. Why is this a requirement.
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The overall logic is this
You do your ajax call on doPost
Find out if data returned is of type url or anything that need to open in new window
If it is url type it would have a url (check if this is not null or empty or even a valid url) then open a new window with that url. Have a read of W3C window.open for parameters
If you want to open and close it for some reason just do that by keeping the window handle but you can do this on dom ready event of that new window otherwise you might end up closing it before its dom is completely loaded. (someone else might have better way)
If its not url type then you do your usual stuff on this page.
If this does not make sense lets discuss.

How would we use Javascript to create a real-time feed?

I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript

Categories