Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form in HTML to textfile using PHP

Tags:

html

forms

php

I have a form written in HTML and a PHP file that should be able to generate the input into a textfile in the same dir. I tested it out before with a different simple HTML file and it worked, now I'm trying to apply it to a bigger HTML file and somehow it wont work and I cant find whats wrong with it.

feedback.html:

<html>
<head>
        <script>
        function myFunction()
        {
            alert("Your feedback has been sent! Thank you");
        }   
        </script>
</head>
<body>
<div class="Linksediv">
    <h3>Feedback</h3>
    <p>Please enter your name and give us some feedback</p>
        <form action="form1.php" method="post">
            Name<input id="Email" size="30" type="text" name="field1"/><br/>
                <textarea id="pass" type="text" name="field2" rows="4" cols="24">Please give us some feedback
                    </textarea>
             <br/>
                <input type="button" name="submit" value="submit" id="buttonOk" onclick="myFunction()" value="Show alert box" />
        </form>

</div>
</body>
</html>

Form1.php

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {                    //Check if fields are there in HTML file
    $data = $_POST['field1'] . ' - ' . $_POST['field2'] . "\n";             //output
    $ret = file_put_contents('data1.txt', $data, FILE_APPEND | LOCK_EX);    //file dir for data1.txt
    if($ret === false) {                                                    //check if anything was written down
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file"."\n";
    }
}
?>

If I press submit on my form then I'll only get a popup with the alert, and the textfile wont be written

like image 710
user2094841 Avatar asked Dec 04 '25 14:12

user2094841


2 Answers

The following line

<input type="button" name="submit" value="submit" id="buttonOk" onclick="myFunction()" value="Show alert box" />

Creates an input type="button", not type="submit", so the form is not actually submitted.

Also, consider presenting the success message after the post and not on click, just echo it on the form1.php script when the file has been written successfully

like image 196
cernunnos Avatar answered Dec 07 '25 02:12

cernunnos


You may also need to add a "return true" statement to your onclick handler after you change the input type from button to submit. Returning false prevents the submit button from executing its default action, which is to submit the form. The behavior may be the same if you don't have a return value.

function myFunction()
{
   alert("Your feedback has been sent! Thank you");
   return true;
} 
like image 39
James Tracy Avatar answered Dec 07 '25 03:12

James Tracy