I have 2 PHP pages called view.php and Operation.php
In view.php I have one execute button which calls the operation.php page at the backend execution - Not redirecting.
In Operation.php I am doing some DB activity.
* For that I am changing the status as In-progress initially
* And changing to Pass/Fail at the end of the page based on the execution.
My question is: Is it possible to refresh the view.php from the Operation.php page once it updates the status as In-progress?
Note: without Ajax and Header method(I don't want to redirect, because
I am not redirected to Operation.php, User is able to see only the
view.php)
EDIT : Below is my code
view.php
echo "<td><a id='execute' href='' onclick='execute_adhoc_prep_page($workflow_id,".$row['Task_Number'].",\"".$row['Script_Name']."\")'>
function execute_adhoc_prep_page(id,tnum,scriptName){
$.ajax({
url: 'view.php', // redirecting to same pages.
method: "POST",
data: {
id: id,
tnum:tnum,
scriptName:scriptName
},
success: function(data) {
console.log(data);
}
});
}
if(isset($_POST['id']) && isset($_POST['tnum']) && isset($_POST['scriptName']) ){
$workflow_id = $_POST['id'];
$taskNum = $_POST['tnum'];
$script = $_POST['scriptName'];
$logfile = fopen("C:\Admin\www\Trigger_next.txt", "w") or die("Unable to open file!");
fwrite($logfile,$workflow_id);
fwrite($logfile,$taskNum);
// using PowerShell via task scheduler I am calling the operation.php script
}
In Operation.php
$myfile = fopen("C:\Admin\www\Trigger_next.txt", "r") or die("Unable to open file!");
if(0 == filesize("C:\Admin\www\xpress\Trigger_next.txt")){
echo "file has NO data";
}else{
echo "file has data";
while (($line = fgets($myfile)) !== false) {
$array[] = $line;
}
fclose($myfile);
}
$workflow_id = $array[0];
$taskNum = $array[1];
// here I am changing the status as I in DB
// And I want to refresh the view.php page
// Once All the activity is completed it will change the status to Pass/Fail
Actually, In my project there is 2 way of calling this Operation.php -> one is Manual execute another one is Automatic (TS) That's why I am doing multiple calls. I know its hard to understand, but please help me to get the way to refresh view.php from operation.php
There is no issue in the code it's updating in the backend, all PS1,TS are working fine, the only thing is I need to refresh the view.php after it is set to in-progress in Operation.php to show it to the user.
Related
This code works. So far, I've only found one exception that breaks it, and it happens only on the live server, on localhost it still works fine all the time.
So, what's the problem.
Basically I generate a PDF file with TCPDF (note that the file is pretty big, over 700 pages) using AJAX and the call returns the link to the file, which I will then append to a modal to let the user choose whether he wants to go to the file, or download it.
This is the AJAX code.
$('#stampa-file').on('submit', function(event)
{
event.preventDefault();
$.ajax({
url:'stampa_file.php?act=stampa',
method: 'POST',
data: $('#stampa-file').serialize(),
success: function(data)
{
if($.trim(data) == 'query_error')
{
alert('Qualcosa è andato storto. Riprova.');
}
else if($.trim(data) == 'stampa_error')
{
alert('Seleziona almeno una sezione');
}
else
{
$('#stampa-file')[0].reset();
$('#loadingModal').modal('hide');
$('#document-link').empty();
$('#document-link-download').empty();
$('#document-link').append('<i class="fas fa-eye"></i> Visualizza PDF');
$('#document-link-download').append('</i> Scarica PDF');
$('#viewFile').modal('show');
}
}
});
});
This is the TCPDF code.
//I generate the PDF above this comment. Below only the link generation, PDF output and save the file into the database.
//Close and output PDF document
$replace = array(" ", "'");
$replacer = array("");
$nome = strtolower($query_ente['nome']);
$now = date("Y_m_d_H_i_s", time());
$link = trim(str_replace($replace, $replacer, 'RDAT_'.$nome.'_'.$now.'.pdf'));
ob_clean();
$pdf -> Output($path_stampa_file.$link,'F');
$output = '';
$timestamp = time();
$result_inserimento = mysqli_query($mysqli, "INSERT INTO files (link, nome, timestamp, categoria) VALUES ('$link', '$link', '$timestamp', 'stampa_rdt')");
if($result_inserimento)
{
/*Registro Attività*/
include 'connessione_multi.php';
session_start();
$user_check = $_SESSION['login_user'];
$result_user_info = mysqli_query($conn, "SELECT * FROM sessioni_login WHERE session_id='$user_check'");
$query_user_info = mysqli_fetch_assoc($result_user_info);
$session_user_id = $query_user_info['id_utente'];
$id_utente = $session_user_id;
$descrizione = 'ha eseguito la stampa del file: '.$link.'';
$timestamp = time();
$indirizzo_ip = $_SERVER['REMOTE_ADDR'];
$result_attivita = mysqli_query($mysqli, "INSERT INTO attivita (id_utente, descrizione, timestamp, indirizzo_ip) VALUES ('$id_utente', '$descrizione', '$timestamp', '$indirizzo_ip')");
$output = $link;
}
else
{
$output = 'query_error';
}
echo $output;
Like I said I have everything working fine, but I can't understand why in just one case, for one customer and only on the live server, not on localhost, it fails. Basically when it fails, what I get in the result of the AJAX call is an empty value and the link in the modal looks like this
www.mysite.com/files/customer_name/
instead of
www.mysite.com/files/customer_name/RDAT_customername_timestamp.pdf
I tried some stuff, but I still can't find a solution.
Things that I tried:
get the link from the database by calling another AJAX request inside the success of the first AJAX call, printed the link in a hidden DIV inside the page and get the link with jQuery .text() and then append it to the modal;
append the link in the "complete" event of the AJAX call instead of "success";
get the link from the database right after it gets saved on the TCPDF generation file, rather than using the same variable $link in the same file;
removed every action in the success event of the AJAX call and only leave the append events;
All of these tests work fine all the time, except for that one time that it fails on the live server.
I really have no other option at this point.
I'm writing an application that sends some data to my server in order to produce a PDF file. To do this I use shell_exec to call on the approapiate latex compilation command. I always show the output of log in the cliente by using the following code in the server(this is oversimpliefied to show the problem):
$log = shell_exec("cd ../../template; pdflatex $texinput;");
$ret["log"] = $log;
echo json_encode($ret);
However every once in a while the log will contain a chararcter that will break the json_encode. That is json_enconde($ret) will be false.
Is there any other way to send the information (as text or maybe as a file) to the client?
EDIT:
Since the output is the output of a Latex compilation it is very difficult to reproduce simply. However, as I've been asked to provide an example, I managed to create this minimal example using the log file (automatically saved by the pdflatex command) and this minimal php script.
This is the PHP script:
$trial = "trial.log";
$handle = fopen($trial,"r");
$data = fread($handle,filesize($trial));
if ($handle === false){
$errors = error_get_last();
$ret["error"] = "Could not open $trial for reading. Type: " . $errors["type"] . " MSG: " . $errors["message"];
return;
}
fclose($handle);
echo "Done reading<br>";
if (json_encode($data) === false){
echo "I've failed";
}
else{
echo "All good";
}
This is the file trial.log
https://www.dropbox.com/s/04ejx5s1mj0ojj2/trial.log?dl=0
I've tested it in my browser and I get the I've failed. However I have bypassed the problem. (See my answer)
So after trying a couple of different things, I went with trying to send the pdflatex generated log file to the client. So instead of returning the contents of the file (which are the same as the contents returned by the command) y returned the path to the log file. Then in my browser I used this code:
// Getting the base URL
var url = window.location.href;
var l = url.length;
while (l--){
if (url[l] == '/') break;
}
url = url.substring(0,l);
// Creating the URL for the log file.
var logfile = url + obj.logfile;
The obj.logfile was the relative path in my server to the log file. Then I used the following to load the file into a text area.
// Loading the log file.
$.ajax({
type: "GET",
url: logfile,
success: function(text) {
document.getElementById("pdflatex_out").value = text;
},
error: function() {
document.getElementById("pdflatex_out").value = "Error. please contact the administrator";
}
});
This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'> </div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?
The context is this:
The user click on a button
The page is refreshed with new information on the page (echo is used to print html code).
A file.txt is created
The download of the created file should start automatically
With the code below, the file is created and the remaining part of the page is presented, but no download starts. Also, if I click on the link, the download doesn't start, but the txt file is opened in the browser (whilst I want to force the download).
On the other hand, if I comment the javascript and uncomment the header instructions, I refresh the correct page and download the txt file, but the content of that file is wrong (it contains the html code echoed in the rest of the page).
=================NOT WORKING CODE==================
echo "
<form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
// more not related stuff
<input type=\"image\" src=\"".JURI::root().
"components/com_comp/images/download_icon.png\" .
"\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
// more not related stuff";
if($_POST['downloadaddresses_x']!=0) {
$myfilename = "tmp/results.txt";
$fh = fopen($myfilename, 'w');
$recipients = $_POST['recipients'];
$semicolon_separated = implode(";", $recipients);
fwrite($fh, $semicolon_separated);
fclose($fh);
/*header('Content-disposition: attachment; filename='.$myfilename);
header("Content-type: application/octet-stream");*/
echo "<a href=\"".$myfilename."\" id=\"downloadlink\">
This download should start automatically!</a>";
echo "<script type=\"text/javascript\">
newwindow=function{
window.open('".$myfilename."','name','height=400,width=200');
if (window.focus) {newwindow.focus()}}
</script>";
}
========================MORE CODE THAT DOES NOT WORK==================
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
Instead of this click simulation code:
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
Can you use this:
<script type="text/javascript">
location.href = document.getElementById('downloadlink').getAttribute('href');
</script>
I have a simple script of code that reads a PHP file and when it get's changed it's supposed to say CHANGED on the page which I will change to refresh the page or change the content. For now, it shows the content, the function repeats once or twice and then it just shows nothing. Any help?
Here is the code:
<?php
$handle = fopen("../chat/real/chatserver.php", "r");
$contents = fread($handle, filesize("../chat/real/chatserver.php"));
fclose($handle);
$newcontents = $contents;
echo $contents;
?>
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("<?php $handle = fopen('../chat/real/chatserver.php', 'r');
$newcontents = fread($handle,filesize('../chat/real/chatserver.php'));fclose($handle);?>");
document.write("<?php if(!($contents==$newcontents)){echo 'Changed';} ?>");
setTimeout('checkchanged()',3000);
}
</script>
Link to example
Thanks for the help
This is because you can't include PHP in your JavaScript in order to execute it by the client. Yes, you can include PHP values, but that's it. Have a look at the source code in your browser:
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("");
document.write("");
setTimeout('checkchanged()',3000);
}
</script>
As you can see, the function document.write gets called with an empty string "". This is because everything that is in <?php ?> gets executed on the server, not on the client, before the resulting page gets sent to the client.
Since every PHP code is parsed only once $contents==$newcontents will be true, so you'll never see Changed.
To achieve something like a chat server you'll need new http request. Have a look at AJAX.