0

I have a form that should be filled by the user. After filling the form the pieces of information should be sent to the database, and then a success message should arise in the same page.

But the problem is when I try to use the 'click' event in javascript on the submission button it will execute the function I asked for and show the success message but it will stop the data from being sent to the database, it's like it's changing the original behavior of the submit button.

And what made things harder is that I've been trying to do all of these things on one page which means even if the form if successfully submitted we should be redirected to the same page. Can someone suggest a solution? here's the php code:

<div class="container ml-5" id="parentcreateUser">
        <span style="text-decoration:underline;" id="spantext"><b>Veuiller remplir le formulaire ci-dessous pour ajouter un utilisateur </b></span> <br><HR>
        <form class="row" method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> id="main_form">
            <div class="col-lg-8">
                <div class="form-group">
                    <label >Role : </label>
                    <input type="text" class="form-control" name="role" required>
                </div>
                <div class="form-group">
                    <label >Nom : </label>
                    <input type="text" class="form-control" name="nom" required>
                </div>
                <div class="form-group">
                    <label >Prenom : </label>
                    <input type="text" class="form-control" name="prenom" required>
                </div>
                <div class="form-group">
                    <label >Nom d'utilisateur : </label>
                    <input type="text" class="form-control" name="nomutilisateur" required>
                </div>
                <div class="form-group">
                    <label >Adresse email : </label>
                    <input type="email" class="form-control" aria-describedby="emailHelp" name="adresseemail" required>
                </div>
                <div class="form-group">
                    <label>Mot de passe :</label>
                    <input type="password" class="form-control" name="mdp" required>
                </div>
                <button type="submit" class="btn btn-outline-primary float-right" name="submit">Envoyer</button>
            </div>
        </form>
        <?php
            require 'user__bd.php';
        ?>   

        <?php

        if(isset($_POST['submit'])){
            $role=$_POST['role'];
            $nom=$_POST['nom'];
            $prenom=$_POST['prenom'];
            $nomutilisateur=$_POST['nomutilisateur'];
            $adresseemail=$_POST['adresseemail'];
            $mdp=md5($_POST['mdp']);

            $user=new User($role,$nom,$prenom,$nomutilisateur,$adresseemail,$mdp);
            $user->CreateUser();    
        }
        ?>
    </div>

and here's the javascript linked to it:

var parentEl=document.querySelector('#parentcreateUser'),
    divEl=document.createElement('div');

var h4El=document.createElement('h4'),
    h4Text=document.createTextNode('Opération Réussi!');
h4El.appendChild(h4Text);
h4El.classList.add('alert-heading');

var pEl=document.createElement('p'),
    pText=document.createTextNode('un utilisateur a été ajouté à la base de donné du site');
pEl.appendChild(pText);


divEl.appendChild(h4El);
divEl.appendChild(pEl);
divEl.classList.add('alert');
divEl.className+=' alert-success';
divEl.setAttribute('role',"alert");
divEl.style.width='640px';

let createUserSuccess=function()
{
    var spanEl=document.getElementById('spantext'),
        formEl=document.getElementById('main_form');
    spanEl.remove();
    formEl.remove();
    parentEl.appendChild(divEl);
}

var btnEl=document.getElementsByName('submit')[0];
console.log(btnEl);

btnEl.addEventListener('click',createUserSuccess);

Note that I'm trying to get things done in the following order:

  1. form submission and data sent to the database successfully
  2. redirection to the same page of the submission
  3. executing the javascript and therefore removing the form from the page or replacing it with a success message
kHarshit
  • 11,362
  • 10
  • 52
  • 71
  • Use jquery and you can do it in 2 steps (without redirect), just send ajax and if response is ok hide form and show success message – Ruben Danielyan Feb 25 '20 at 12:54
  • Return a success URL parameter from the form processing script and check it in your script. If it exists. Hide the form. – Muhammad Tashfeen Feb 25 '20 at 12:55
  • I've never worked with jquery since I'm a newbie but I'll try to do as you said – Firdaouss Lotfi Feb 25 '20 at 13:09
  • You should [learn how to use the label element properly](http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/). Without a for attribute or a form control inside it, a label is useless. – Quentin Feb 25 '20 at 14:12

3 Answers3

1

Given your current situation:

  1. Load page A with a <form>
  2. Submit form
  3. Load page B with the result of submitting the form

Then JavaScript on page A (which the click event would be) cannot run after step 3: It's a different page.

You can include a <script> element in page B that just runs your function without waiting for any event.

        $user->CreateUser();    
        ?>
        <script> createUserSuccess(); </script>
        <?php
    }

You could also use Ajax which would change the flow to:

  1. Load page A with a <form>
  2. Run JavaScript that collects the data the user entered into the form on the click event
  3. Make an HTTP request with JavaScript's XMLHttpRequest or fetch object
  4. Run your function in response to the load event on the XHR object
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Try to add

event.preventDefault();

to your createuserSuccess function. Default behavior of a submit is doing a refresh, so if this happens before your php script finishes it might cause unexpected behavior.

GetShifting
  • 461
  • 4
  • 12
  • If you do that, then the PHP script **won't even start** – Quentin Feb 25 '20 at 14:10
  • I see. But you could trigger the php script in a different way like explained here: https://stackoverflow.com/questions/16834138/javascript-function-post-and-call-php-script/16834317 . I am also new, just trying to help. – GetShifting Feb 25 '20 at 14:21
  • They could, and I mentioned that in the second half of my answer, but unless they do all that work, your answer won't help at all. – Quentin Feb 25 '20 at 14:22
-1

You need to submit the form in function createUserSuccess

but first change button type = "button" so that it will not be submitted twice

document.getElementById("main_form").submit();

then remove form and then show success message

Virender Kumar
  • 182
  • 1
  • 8
  • The form is already being submitted, doing it again with JS won't make any difference … and certainly wouldn't cause createUserSuccess to run **after the form has finished submitting** which is the goal! – Quentin Feb 25 '20 at 14:12
  • Need to change button type = "button" so that it will not be submitted twice – Virender Kumar Feb 26 '20 at 12:53
  • That still won't cause the `onclick` function to run **on the page that loads after the submission is complete**. (And as I said: It doesn't make a difference. The page can only reload once, so triggering a submission and then immediately triggering it again with JS will just cancel the first submission). – Quentin Feb 26 '20 at 12:57
  • When there is no submit button form will not be submitted by PHP and hence not reload, so onclick event will run in javascript and form will be submitted in javascript and success message will also be displayed in any element on page. SO all functionality will run in javascript and no page load – Virender Kumar Feb 26 '20 at 18:35
  • No! The order is still wrong. The success message will still be displayed on the first page before the form submits and the second page is loaded. – Quentin Feb 26 '20 at 23:10