POST to PHP using AJAX and refresh upon change - javascript

I am trying to build a web application that needs to refresh the entire page when there is a change in the database. I would like to achieve this using AJAX and PHP. I would like to POST a single piece of information to the PHP script every 5 seconds and if the returned value from the PHP script is different from a predefined variable, I would like to refresh the entire page.
For example, I have a predefined value in javascript of 200. If the PHP script returns a different value, I would like to refresh the entire page.
I know how to write the PHP, it is just the XJAX I am having issues with. I would also not like to use jquery if possible.
Thanks in advance for any guidance!
EDIT : I would not like to use jquery or any other framework, just raw javascript. I also need to refresh the entire page upon change and run the AJAX every 5 seconds.

Good question. You can do if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") { to check if the PHP-side value has changed. This watchdog method is called very 5 seconds through setInterval. If there is a change, then the page is refreshed via document.location.reload(true) (ref) to prevent reusing the cache.
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 5 seconds
setInterval(function(){ watchdog(); }, 5000);
Note: I chose setInterval over setTimeout because if the connection to the server fails (500-error, timeout, etc.), then the response logic may otherwise fail to trigger another setTimeout. setInterval ensures the server is polled consistently regardless of connection failures.

Your AJAX can be executed every 5 seconds using the setInterval() function.
And you can call to refresh the page from AJAX request completion callback.

Please try below code. I have used javascript setInterval function which will make ajax call every 5 seconds. Now please make efforts to make changes in code as per your requirements and take it further.
<script type="text/javascript" >
var predefined_val = 'test';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"test/test_script.php", //put relative url here, script which will return php
data:{}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
// action you want to perform on value changes.
}
}
});
},5000);// function will run every 5 seconds
}));
</script>

Related

how to fix xmlhttprequest function problem when inserting data

my code works only if i add this code:
document.write(str);
which open a new page and write in it insert data in database
but if i try to the code without it like this :
function addcourse2(str,cn)
{
xmlhttp=new XMLHttpRequest();
//document.write(str);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status == 200) {
alert('response:'+xmlhttp.responseText);
} else {
alert('failure!');
}
};
xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);
xmlhttp.send();
}
here i get alert message failure and nothing gets inserted into database
i need and explanation to this a way to fix it
looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing
add return false;
<button "onclick='addcourse2("value1","value2");return false;'>add course</button>
Let's try to describe.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"
If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.
Also, may be was an other case.

How can i dialog-answer yes or no in PHP and do php code depending on answer? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I figured how i can get a dialog and seems like i need to use javascript but this doesnt let me follow up with php code depending on the answer unless there is a way?
<?php
$ime = "Marko";
echo <<< EOT
<SCRIPT language="JavaScript">
var hi= confirm("Do you really want to deactivate $ime?");
if (hi== true){
<?php ?>
alert("$ime Deactivated!");
// I need to do php code here...
}else{
alert("Skipping $ime");
// I need to do php code here...
}
</SCRIPT>
EOT;
?>
Improving on #papirtiger's answer, you could use AJAX to pass onto the PHP code seamlessly without a page reload.
All AJAX really is is the way you can pass data from javascript to a PHP file. Because PHP is server side, any PHP script that needs to be executed MUST be on the server. PHP generates the script and sends it to the client and the connection between the client and the server is done when the generated page downloads. Javascript can continue its work as it is client side. But since it's on the client's machine, it can't run a PHP script inside it as it can't be interpreted.
AJAX takes data from PHP and sends it like a Form would (using POST or GET variables), executes a separate PHP file on the server, grabs the response from the script and puts it into the javascript without the entire page reloading.
Here is what your script could look like.
<script>
if (window.confirm("Are you sure?")){
// Begin the AJAX function
$.ajax({
// Declare the type (GET or POST)
type = "POST",
// The local server location to the PHP script to get the response from
url = "yes.php",
// Data to send (in this case nothing needs to be sent)
data = "",
// Get the response if a script is executed successfully
success: function(response) {
// Display the response from the script in an alert box
alert(response);
}
)};
} else {
// Rinse and repeat using another file
$.ajax({
type = "POST",
url = "no.php",
data = "",
success: function(response) {
alert(response);
}
)};
}
</script>
You would also need to include the jQuery library in the head of your HTML otherwise this AJAX markdown will not work and you would have to result to traditional (and ugly/messy) pure javascript AJAX executions.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Hope this helps! :)
PHP is a server-side scripting language. You can not trigger it with JavaScript.
#StashCat´s answer is totally correct, however the pattern you are looking for is something like this:
<script>
if (window.confirm("Are you sure")){
window.location("/yes.php");
} else {
window.location("/no.php");
}
</script>
Note that the script that is running will continue until it exits.
The user is then presented with the web page and the confirm box. When they click the yes or no they will be redirected and a new script will be run.
in a nutshell, its not a good solution for languages mix like this. According to a code you have, i can declare a global varaibale with php like <?php <script> var some = "123"; </script> ?> and then use it in client javascript code, but i'll repeat its bad approach. You'd better to refactor your code.
Php code runs on Server, while javascript code runs on client i.e., your browser. So, you can't write code to display a dialog box at server side, But you can dynamically remove and add HTML elements using Ajax. You can code your dialog box in javascript and call an Ajax block. A typical example of Ajax(Ajax--> Async Javascript) code,
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

AJAX wont call its PHP script while another PHP script is running

Scenario:
I have two PHP scripts to be called simultaneously:
First script will run several minutes (PHP based file download), depending on downloaded file size
Second PHP script is supposed to be called within regular intervals to monitor execution of the first script - file progress download. To avoid opening new windows upon script completion, it is called via AJAX.
Problem:
The regularly called AJAX monitoring script is not processed during the execution of the first long running PHP(later download) script. Only if the first script is finished the AJAX called PHP script gets processed.
I spent many hours over this problem. I have simplified my test scripts as much as possible. However, I still can not get the AJAX script working during execution of the main php script. Neither can I obtain intermediary feedback values from the main-download script, in any other way.
Would you be so kind and analyze my code samples please? They have the precise form as I use them now. If possible, would you be so kind and run them in your environment? I suspect the problem can be in my WAMP environment.
PHP Version 5.4.12
Apache/2.4.4 (Win64) PHP/5.4.12
Windows 7 x64
8GB RAM
Code Samples:
JavaScript code calling both PHP scripts:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body onload="callScripts();">
<script type="text/javascript">
// call both PHP scripts(download and monitoring) in desired order
callScripts = function()
{
// run long running (later Download) PHP script
console.log("Calling: PHP/fileDownload.php");
window.location.href = 'PHP/fileDownload.php';
// call the monitoring PHP script multiple times in 2 second intervals
window.setTimeout(function(){startDownloadMonitoring()}, 1000);
window.setTimeout(function(){startDownloadMonitoring()}, 3000);
window.setTimeout(function(){startDownloadMonitoring()}, 5000);
window.setTimeout(function(){startDownloadMonitoring()}, 7000);
window.setTimeout(function(){startDownloadMonitoring()}, 9000);
};
// call monitoring PHP script via AJAX
function startDownloadMonitoring()
{
console.log("Calling startDownloadMonitoring()...");
var xmlhttp;
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)
{
console.log("Response Received: " + xmlhttp.responseText);
}
}
xmlhttp.open("GET", "PHP/fileDownloadStatus.php", true);
xmlhttp.send();
}
</script>
</body>
</html>
PHP Monitoring Script(fileDownloadStatus.php)
<?php
include 'ChromePhp.php';
// start session, update session variable, close session
session_start();
$_SESSION['DownloadProgress']++;
ChromePhp::log('$_SESSION[\'DownloadProgress\'] = ' . $_SESSION['DownloadProgress']);
session_write_close();
echo "success";
?>
PHP long-running script (fileDownload.php)
<?php
include 'ChromePhp.php';
// disable script expiry
set_time_limit(0);
// start session, define variable, close session
session_start();
// prepare session variables
$_SESSION['DownloadProgress'] = 10;
session_write_close();
// execute for 60 seconds
for( $count = 0; $count < 60; $count++)
{
sleep(1);
}
?>
The first script it's not send through ajax:
// run long running (later Download) PHP script
console.log("Calling: PHP/fileDownload.php");
window.location.href = 'PHP/fileDownload.php';
You simply redirect the user to another page, and because you have download headers in php, the file is downloaded in the same page.
You can easily achieve your scope through an iframe. You set the source of that iframe : 'PHP/fileDownload.php' and then simply call your ajax download checker.
Short example:
<iframe src="PHP/fileDownload.php">
<script>
window.setTimeout(function(){startDownloadMonitoring()}, 1000);
window.setTimeout(function(){startDownloadMonitoring()}, 3000);
window.setTimeout(function(){startDownloadMonitoring()}, 5000);
window.setTimeout(function(){startDownloadMonitoring()}, 7000);
window.setTimeout(function(){startDownloadMonitoring()}, 9000);
// .... blah blah
</script>
When you call
window.location.href = 'PHP/fileDownload.php';
the script execution stops (not immediately, see https://stackoverflow.com/a/2536815/2806497).
Are you sure ajax calls to fileDownloadStatus.php are executed ?
A solution would be to call the fileDownloadStatus.php file by an ajax asynchronous call, or maybe to load it into an iframe you put in your page.
Hope that helps.

Autorefresh a .gsp in Grails when a database table changes

What I have:
- A database table called 'orders' that is constantly populated by some java module on the back-end.
- A website running on Grails that displays those orders. More precisely - a list.gsp in the Orders view.
- the list.gsp will display new orders if the refresh button is pressed on the browser.
What I need:
- Some way for the .gsp page on a client to get refreshed automatically when a new order is placed on the database.
- The autorefresh needs only to autorefresh the .gsp page when the client is already in the .gsp page. i.e. if a client is on the show.gsp for a particular order, then no need for autorefresh.
Things I though might help:
option1: Having a grails service that will periodically (every 5sec.) query the database to see if there are any new orders. If there are, then somehow from the .gsp page call again and re-render the .gsp page ??!
- suboption1-1: create and destroy a new connection every 5 sec.
- suboption1-2: create and keep a connection alive ... forever
option2: Have the java module that places the orders call a refreshController thru the web and somehow re-render the .gsp page. i.e. Have the refreshController notify all clients currently in the .gsp page that a refresh is needed.
=================================================================================
Follow up:
How can I call a controller from java script?:
function checkDB()
{
t = setTimeout("com.mypackage.DBChecker.checkdbController.checkAction()", 5000)
}
==================================================================================
Follow up 2:
So I almost got what I wanted working except that I can't figure out how to AJAX back to my list.gsp page only part of itself. I dont want to refresh the whole page, but only a division with id="refresh table". i.e. .
I have the following code at the moment that is not working:
<script type="text/javascript">
function checkDB()
{
var xmlhttp;
var xmlDoc;
var x;
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)
{
xmlDoc=xmlhttp.responseText;
x=xmlDoc.getElementsByTagId("refreshTable");
for (i=0;i<x.length;i++)
{
txt = x[i].childNodes[0].nodeValue;
}
document.getElementById("refreshTable").innerHTML=txt;
}
else
{
}
}
xmlhttp.open("GET","http://localhost:8080/Orderlord/checkdb/checkdb",true);
xmlhttp.send();
}
window.load = checkDB();
</script>
=================================================================
Follow up 3:
I succeed in returning only a partial page through my ajax call by copy/paste the div that i wanted to a separate gsp. I dont know how It is working - it's a bit of a magic to me, but everything works, except for when I try to sort the columns of my table. Then, only that partial gsp is rendered on my browser, without the rest of the initial page resulting, in a simple tabulated text page. Also once I end up in that kind of html page - the autorefresh doesnt work anymore, but as long as I will stay in the checkDB list view, the page will refresh every 5 seconds.
...So , how do I fix my problem
Another thing i cant figure out is how to return True/False from a controller to a javascript function in the gsp and how exactly did you have in mind for me to use it?
And lastly, I am currently using 'window.load = timeDB' inside my tag to call the timer function. I tried using , but for some reason I cant get it to work no matter what. Is there something I should keep in mind when using ?
Very lastly: What can I do to simply refresh part of the gsp every 5 sec?
You could take the approach of setting a timer on the page via javascript. You would then invoke a lightweight ajax call from your gsp page back to your controller that would yield a true/false to indicate if you needed a full refresh. This is a fairly simple approach but you would want to be careful that the back end target of the ajax call is optimized as it will be called every 5 seconds for each user on that page. It also generates quite a bit of traffic.
I might explore the publish subscribe plugins from the earlier answer before falling back to this approach, however I have implemented the simple timer / ajax call (in the java struts world) on a medium size website with pretty good results.
What you're explaining is a typical publish - subscribe model.
There are a few plugins in grails that will help you do this. Look at Atmosphere and cometD for this. Both options provide this kind of pub/sub.
If they feel a little too heavy for what you want, you should checkout Pusher and the associated Grails plugin. It is a little nicer because you can just integrate a javascript library in your gsp page and do the push from the server side whenever an order is created. Feels slightly lighter than the 2 libraries above. It uses HTML5 web sockets.
So the following piece of code in my list.gsp did it for me. I decided that just refreshing the 'div id="myDiv"' under question every 5sec it's good enough, otherwise I would have hit the server every 5 seconds anyway since I am querying the database.
<script type="text/javascript">
function ajaxrefresh()
{
var xmlhttp;
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)
{
//alert("aaaaaaa")
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else
{
//alert("state: "+xmlhttp.readyState)
//alert("status: "+xmlhttp.status)
}
}
xmlhttp.open("GET","http://${localHostAddress}:12080/Orderlord/refresh/refreshactiveorders",true);
xmlhttp.send();
var t=setTimeout(ajaxrefresh,5000);
}
window.load = ajaxrefresh();
</script>

AJAX / ASP - Simple Task But I'm stuck?

I'm trying to do a simple AJAX call to an ASP page, that resets session variables and posts a little message back on completion. I'm doing this purely to learn AJAX.
The example came from W3 Schools website but since applying it to my page, I can't seem to get it to work and it's not producing any errors, which is annoying, because I can't debug it.
This is my JS, which is called when a user hits a button [Clear Form]:
function resetSearchForm()
{
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("notification").innerHTML=xmlhttp.responseText;
document.getElementById('notification').style.visibility = 'visible';
}
}
xmlhttp.open("GET","clearSearchData.asp",true);
xmlhttp.send();
document.searchFrm.searchStr.value='';
document.searchFrm.vertical.checked = true;
document.searchFrm.horizontal.checked = true;
document.getElementById('dateRange').selectedIndex = 0;
document.searchFrm.searchStr.focus();
}
And this is the ASP (clearSearchData.asp) that clears my session variables and writes a message:
Response.Expires = -1
Session("search-str-boolean") = ""
Session("search-str-plain") = ""
Session("date-range") = ""
Session("date-from") = ""
Session("date-to") = ""
Session("specificDate") = ""
Session("peopleStr") = ""
Session("orientation") = ""
Response.Write "Form has been reset"
Can anybody see where I'm going wrong? I have been looking at it for a long time and I just can't see it.
The function itself works because the last part of the function gets processed, the bit that clears the form values... but... the AJAX call doesn't happen because the session variables still contain data and the message doesn't appear.
Many thanks in advance...
UPDATE - - - - - - - - - - -
It now works. The problem was I didn't include the full URL to the ASP page. Thanks for 'thedaian' (below) for pointing that out
Chances are, something is wrong with the page you're trying to get via AJAX. Check what xmlhttp.status is, if it's 404, then you're never going to get to the point where you're printing the AJAX response. Make sure that "clearSearchData.asp" is accessible from the same directory as your javascript. This is a common problem if you have your javascript code in a separate folder from the rest of your site. Or simply put in the full URL path for the "clearSearchData.asp" so it'll definitely work.
Something to point out, the function in xmlhttp.onreadystatechange is (usually) called after it's declared in the code. In this case, it gets called after your search form fields are cleared out and reset.
The ajax call does not automatically send along a session cookie. That means the session you're clearing is not the user's session, but just a session that's been created for that ajax call alone.

Categories

Resources