Saving html file by POST only works once - php

I have a html page (database.html) that contains a table you can edit via javascript. The following PHP script is used for saving the the page.
The PHP script saves the updated version of database.html and redirects to the new version (same file).
The problem is that it doesn't work the second time you press save, only the first time.
Any ideas what the problem can be?
HTML:
<!DOCTYPE html><head>
<title>Database</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
#textarea_database {
display:none;
}
</style>
<script src="js.js"></script>
</head>
<body>
<a id="a_save" href="#">Save</a>
<form id="form_database" method="post" action="save.php">
<textarea id="textarea_database" name="textarea_database"></textarea>
</form>
<div id="contenteditable" contenteditable="true">
Write something and press save...
</div>
</body>
JavaScript:
window.onload = function () {
var a_save = document.getElementById('a_save'),
form_database = document.getElementById('form_database'),
textarea_database = document.getElementById('textarea_database');
a_save.onclick = function () {
textarea_database.value = document.documentElement.innerHTML;
form_database.submit();
}
}
PHP:
<?php
// the textarea contain all th html
$textarea_database = $_POST["textarea_database"];
// add doctype since javascript document.documentElement.innerHTML dont get it
$textarea_database = '<!DOCTYPE html>' . $textarea_database;
// update the html database file
$open_database = fopen('database.html','w+');
fputs($open_database,$textarea_database);
fclose($open_database);
// redirect to the uppdated database (timestamp prevent browser cache)
$the_time = date('Y-m-d-H-i-s');
$url_and_time = "database.html?" . $the_time;
header("Location: $url_and_time ");
exit;
?>

Related

Should I make the Apache2 Server treat/see/parse .html files as .php files or not?

I've recently started trying to use PHP.
I've installed a Apache2 Server with PHP 7.2 on Linux Mint 19.1.
Then I've added: AddType application/x-httpd-php .html .htm to mime.conf so that my server sees .html as PHP.
But I don't know if this is the right way to go.
Currently, I have 2 files in var/www/mysite : index.html and test.php.
I've added DocumentRoot /var/www/mysite to /etc/apache2/sites-enabled/000-default.conf
My .html is something like this:
<!DOCTYPE html>
<html>
<?php include('test.php'); ?>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href = "master.css">
<title>Home Page</title>
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script>
$( document ).ready(function() {
$('.URR').change(function() {
var n = $('.URR').val();
if (n < 1)
$('.URR').val(1);
if (n > 10)
$('.URR').val(10);
});
$('.Brightness').change(function() {
var m = $('.Brightness').val();
if (m < 2)
$('.Brightness').val(2);
if (m > 99)
$('.Brightness').val(99);
});
});
</script>
</head>
<body>
<div id = "container">
<div class = "center-container">
<div class = "logo"><img url="/logo.png"></div>
<div class = "title"><h1>Current Settings</h1></div>
<div id = "center_text_box">
<p>URL:</p> <p><span>%PLACEHOLDER_URL%</span></p>
<p>URL Refresh Rate:</p><p><span>%PLACEHOLDER_URR%</span>(s)</p>
<p>Brightness:</p> <p><span><?php if(isset($Brightness)) print $Brightness; ?></span>(%)</p>
</div>
</div>
</div>
</body>
</html>
And test.php is this:
<?php
// Check if the form is submitted
if ( isset( $_POST['save_values'] ) ) { // retrieve the form data by using the element's name attributes value as key
$Brightness = $_POST['getBrightness'];
$RefreshRate = $_POST['getRefreshRate'];
}
?>
Is this a good practice ?
To have <?php include('test.php'); ?> inside a .html file and to use <?php ?> tags wherever I need them INSIDE the .html file ?
Or should I stop parsing .html as .php and instead start generating HTML inside a PHP file by doing:
<?php
$data = "<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href = "master.css">
<title>Home Page</title>
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script>
$( document ).ready(function() {
$('.URR').change(function() {
var n = $('.URR').val();
if (n < 1)
$('.URR').val(1);
if (n > 10)
$('.URR').val(10);
});
$('.Brightness').change(function() {
var m = $('.Brightness').val();
if (m < 2)
$('.Brightness').val(2);
if (m > 99)
$('.Brightness').val(99);
});
});
</script>
</head>
<body>
<div id = "container">
<div class = "center-container">
<div class = "logo"><img url="/logo.png"></div>
<div class = "title"><h1>Current Settings</h1></div>
<div id = "center_text_box">
<p>URL:</p> <p><span>%PLACEHOLDER_URL%</span></p>
<p>URL Refresh Rate:</p><p><span>%PLACEHOLDER_URR%</span>(s)</p>
<p>Brightness:</p> <p><span>
"
if(isset($Brightness)) print $Brightness;
$data .= "$Brightness</span>(%)</p>
</div>
</div>
</div>
</body>
</html>
"
echo $data;
?>
And if the later is the "way to go" can I have more than one .php file to do things ?
And how do they work together ?
Also, will JavaScript or jQuery work from inside $data ? Will it work from inside HTML from inside PHP ?

jquery php image upload using http://valums.com/ajax-upload/

Iam looking for jquery php image upload exactly given in http://valums.com/ajax-upload/.
i tried code given in the above site. but its not working . as iam newbie.. i tried below code.
<?php
$uploaddir = 'c:\xampp\htdocs\ajax-upload\server\uploads\';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "success";
} else {
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
// Otherwise onSubmit event will not be fired
echo "error";
}
?>
this is my html code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="fileuploader.css" rel="stylesheet" type="text/css">
<style>
body {font-size:13px; font-family:arial, sans-serif; width:700px; margin:100px auto;}
</style>
</head>
<body>
<p>Back to project page</p>
<p>To upload a file, click on the button below. Drag-and-drop is supported in FF, Chrome.</p>
<p>Progress-bar is supported in FF3.6+, Chrome6+, Safari4+</p>
<div id="file-uploader-demo1">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
<script src="fileuploader.js" type="text/javascript"></script>
<script>
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader-demo1'),
action: '../server/upload.php',
debug: true
});
}
// in your app create uploader as soon as the DOM is ready
// don't wait for the window to load
window.onload = createUploader;
</script>
</body>
</html>
in php change:
$uploaddir = 'c:\xampp\htdocs\ajax-upload\server\uploads\';
to
$uploaddir = 'server/uploads';
in javascript change:
action: 'http://localhost/ajax-upload/server/upload.php',
to
action: 'server/upload.php',
if the php file you are running is in the ajax-upload folder.

PHP var displays in Chrome Dev Tool, but not webpage

I have this issue where, I can see the echo of a variable via the preview on Chrome Developer Tools, but it's blank on the actual web page.
I am guessing this is down to a timing issue, so to make it clear this is how I have it.
As page (index.php) loads, it links a .js file that does a FLQ query on FB to get the users name.
It then uses ajax to repost to the index.php with the information.
Back at the index.php page, it reloads and collects via $_POST
It then displays some of the user info held in $_POST
I am guessing why I am doing is not possible, but it's odd that in the Chrome dev tool, all the variables echo on the page, but the actual page is blank where the variable should display.
I can only suggest I have a holding page, collect the detail and then load then moves to the main page to display the data.
<!--
Index.php
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<?php
global $uid;
global $una;
global $uem;
global $uph;
?>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"> </script>
<script type="text/javascript">
// initialize the library with the API key
FB.init({ apiKey: '2847xxxxxxxx689' });
</script>
<?php
?>
<script type="text/javascript">
FB.login(function(response) {
// handle the response
}, {scope: 'email,publish_stream'});
</script>
<script type="text/javascript" src="jquery/op.js"></script>
<?php
$uid = $_POST['uid'];
$una = $_POST['una'];
$uem = $_POST['uem'];
$uph = $_POST['uph'];
echo $_POST['una'];
?>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="stylesheets/op_main.css" media="Screen" type="text/css" />
<?php
//include('assets/opPHP.php');
include('sql/ajaxsql.php');
include('sql/phpsql.php');
$opapp = new opapp;
?>
<body>
<div id="mainbody">
<div id="topbanner">
Beta Name <?php echo $una; ?>
</div>
<--
.js File
-->
$(window).load(function() {
FB.api('/me', function(response) {
var query = FB.Data.query('select uid,name,email, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
var uid = rows[0].uid;
var una = rows[0].name;
var uem = rows[0].email;
var uph = '<img src="' + rows[0].pic_square + '>';
$.ajax({
url: '../index.php',
type: 'POST',
data: 'uid=' + uid + '&una=' + una + '&uem=' + uem + '&uph=' + uph
});
});
});
});
I can see it posts the information, so my question is. Is their another way to collect the information, while being on the same page. Even explain why I can see it it dev tool, but not the main page?
Thanks
Andrew
echo $_POST['una']; is echoed in the head tag so it will be shown in Chrome dev tools but not in web page.
Regarding <?php echo $una; ?>, I am not seeing anyplace were this variable is getting set. So this may be the reason why it is coming blank

Inline javascript checks in PHP

I was trying to use <script> <noscript> checks inline with my PHP to render different form elements depending on weather or not someone has javascript enabled.
To display something to non enabled users only I can successfully use
<noscript> <?php ... ?> </noscript>
To display something to enabled users only I tried whats below but it does not work the same as above. Instead it allows all users to still see the PHP.
<script> <?php ... ?> </script>
How can I limit something to only those with javascript enabled without having two totally different pages?
You may be able to use something like this:
<script>
<?php
ob_start();
// ...
$scriptOnlyData = ob_get_clean();
?>
document.write(<?php echo json_encode($scriptOnlyData); ?>);
</script>
Javascript runs on the Client-side (in the browser), PHP runs on the Server-side (before the page is sent to the browser). So PHP does not know whether the browser does, or does not, have Javascript.
The simplest solution is to use Javascript itself to show/hide various elements within the browser, like so:
<!doctype html>
<html>
<head>
<title>Test Page</title>
<style>
.showWithJS {
display:none;
}
</style>
</head>
<body>
<div class="showWithJS">
This DIV, and anything with the class "showWithJS",
will only be seen when Javascript is enabled.
</div>
<div class="hideWithJS">
This DIV, and anything with the class "hideWithJS",
will not be seen when Javascript is enabled.
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.showWithJS').show();
$('.hideWithJS').hide();
});
</script>
</body>
</html>
Another option would be to use Javascript to set a cookie (which can be read by PHP) to indicate whether that javascript is running. The downside of that, of course, is that, should the user switch javascript on/off mid-visit, the cookie will not update to reflect that change.
<?php
$javascriptOn = ( isset( $_COOKIE['javascript'] ) && $_COOKIE['javascript']=='on' );
?><!doctype html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<?php if( $javascriptOn ){ ?>
<div>
This DIV will only be seen when Javascript is enabled.
</div>
<?php } ?>
<?php if( !$javascriptOn ){ ?>
<div>
This DIV will not be seen when Javascript is enabled.
</div>
<?php } ?>
<script>
document.cookie = 'javascript=on';
</script>
</body>
</html>
The downside of this is that you need a pageload to set the cookie (it cannot be set and read by the same pageload), so you would need to refresh the page to see the changes.
Load the PHP in javascript and then insert when the DOM loads
JS:
function pageLoad(){
var text = "<?php ... ?>";
document.getElementById('scriptSpan').innerHTML = text;
}
html:
<span id="scriptSpan"></span>

Notifications script, how to put data inside of a div

I was trying to create a notifications system for a website with the following code :
setInterval(function() {
$.post('notifications.php', {
email: 123
}, function(data) {
});
}, 30000);
And the notifications.php :
$userid = $_SESSION[username];
$notifications = array();
$sql = "SELECT appreciation FROM ms_notifications WHERE email = '$userid' AND new = '1'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res)) {
while ($r = mysql_fetch_object($res)) {
$notifications[] = $r->appreciation;
}
$nb_result = mysql_num_rows($res);
}
$sql = "UPDATE ms_notifications SET new = '0' WHERE email = '$userid'";
mysql_query($sql) or die(mysql_error());
echo $nb_result;
Problem is that, as I'm new to jquery/Js, I don't know how to put the result inside of a div. For now it stays on the top of the page, above everything.
I tried that, inside the data function but not working... :
$('#test_app').html(data);
I guess it's a very stupid question but help would be really appreciated ! Thank you very much.
UPDATE : Here the HTML Code
<?php
session_start();
include ('connection/database.php');
include ('login_script.php');
include ('notifications.php');
if($logged_in){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Home</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="ms.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/font_i/specimen_files/easytabs.js" type="text/javascript" charset="utf-8"></script>
<!-- FONT SCRIPT-->
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#container').easyTabs({defaultContent:1});
});
</script>
<script type="text/javascript" charset="utf-8">
var scrollSpeed = 70; // Speed in milliseconds
var step = 1; // How many pixels to move per step
var current = 0; // The current pixel row
var imageHeight = 505; // Background image height
var headerHeight = 59; // How tall the header is.
//The pixel row where to start a new loop
var restartPosition = -(imageHeight - headerHeight);
function scrollBg(){
//Go to next pixel row.
current -= step;
//If at the end of the image, then go to the top.
if (current == restartPosition){
current = 0;
}
//Set the CSS of the header.
$('#main_logo').css("background-position","0 "+current+"px");
}
//Calls the scrolling function repeatedly
var init = setInterval("scrollBg()", scrollSpeed)
</script>
<!-- NOTIFICATIONS_SCRIPT !!!!!! -->
<script type="text/javascript" charset="utf-8">
setInterval(function() {
$.post('notifications.php', {
email: 123
}, function(data) {
});
}, 30000);
</script>
<style>
body{
font-family:SommetRoundedLight;
}
</style>
</head>
<body>
<div id="container">
<div id="header_contain">
<div id="test_app">
</div>
</div>
</div>
</body>
</html>
<?php }
else{
echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("connexion.php");
-->
</script>';
} ?>
Thanks again
Use .append() instead of .html()
Instead of
$('#test_app').html(data);
just use:
$('#test_app').html('<div>' + data + '</div>');
Seems to simple to be it. Am I missing something?

Categories