0

I'm trying to write this form's input to a new .txt file with php, without redirecting to a new page. This code is written in index.php and I suppose I can't put that as the 'form action= ' as well (sorry, looking back it feels especially stupid). My Javascript knowledge is limited, but I believe this is a matter for .ajax? A yes or no would be great! And if you know a good place to learn what I need to, even better!

<form action="index.php" method="post">
     <input type="text" name="email" class="emailSubmitSidebar" placeholder=" Your Email">
     <input type="submit" class="submitButton">
</form>
<?php 
    $fileHandle = fopen('emailList.txt', 'w+')
            OR die ("Can't open file\n");
    $email=$_POST("email");
    $result = fwrite ($fileHandle, $email);
    if ($result)
         {
             print '<script type="text/javascript">'; 
             print 'alert("Email added!")'; 
             print '</script>';  
        } else {
            print '<script type="text/javascript">'; 
            print 'alert("Email not added!")'; 
            print '</script>';  
        };
    fclose($fileHandle);
?>

2 Answers 2

1

The issue is that you are using this $email=$_POST("email"); but you have to use this

 $email=$_POST["email"];

I think Below will help you as par ur comment. for doing without page load user ajax.

<?php
if(isset($_POST["submit"]))
{


    $fileHandle = fopen('emailList.txt', 'w+')
            OR die ("Can't open file\n");
    $email=$_POST["email"];
    $result = fwrite ($fileHandle, $email);
    if ($result)
         {
             print '<script type="text/javascript">'; 
             print 'alert("Email added!")'; 
             print '</script>';  
        } else {
            print '<script type="text/javascript">'; 
            print 'alert("Email not added!")'; 
            print '</script>';  
        };
    fclose($fileHandle);
    }
    ?>

<form action="#" method="post">
     <input type="text" name="email" class="emailSubmitSidebar" placeholder=" Your Email">
     <input type="submit" name="submit" class="submitButton">
</form>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, silly mistake! I'm now getting an alert upon first loading the page that the "email (was) not added". How do I make the if/else run only when the button is pressed/when the data is written? Also how do I do this without reloading the page?
1

The $email=$_POST("email"); should be $email=$_POST["email"]; .

You are calling the $_POST global array as a function , which is wrong. Enclose it in square brackets. [ ] as shown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.