0

I want to stop page refresh after the user submits the form. The problem is that it doesn't seem to work. PHP:

<?php 
    function displayimage() {
        $con = mysqli_connect("localhost", "root", "", "cookbook");
        $result = mysqli_query($con, "SELECT * FROM product");
        
        while ($row = mysqli_fetch_array($result)) {
            echo "<img src='uploads/".$row['image']."' class='imageaaa'>";
        }
        
        mysqli_close($con);
    }

    function addrecipe() {
        
        $con = mysqli_connect("localhost", "root", "", "cookbook");
            
        if (isset($_POST["Add"])) {
            
            if (!empty($_POST["Name"])
               ){
                    
                $name = $_POST["Name"];
                $type = $_POST["Type"];
                $image = $_FILES['Image']['name'];
                $date = date("d.m.Y, G:i");

                $sql = "
                INSERT INTO
                product(`name`, `type`, `image`, `date`) 
                VALUES('$name', '$type', '$image', '$date');
                     // More Insert Into queries
                ";

                $target = "uploads/".basename($image);

                if (move_uploaded_file($_FILES['Image']['tmp_name'], $target)) {
                    $msg = "Image uploaded successfully";
                } else {
                    $msg = "Failed to upload image";
                }

                $var = mysqli_multi_query($con,$sql);

                if($var){
                    echo "good";
                } else {
                    echo "bad";
                }    
                
            } else {
                echo "Fill in the form";
            }

        }  
 
        mysqli_close($con);     
    }
?>

HTML:

<?php
  addrecipe();
  displayimage();
?>

<form method="POST" id="form" enctype='multipart/form-data'>
                            
Name:
<input type="text" name="Name" value="<?php echo isset($_POST['Name'])?htmlspecialchars($_POST['Name'], ENT_QUOTES):'';?>"><br>
Type:
<select name="Type" required>
  <option value="dishes" disabled selected hidden required>Wybierz typ</option>
  <option value="dishes">Dania</option>
  <option value="desserts">Desery</option>
  <option value="snacks">Przekąski</option>
</select><be>

Image (jpg, png):                       
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('upload_image').click();" />
<input type="file" style="display:none;" id="upload_image" name="Image">
<br><be>

<!-- More text inputs -->

<button name="Add" id="add">sdfsdfsd</button>
                            
<script>
  $("#add").submit(function(e) {
    e.preventDefault();
  });
</script>

</form>

I've tried a few things, but nothing seems to work. Everything works ok, data is sent to the database, but I can't get rid of this page reload. Did I do something wrong? If there is a better solution I'd love to know it. Also, I have this js code:

    <script>
        if (window.history.replaceState){
            window.history.replaceState(null, null, window.location.href);
        }
    </script>

After my HTML tag, deleting it changes nothing. It disables the resubmit form pop-up before you refresh the page. Is there any way I can disable page refresh after form submission?

Astw41
  • 394
  • 3
  • 12
  • ... e.preventDefault(); return false; ... – svgta Jul 29 '22 at 14:52
  • 1
    There is no "refresh" here, there is a _form submission_: you click the button, the browser makes a request to the server, the server processes the data, and renders a new page. If it didn't do that, the PHP code to process `$_POST` would never run. There is an alternative, generally called "AJAX" - you don't really submit the form at all, you fabricate a request in JavaScript and send it to the server "in the background". – IMSoP Jul 29 '22 at 15:01
  • Try handling "click" event on submit button. It cannot be bypassed even by pressing Enter on a form – Aziz Hakberdiev Jul 29 '22 at 15:59
  • @svgta Thank you for the reply, unfortunately it still doesn't work. – Astw41 Jul 29 '22 at 16:05
  • @IMSoP I found this: https://stackoverflow.com/questions/16616250/form-submit-with-ajax-passing-form-data-to-php-without-page-refresh $(function () { $('#form').on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'post', url: 'recipes.php', data: $('#form').serialize(), success: function () { alert('form was submitted'); } }); }); }); But it doesn't work :/ – Astw41 Jul 29 '22 at 16:06

1 Answers1

0

The <script> tag should be outside of the <form> tag and should contain #form instead of #add

...
</form>
<script>
  $("#form").submit(function(e) {
    e.preventDefault();
  });
</script>

The .submit() method is applied on the form element.

You can also achieve the same by simply returning false from the handler as mentioned in the spec.

...
</form>
<script>
  $("#form").submit(() => false);
</script>
ahmedazhar05
  • 580
  • 4
  • 7
  • Thank you for the comment, but unfortunately it didn't help. I put the script tag (with #form) after the form tag and nothing is sent to the database. I have tried the second option - same result. – Astw41 Jul 29 '22 at 19:21