Manually refresh page from another page, on the same server - javascript

I'm trying to use a code to set a MySQL flag to true from a PHP file (Let's say A). I would like to read this MySQL flag from another PHP file (B), that will be already opened. The question is: Is there any way to manually refresh this (B) page after changing the flag value from the first page (A)?
May be using cron or something similar, I don't really want to refresh page B every X seconds until it reads new flag value.

Use AJAX.
Inside B page create a request function to check the status of MySQL flag. If the flag is set to true, refresh the page.
In HTML of B program insert:
<head>
...
<script>
function enableChecker() {
setInterval( checkFlag, 10000); // Check each ten seconds
}
function checkFlag() {
xmlhttp = GetXmlHttpObject();
if ( xmlhttp==null ) return;
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 ) {
if ( xmlhttp.responseText == "OK" ) {
location.reload(); // Refresh the page
}
}
}
xmlhttp.open( 'GET', 'myCheckProgram.php', true ); // Call php program to check the flag value
xmlhttp.send( null );
return false;
}
</script>
</head>
<body onload="enableChecker()" >
Create a program called myCheckProgram.php
<?php
/* Blah blah to connect with database and query for flag */
$flag = // Result of query
echo $flag ? 'OK' : 'NOK' // Return OK if flag is true
?>

Related

Duplicate JavaScript and php problems

I recently notice that I have a duplicate line on the table, when the device is spinning or calling someone on this davay at the time of pressing the 'save' button. On the lines of UserRealTime I see that the interval is a duplicate of 5-6 milliseconds.
How to avoid duplicates using javascript or jQuery. For example, check the connection of the device to the Internet?
ajax.php
<?php
if (isset($_GET['d1']) && isset($_GET['d2']))
{
$conn=connSQL();
$query = "insert into doorname(d1, d2, UserRealTime) values ('".$_GET['d1']."','".$_GET['d2']."', getdate())";
$rs=$conn->execute($query);
$rs->Close();
$conn->Close();
}
?>
JavaScript
<script>
var httpObject = null;
function getHTTPObject()
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
return null;
}
}
function Inter()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
var d1=document.getElementById('d1').value;
var d2=document.getElementById('d2').value;
if (d1=="" || d2=="")
{
alert("sorry!!!");
}
else
{
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2, true);
httpObject.send(null);
httpObject.onreadystatechange = InterSet;
}
}
}
function InterSet()
{
if(httpObject.readyState == 4)
{
var data=httpObject.responseText;
alert("Good!!!");
}
}
</script>
This way of approach it is not a suggested practice. However, just to work around the problem here is one way of handling general duplicate DB entries.
Generate one random Token on the client side for every successful server side insert. Discard the Token on client side once the server confirms the successful insert. Following is an example:
1) Generate a random Token on the client side, like so
Generate random string/characters in JavaScript
var tokenOnClientSide = makeid();
2) Attach the generated Token to Ajax Params:
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2+"&token="+token, true);
3) Server side: Look if the Token already exists
<?php
if (isset($_GET['d1']) && isset($_GET['d2']) && isset($_GET['token']))
{
$query = sprintf("SELECT * FROM token_table WHERE token = '%s'", $_GET['token']);
$rs=$conn->execute($query);
if (mysql_num_rows($res) == 0) {
// carry on with insert and return success message
.....
// now store the token permanently
$query = "insert into token_table(token, time_of_exec) values ('".$_GET['token']."', getdate())";
$rs=$conn->execute($query);
}
4) Finally, unset the global token on client side
tokenOnClientSide = "";
Hope that one gets a basic idea of handling duplicates.

window.location.reload(true) reloads page but page needs refreshing to show changes

Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.
This is an example that adds the button and reloads page on click
if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li>' . $text . '</li>';
}
So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.
Thanks in advance for your help
EDIT -
I have already tried
location.href = location.href; and
document.location.reload();
ADDITIONAL INFO -
Function
add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
die( __('No post ID specified.') );
}
// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?') );
}
// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
die( __('You are not allowed to edit this item.') );
}
// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));
// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );
$index = array_search($live, $terms);
if ($_REQUEST['value']) {
if ($index === false) {
$terms[] = $live;
}
} else {
if ($index !== false) {
unset($terms[$index]);
}
}
wp_set_object_terms( $post_id, 'live', 'campaign_action' );
die('1');
});
JS
function toggleLive(caller, post_id)
{
var $ = jQuery;
var $caller = $(caller);
var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";
// Check there's no request in progress
if ($caller.text() == waitText) {
return false;
}
// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);
// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);
// Ajax request
var data = {
action: "toggle_live",
post: post_id,
value: value
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
if (response == "1") {
// Success
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
} else {
// Error
alert("Error: " + response);
// Reset the text
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
}
// Reset the width
$caller.width("auto");
});
// Prevent the link click happening
return false;
}
IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR
Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.
Try using Live Query plug-in in jquery instead of live .
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.
I believe #cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

how to check if content txt file has changed

Situation:
I am reading the content of a .txt file with php and with AJAX i load the content into a div. The javascript checks every 5 seconds the .txt file and put the content into the div.
If the content of the .txt file changes, (which i do with a form submit), the content of the div changes automatically after 5 seconds.
For this; i use a checkbox with 3 options:
Status: Available
Status: Busy
Status: Paused
One of the 3 lines above is in the .txt file.
Situation now: every 5 seconds check of the .txt file and every 5 seconds refresh of the div. Is it possible that if the content of the .txt file has not changed, to keep the refresh away?
How can i achieve this?
Below the javascript:
function Ajax()
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 5000);
}
};
$http.open('GET', 'loadtxt.php' + '?' + new Date().getTime(), true);
$http.send(null);
}
}
Loadtxt.php
<?php
//
$file = "status.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 5000) ) {
echo $line;
}
?>
The div:
<script type="text/javascript">
setTimeout(function() {Ajax();}, 5000);
</script>
<div id="ReloadThis">Default text</div>
Calculate the HASH of the file on the server-side have your AJAX check with the for the hash (say a SHA1 or an MD5) - and only update the DIV if the hash has changed since it last looked ?
Maybe this PHP function on the server could help here ?
string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )
Which I found on this link : http://php.net/manual/en/function.hash-file.php
So something like this (I am not in a position to test this; so edits are very welcome here):
filehash.php:
<?php
$file = "status.txt";
echo hash_file( "SHA1", $file, $raw_output=false )
?>
Set up a Javascript variable like 'fileHash':
var fileHash;
populate with an AJAX call to the new PHP script:
[...]
$http.open('GET', 'filehash.php' , true);
newFileHash=$http.responseText;
if (fileHash!=newFileHash) { // file changed - so fetch contents
[...]
// check me here: can we just make use of $http twice here ?
$http.open('GET', 'loadtxt.php' + '?' + new Date().getTime(), true);
// update div.
document.getElementById('ReloadThis').innerHTML =$http.responseText;
fileHash=newFileHash;
}
setTimeout(function(){$self();}, 5000);
[...]
Alternative suggestion:
Your webserver might be able to automatically return a HTTP code to state that the file hasn't changed since it was last requested (by comparing with your browser headers) - with an HTTP 304 for instance:
From Wikipedia:
304 Not Modified
Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or
If-None-Match. This means that there is no need to retransmit the
resource, since the client still has a previously-downloaded copy.
It looks like you have added a timestamp parameter to your GET request - which I presume is prevent your browser caching the old copy of the text file: if you do opt for the method above, you should remove this from your GET request - as this will appear to the webserver that you are asking for a new document each time.

Post Javascript to PHP and then retrieve in another javascript

I m trying to post the value from my java_post.js into php_post.php and then retrieve in another javascript page, index.html. So far i can post the value into the php_post.php and retrieve back into my java_post.js as alert(data)
but i cannot retrieve from my index.html
Java_post.js
var url_link ="index.html";
//On Click Select Function
$("#table_hot").on('click', 'tbody tr',function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
$.post('PHP_post/php_post.php',
{
postvalue:value
},
function(data){
alert(data);
}
);
});
//Window Pop Out Function
function hotspot_pop(url_link){
newwindow = window.open(url_link, '', "status=yes,
height=500; width=500; resizeable=no");
}
The value is retrieve when the client click the selected table and then post into the php_post.php. The php_post.php will filter the result and return to index.html.
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
echo $filtered_students;
So now i m able to retrieve the value and post into as an alert for my java_post.js but the value is no pass into index.html and i receive the error for undefined postvalue.
<html>
<script src="js/jquery-1.11.1.min.js"></script>
<body>
<div id="result"></div>
<script>
var xmlhttp_user = new XMLHttpRequest();
var url_user = "PHP_post/php_post.php";
xmlhttp_user.onreadystatechange=function() {
if (xmlhttp_user.readyState == 4 && xmlhttp_user.status == 200) {
document.getElementById("result").innerHTML=xmlhttp_user.responseText; }
}
xmlhttp_user.open("GET", url_user, true);
xmlhttp_user.send();
</script>
</body>
</html>
So my problem is now, is there any method that allow me to show the value in index.html from php_post.php. As a reminder the alert(data) from java_post.js is just a testing purpose to show the value did post and return from php_post.php
The issue you're having is that when you pass the data into your PHP file and receive the data back in your JavaScript, the information only lasts as long as your current request.
To fix this issue, consider using PHP Session variables to store your data, so that you can retrieve it later.
Example:
// php_post.php
<?php
start_session(); // initializes session for persistent data
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
$_SESSION["filtered_students"] = $filtered_students; // You can now retrieve this in
// Another PHP file
?>
Now in another file (you would switch your HTML file to get from php_get.php):
//php_get.php
<?php
start_session(); // Don't forget to start the session
echo $_SESSION['filtered_students'];
?>
More information here: http://www.w3schools.com/php/php_sessions.asp
You can set the desired value into PHP session while at php_post.php.
This way, you can retrieve the session's value on any page you desire.

Categories

Resources