-1

In a data entry form, I would like that, when clicking on the 'Submit' button, it would not leave the page where the form is located.

When the forum is submitted, a popup is displayed with information to the user that the form was sent!

In a search, I know that AJAX exists, but I don't know how to implement it fully. I'm a PHP novice, I would like someone to help me with this!

Sorry my English!

HTML:

<form action="php/newsletter.php" method="post" class="formulario">
                <input type="text" name="email" placeholder="Email" required>
              </div>
            <div class="ss-item-required" style="text-align:center;">
              <button type="submit" class="site-btn">Send</button>
            </div>
          </form>

PHP:

  <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conexao = new mysqli($servername, $username, $password, $dbname);
if ($conexao->connect_error) {
    die("Erro na conexão: " . $conexao->connect_error);
}
if (!$conexao) {
    die("Erro de ligação: " . mysqli_connect_error());
}
$sql = "INSERT INTO newsletter (email) VALUES ('email')";
if (mysqli_query($conexao, $sql)) {
    echo '<div id="form-submit-alert">Submitted!</div>'; 
} else {
    echo "Erro: " . $sql . "<br>" . mysqli_error($conexao);
}
?>
j08691
  • 204,283
  • 31
  • 260
  • 272
Sergio C
  • 113
  • 7
  • 1
    Does this answer your question? [jQuery Ajax POST example with PHP](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – harunB10 Apr 16 '20 at 20:38
  • yes! I will try to use this code, thank you – Sergio C Apr 16 '20 at 20:41
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Apr 17 '20 at 23:36

4 Answers4

3

With Ajax, you can call a html request and do something with return code.

For example, you can intercept submit form and create an ajax request in place. This ajax request call your php function, and get result to display/ update some data in page, without reloading all html.

https://api.jquery.com/jquery.ajax/

 <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 </head> 


<form action="php/newsletter.php" method="post" class="formulario">
     <input type="text" name="email" placeholder="Email" required>
     <div class="ss-item-required" style="text-align:center;">
          <button type="submit" class="site-btn">Send</button>
     </div>
</form>

<script>
jQuery(document).ready(function() {

    let form = $('body').find('form');
    $(form).submit(function(e){

            e.preventDefault();
            e.stopPropagation();
            var formData = new FormData($(form)[0]); // serialize form data

            $.ajax({
               type:"POST",
               url:$(form).attr('action'), // use your form action as ajax url
               data:formData,
               contentType: false,
               processData: false,

               success: function(response){

                // test if response is json array or html content
                var is_JSON = true;
                try{ var json = $.parseJSON(response);
                }catch(err){ is_JSON = false; } 

                if(is_JSON){ // json resonse : if your php return json (for handle error )
                    console.log('response is JSON')
                }else{
                    // response is your html of php return
                    console.log('response is not JSON')
                    console.log(response)
                }
            }
        });
        });
});
</script>

Not tested but this should work.

Dharman
  • 30,962
  • 25
  • 85
  • 135
threeside
  • 323
  • 2
  • 10
2

I would use JavaScript for that approach.

Let's say your form has the id my-form; your JavaScript would need to prevent the form from submitting normally and take over the process itself.

let form = document.getElementById("my-form"); // find the form
form.addEventListener("submit", function (event){ // react to the submit try
     event.preventDefault(); // prevent the sending at this point

     let data = new FormData(form); // collect data, as we want to send it later
     // We'll use an XMLHttpRequest, which basically means we send a normal web
     // request from JavaScript and can interpret the answer afterwards
     let xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function() {
         // here we can define code to be executed when the request is running
         if(this.readyState == 4 && this.status == 200){
             // we know the request has been successfull
             window.alert("Data sent!"); // Popup
         }
     };

     // finally we need to execute the xhr
     let method = form.getAttribute("method").toUpperCase();
     let url = form.getAttribute("action"); // reuse from form

     xhr.open(method, url, true);
     xhr.send(data);
});

The benefit of this method is that it runs completely in the background, i.e. the user can proceed using the site while the request is running and it doesn't involve another library.

Resources:

The "submit" event on mozilla.org

The XMLHttpRequest on w3schools.com

Tobi Fischer
  • 36
  • 2
  • 6
0

So what you're saying is after the submit button you're getting send to the backend page actually? what i would do is ( in the backend page) when the code has executed, simple place a php statement :

location:('index.html');

this way you'll instantly get put back to the page you submitted your form on

Morris420
  • 11
  • 3
  • thank you for your answer! where could I put that line of code? – Sergio C Apr 16 '20 at 20:35
  • 1
    assuming you got a backend page where you write SQL to put the data in the SQL and and the bottom of that, to redirect , if you want to use the popup, which is a little bit more advanced in PHP i would look into SESSIONS , to check if a form has ben sent and based of that you can show the user popup dialogs etc – Morris420 Apr 16 '20 at 20:35
  • 1
    `location:('index.html');` is not PHP – halfpastfour.am Apr 16 '20 at 20:36
0

When you submit the form we will set a $result var saving the result.

Then we redirect to index.php again with query url param ?result=success

And then we ensure if is setted (isset()) and compare the value to show the right message.

So assuming the form is in /index.php

<?php
if(isset($_GET['result') && $_GET['result') == "success") {
echo '<div id="form-submit-alert">Submitted success!</div>';
} else {
echo '<div id="form-submit-alert">Submitted error!</div>';
}
?>
<form action="php/newsletter.php" method="post" class="formulario">
  <div>
    <input type="text" name="email" placeholder="Email" required>
  </div>
  <div class="ss-item-required" style="text-align:center;">
    <button type="submit" class="site-btn">Send</button>
  </div>
</form>

// php/newsletter.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conexao = new mysqli($servername, $username, $password, $dbname);

// Init result
$result = "error";

if ($conexao->connect_error) {
    die("Erro na conexão: " . $conexao->connect_error);
}
if (!$conexao) {
    die("Erro de ligação: " . mysqli_connect_error());
}
$sql = "INSERT INTO newsletter (email) VALUES ('email')";
if (mysqli_query($conexao, $sql)) {

    // if the result is OK
    $result = "success";
} else {
    echo "Erro: " . $sql . "<br>" . mysqli_error($conexao);
}


// Redirect to initial page with the query url param
header("Location: /index.php?result={$result}");
?>

Albert Ramos
  • 134
  • 4
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Apr 17 '20 at 23:36
  • OMG, I'M JUST COPYING HIS EXAMPLE. I'd just added a few simple logic to make it work as he needed. So please, for security issues tell him. I'm not gonna refactor his code until is perfect because he has not asked for this. – Albert Ramos Apr 18 '20 at 07:04
  • If you are not going to refactor the code then it is better not to answer. Answering and making the same mistakes is not very helpful. – Dharman Apr 18 '20 at 11:35