Javascript only works when javascript console is open on chrome - javascript

I have a script (javascript) that works in firefox but not in chrome or IE. I opened chromes debug console to find the problem. No errors are reported and the code works perfectly. Running it again with the console closed does not work again.
I verified that the version of the script is correct (not old and cached). The console does not report any warnings or errors.
I tried putting in simple logging that writes to a div at the bottom of the page - no information.
(in the debug console it works - including logging info in the div).
The function is the callback after an XMLHttpRequest is made to the server.
I verified that the php script is called by including error_log calls. The error_log shows the return value correctly. A page refresh also show the row has been deleted.
It appears as if the function removeRow() is never called unless the console is open. (method or reserved words conflict??) Tried changing the function name to delRow (including callback) - still not working.
All other Ajax calls seem to work fine.
A Code snippet follows:
var pos = 0;
var xhr;
function eraseRow() {
var myImage = this;
var fullid = myImage.id;
// split row no and record id eg 5_1223 => row=5 and recordid=1223
var idComponents = fullid.split("_");
if (idComponents.length > 1) { // check if image has complete row info
rowid = idComponents[1]; // extract row number from id
pos = parseInt(idComponents[0]);
xhr = new XMLHttpRequest(); // only support IE8 or +
xhr.onreadystatechange = removeRow;
xhr.open("GET","valid_del.php$delrow="+rowid;
xhr.send(null);
}
}
function removeRow() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var err = document.getElementById("errormsg");
var str = xhr.responseText;
err.innerHTML = "Server returned "+str;
if (str === "go-ahead") {
var table = document.getElementById("tableid");
table.deleteRow(pos);
}
}
}
}
PHP (valid_del.php):
<?php
include(funclib.php);
if (isset($_GET['delrow']) && strlen($_GET['delrow'] > 0) {
$recid = $_GET['delrow'];
$db = createDbConn(); // function that connects to mysql server db
$result = $db->query("delete from doclibrary where doc_id='$recid'");
if ($result===true) {
echo 'go-ahead';
error_log('Script successful - returns go-ahead',0);
} else {
echo 'stop';
error_log('Script not successful - returns stop',0);
}
$db->close();
} else {
echo 'stop';
error_log('Script not given record id - returns stop',0);
}
?>

I think the DOM is not ready, try to add your code calls into window.onload, or in $(document).ready if you are using JQuery.

Related

Calling Powershell script from PHP is not working

I need to use a powershell script within my PHP code. Javascript code calls a PHP file and waits for the response, the PHP code calls my powershell script and returns a value.
This works fine when I run PHP alone which calls powershell script.
This also works fine when I simply print a value in runpm.php commenting shell_exec() command. So I assume the problem is with the Shell_exec() command. Any help would be really appreciated. Thanks in Advance.
javascript code:
var myLink = document.getElementById('btn');
var php_var = "<?php echo $dest_path; ?>";
myLink.onclick = function(){
try{
var pingtext = document.getElementById('ping');
var ping = document.getElementById('btn');
ping.style.backgroundColor = "#5bc0de";
ping.style.visibility='hidden';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == 1) {
alert(this.responseText);
ping.style.visibility='visible';
ping.style.backgroundColor = "green";
ping.innerHTML='Import Success' ;
ping.style.width='80px';
ping.style.marginLeft='10%';
pingtext.innerHTML = '';
} else {
alert("error");
ping.style.visibility='visible';
ping.style.display='block';
ping.style.backgroundColor = "red";
ping.innerHTML='Failed' ;
ping.style.width='80px';
ping.style.marginLeft='25%';
pingtext.innerHTML = '';
}
}
};
pingtext.innerHTML = "<img src=\"gentel/production/images/loadingspinner.gif\" width=\"30px\">";
xmlhttp.open("Get", "runpm.php", true);
xmlhttp.send();
}catch(e){
console.error(e);
}
runpm.php:
<?php
$psoutput = shell_exec('powershell -ExecutionPolicy Bypass -NoProfile -File "C:\inetpub\wwwroot\retailPlanning\testpsscript.ps1"');
echo "$psoutput"
?>
testpsscript.ps1:
cls
echo "1"
What the web server do you use?
If it is Apache, you can try to run this service as non-default user. To do it go to services.msc, find Apache service, click Properties, find Log On tab and set some other account (username and password). Do not forget to restart service.
If it is not Apache, you can try to do similar steps with any other web server.

How to receive data continuously and update HTML table?

I am new to Web Development. I'm creating a web application where I need to use ZMQ Library for receiving data continuously and update a html table in real-time.
I tried a lot and just succeeded in receiving a single data packet. Later I'm calling the function recursively to get all data packets. But, by the time I call the function, I already lost some packets in the gap.
Following is the javascript function I'm using in index.php and test.php for receiving data using ZMQ:
Javascript function inside index.php
function samp(result)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var x=document.getElementById('PageTable');
var rowCount = document.getElementById("PageTable").rows.length;
for (var i = 0; i < rowCount; i++)
{
if(x.rows[i].cells[2].innerHTML == xmlhttp.responseText)
{
x.rows[i].cells[3].innerHTML=xmlhttp.responseText;
}
}
samp(result);
}
};
xmlhttp.open("GET","test.php?q="+result,true);
xmlhttp.send();
}
test.php for receiving data using ZMQ
<?php
$Params = $_REQUEST["q"];
$context = new ZMQContext();
$subscriber = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$subscriber->connect("tcp://localhost:5000");
$mnemonic = explode(" ", $Params);
foreach ($mnemonic as $value)
{
if($value!="")
{
$subscriber->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, $value);
}
}
$contents = $subscriber->recv();
echo $contents;
I even tried running the php script inside the javascript function but had no luck. I also tried using an infinite loop in test.php to receive data as following but now as the loop is not ended I stopped receiving even a single packet.
while(true)
{
$contents = $subscriber->recv();
echo $contents;
}
Any help to solve this problem or even suggestion to any different approach is highly appreciated. Thank you.

AjaxChat: Image Upload code hangs, freezes browser, crashes server

This is a tangent from the question here:
Returning value to Javascript from PHP called from XMLHttpRequest
I am adding an "image upload" button to my AjaxChat. I am using an XMLHttpRequest to send the image to the server, where I run a PHP script to move it to my images folder. Below is the Javascript function in charge of opening the XMLHttpRequest connection and sending the file:
function uploadImage() {
var form = document.getElementById('fileSelectForm');
var photo = document.getElementById('photo');
var uploadButton = document.getElementById('imageUploadButton');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text
uploadButton.innerHTML = 'Uploading...';
//Get selected files from input
var files = photo.files;
// Create a new FormData object
var formData = new FormData();
// Loop through selected files
for (var i = 0; files.length > i; i++) {
var file = files[i];
// Check file type; only images are allowed
if (!file.type.match('image/*')) {
continue;
}
// Add file to request
formData.append('photo', file, file.name);
}
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
var result = xhr.responseText;
ajaxChat.insertText('\n\[img\]http:\/\/www.mysite.com\/images' + result + '\[\/img\]');
ajaxChat.sendMessage();
} else {
alert('An error occurred!');
}
form.reset();
};
// Send data
xhr.send(formData);
}
}
Here is upload.php:
<?php
$valid_file = true;
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = $new_file_name;
exit("$message");
}
}
}
?>
I currently have the multiple image upload disabled, so the "Loop through selected files" only executes once.
The upload worked for a little bit on my PC, but then I tried uploading an image from my phone. When I did so, the entire server (and my browser) crashed, presumably due to an infinite loop somewhere. Every time I close my browser and log back in, or restart the server, or restart my computer, it hangs and eventually crashes again (on my PC or on my phone). I have been unable to find the script that is causing the issue. I get the feeling it's right under my nose. Does anyone see the problem? If you need the HTML form code then I can provide that, but I don't think it's necessary.

Check the status of a file move by comparing directory sizes

i'm trying to use PHP to move some files, as it does that I have a script which will compare the source location with the destination location and work out the difference.
It all starts with a button like so:
<input type="button" class="upload_button" onClick="upload_images('drive_<?=$x["letter"]?>');start_upload_progress()" value="<?=$x["name"]?>"/>
This then starts these two scripts:
function upload_images(x) {
var url = "http://localhost:1234/ppa/php/process_upload.php?x="+x
doc("upload_iframe").src = url;
}
First of all it will change a hidden iframe url to the PHP script and send over the drive letter.
function start_upload_progress() {
upload_progress("http://localhost:1234/ppa/php/upload_progress.php",function() {
doc("upload_bar").innerHTML = this;
if(this != 100) {
//doc("upload_bar").innerHTML = x;
setTimeout(start_upload_progress(),1000);
}
});
}
Next the above script will start, the console.log is simply for me to see if it's working, although I do not see "start" in my console. This function uses a callback, the below code simply loads a PHP script and returns the result. If the result is less than 100 then the call is made again every couple of seconds.
function upload_progress(url, callback) {
var http = getHTTPObject();
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
if (http.responseText == "true") {
//window.location.replace("http://localhost:1234/ppa/rotate.php");
}
callback.call(http.responseText);
}
};
http.open("GET", url, true);
http.send();
}
Below is the PHP script, this was working when I set the $_SESSION['tmp'] variable manually.
<?php
session_start();
//If session has been created then ready to start progress bar
if (isset($_SESSION['tmp'])) {
if ($_SESSION['tmp'] != "true") {
$session_date = str_replace("/","",$_SESSION['session_date']);
$tmp = explode("_", $_SESSION['tmp']);
$upload_number = $tmp[1];
$drive = $tmp[0];
//get paths
$destination = $_SESSION['ROOT_PATH']."data/images/".str_replace("/","",$_SESSION['session_date'])."/".$upload_number."/";
$source = $drive.":/DCIM/";
if (is_dir($destination) && is_dir($source)) {
$source_size = foldersize($source);
$destination_size = foldersize($destination);
echo "Percentage: ".floor(($destination_size / $source_size * 100));
}
} else {
echo "done: ".$_SESSION['tmp'];
}
}
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/'). '/';
foreach($files as $t) {
if ($t<>"." && $t<>"..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
}
else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
?>
The $_SESSION['tmp'] variable is created just before the files begin to move, it seems like I can't access this session variable until the code has finish executing...
It is created here, at the top of the file moving script:
if (isset($drive)) {
$x = explode("_", $drive);
$x = $x[1];
//Check if connected file exists
if(file_exists($x.":/connected.txt")) {
$file = file_get_contents($x.":/connected.txt");
if ($file != false) {
$file_code = split(":", $file);
//Check if the file has the correct pass code
if($file_code[0] == $code) {
$_SESSION['tmp'] = $x."_".$drive;
When the files have finished moving the variable is set to "true", which seems to be the only value I can get...
Any ideas why my "start_upload_progress" function is not working? The console.log isn't running and I don't think the $_SESSION['tmp'] variable is setting until the file moving script has finished.
Edit 2:
I have got the script running, it compares the source and the destination and updated the innerHTML of the div with the difference. Only issue is that it only seems to work when I move the files from one place to the other manually.
The upload_progress script seems to freeze whilst the files are being moved, it should run at the same time to check the progress.
I have watched the files disappear from the source folder as well but all at the same time, shouldn't they move one by one as the scripting is only moving them one by one...

Jquery if statement not working even if the statement is true

I have a simple if statement where when i send this certain data to the database, i want the php code to send bake a code that tells javascript its ok to continue, but if the php script sends back a bad code, javascript is to now move forward and display a certain text or something.
The php code works fine but for some reason my javascript files would not work at all.
My javascript is suppose to ajax request to parse.php and receive the data that parse.php sends back to it, if parse.php says 200 its suppose to load in specific items.
Here is the code for one of my systems:
$(document).ready(function(){
$("#chatForm").submit(function(){
var chatHash = $("#chatHash").val();
var body = $("#chatPoster").val();
var by = $("#userBy").val();
if(chatHash != "" && body != ""){
$.post('parse.php',{chatHash: chatHash, body: body, userBy: by},function(data){
if(data == "200"){ // Right here is where its messing up
$("#chatPoster").val("");
$.get('getChatMessages.php?hash=' + chatHash,function(data2){
$(".allMsgs").html(data2);
});
} else {
alert('Critical error');
}
});
} else {
alert('Error');
}
});
});
Here is the code for the parse.php page:
$chat = new ChatSystem;
if(isset($_POST['chatHash']) && isset($_POST['body']) && isset($_POST['userBy'])){
$chat->sendMessage($_POST['userBy'],$_POST['chatHash'],$_POST['body']);
}
Here is the code from the class ChatSystem that the parse.php page is referring to:
public function sendMessage($user,$hash,$body){
global $db;
$date = date("Y-m-d");
$time = date("H:i:s");
$timestamp = "$date $time";
if(empty($user) == false && empty($hash) == false){
$db->query("INSERT INTO chat_messages VALUES('','$user','$body','$timestamp','','0','$hash')") or die("error");
echo '200';
}
}
Even though my php code works perfectly the javascript still messes up. My php code sends back 200 like i ask it to but yet the jquery messes it up
Have a look here, http://api.jquery.com/jquery.post/.
You need a second parameter to the success callback function to be able to catch the response status code.
I.E. function(data,statusCode){ // check the status code here}

Categories