Automatically Enable Submit button at particular time from server using PHP JS - javascript

What I'm looking for is this.
I have a simple PHP page with a submit button that is disabled by default.
I want the submit button to be enabled at a particular time for example 02:00:00
With PHP i can get the time from server with date("h:i:s") which i am using in a JS variable.
like
var time = "<? php echo date("h:i:s") ; ?>" ;
Now by using setInterval() method every millisec i am trying to compare the value of "time" variable with the
particular time i want the button to be enabled.
like if(time=="02:00:00")
{
button.disabled=false;
}
But the problem is "time" variable should also dynamically change to meet the conditions otherwise nothing will happen.I can't get any simple solution.Do i require AJAX for this?
Any help will be appreciated :)
Thanx!

I would update the time variable using JavaScript:
var curTime = new Date();
var firstColon = curTime.toString().indexOf(":");
time = curTime.toString().substring(firstColon-2, firstColon+6)
I'm a Python person, but I think PHP servers work similarly in that when going to a link, a GET request is sent, and then data is sent back, possibly a dynamically created webpage with Python code, but that webpage can't contain any Python or PHP. Those languages are strictly server-side. You could send a request to the server to get the time, but that would be really inefficient and it's better to do this client side then constantly dynamically change the webpage with requests to your PHP server.
Since this is about disabling a button, if the button sends a request to the server, remember to check that the time is right server-side just in case someone tampered with the webpage using their JavaScript console client-side.

Isn't this enable/disable done better at server side? Why do you need to enable the submit button in JavaScript at all? Will it be too bad of a solution to simply inform the user that they cannot submit operation is not available at the moment? They can always refresh the page or come back later to see if it is enabled.
Alternatively, you can simply have an ajax request that periodically pings the server to see if the button can be enabled or not. But know that a savvy user can use Web Inspector tools available in modern browsers to change DOM state. Always validate your operations at the server side. Hope this helps.

Try the following
/* ########## HTML file ######### */
<html>
<head>
</head>
<body onload="timer_function();">
<button type="submit" id="validateIt" style="none">Submit</button>
</body>
<script type="text/javascript">
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//document.getElementById("msg").innerHTML=httpxml.responseText;
//document.getElementById("msg").style.background='#f1f1f1';
}
if(httpxml.responseText == "02:00:00")
{
document.getElementById('validateIt').style.display = 'block';
}
if(httpxml.responseText >= "00:00:00" && httpxml.responseText < "02:00:00"
|| httpxml.responseText >= "02:05:00" && httpxml.responseText < "02:00:00")
{
document.getElementById('validateIt').style.display = 'none';
}
}
var url="server-clock-ckk.php";
url=url+"?sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
tt=timer_function();
}
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
} // Display server time ends
</script>
</html>
/* ########## PHP file server-clock-ckk.php ######### */
<?Php
echo date("H:i:s", time());
?>

Related

onUnload AJAX Post to C# Back-end

I'm limiting the amount of certain pop up windows with a static counter in the back-end of my web form application (C#). I only want to have 1 window open at a time. The back-end counter works fine, however when a user closes the child window I want to reset the counter in the back-end. For that I'm using AJAX with JS (can't use JQuery) and I'm calling that AJAX to make a POST in the back-end in an onUnload event.
I'm using IE 11.
Back-end method I want to call from my JavaScript.
public void DecreaseItem1()
{
int? inspID = convert.ToInt(Request.QueryString["inspid"]);
int? inpID_static = InspectionList.GetWindowInspID();
string path = HttpContext.Current.Request.Url.AbsolutePath;
if (path.Contains("ReadOnlyInspection"))
{
if (inspID != inpID_static)
{
InspectionList.DecreaseCounter();
}
else
{
InspectionList.DecreaseCounter();
InspectionList.SetGetWindowInspID(null);
}
}
From my front-end I'm calling onUnload the DecreaseItem() JavaScript function.
Body tag
<body onUnload="DecreaseItem()" >
JavaScript function:
<script type="text/javascript">
function DecreaseItem() {
var win_loc = "ReadOnlyInspection.aspx/DecreaseItem1";
var xhttp = new XMLHttpRequest();
xhttp.open("POST", win_loc, true);
xhttp.send();
}
</script>
[problem] Counter never gets decreased. Any help or suggestion is greatly appreciated.

call PHP function inside JS [duplicate]

Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.

Getting remote html page fails give me the php code itself instead, how to fix?

Well the problem is simple I need the javascript to get content of remote webpage, because there is no way to do it directly I am doing it from local php file and ajax in the java script just like this
The php file:
"getpage.php?url=http://stackoverflow.com" '
The php code :
<?php
$htm = file_get_contents($_GET['url']);
echo $htm; ?>
This code get content of the html page I direct him too.
The AJAX code :
function makeAJAXObject() {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
return false;
}
}
}
return ajaxRequest;
}
'
And I call him latter in my script like this :
window.ajax = makeAJAXObject();
window.ajax.open("GET","getpage.php"+ queryString, true);
The problem is than I do
alert(window.ajax.responseText);
instead giving me the content of the url I asked him too Its give me the actual php script that I wrote above.
This script works on localhost just fine, but I need it to work form local computer without reuploading to any server, there is away to do it ?
Edit :
The php file is on the pc, I am building a win 8 app , it's not like I have a url or something.
You need to check your remote server configuration to make sure that PHP file are processed by the server. Make sure mod_php is installed in apache and you have the proper AddType to process php files.
See this question: why are my php files showing as plain text?
Also, this is a HUGE security issue, you need to check what is requested and/or whitelist it.
What if I call
getpage.php?url=/etc/passwd
getpage.php?url=/your/secret/file
Because you don't do any checks, you would simply return the results to me ...

How to prevent requests to server every page load

I wanted to know if there is a way to stop Javascript from calling a php every page and populating an array, and instead just carry the array accross all the pages the user browsers.
Currently every page load it makes a new reqest to the server and repopulates the array for example when a user clicks link on a html page.
This is what i have in my JS file:
//Browser Support Code
function call_data(url,data){
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
querystring = "?dta="+data;
AJAX.open("GET", url + querystring, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var statistics = JSON.parse(call_data('user_info.php',userid));//user data
I don't currently see an advantage if its calling every page load, as I might as well do without ... unless theres a way to keep my array set each page load?
You should use HTML5 Local Storage.
You could use the Web Storage / DOM Storage API through JavaScript. It has decent browser support and if you implement it properly you can always fall through to requesting the PHP page if Web Storage is not available.
Here is a tutorial to get you started:
http://www.diveintojavascript.com/tutorials/web-storage-tutorial-creating-an-address-book-application
You can store it in a cookie and check if the value in the cookie is valid, load it from cookie, otherwise request it from the server and save it in the cookie for future use.

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