skip to Main Content

This is my first question here and hope I’m doing it correctly.
I am a beginner in this "coding world" and already made some progress using the answers found here!

Today I face a problem with a form submission via AJAX and PHP. If I leave out the AJAX part. The Insert form works great and does what it should do, but when I try to submit it with AJAX it doesn’t do anything but refresh the page. I want to use AJAX to set error divs in the HTML part without page refresh.

here is the code used:

HTML:

<form class="form" action="../actions/insertUser.php" method="post" id="createUserForm">
    <div class="row">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <label>Gebruikersnaam</label>
                        <input 
                        class="form-control"
                        id="userGebruikersnaam" 
                        type="text" 
                        name="userGebruikersnaam" 
                        placeholder="JODO"
                        value=""
                        maxlength="4"
                        pattern="[A-Za-z]{4}"
                        title="Maximaal 4 letters"
                        required>
                        <div id="form-info"></div>
                        <small class="small-form-text">Eerste 2 karakters Voornaam &amp; Eerste 2 karakters Achternaam<hr></small>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <label>Voornaam</label>
                        <input 
                        class="form-control"
                        id="userVoorNaam" 
                        type="text" 
                        name="userVoorNaam" 
                        placeholder="John" 
                        value=""
                        required>
                        <div id="form-info"></div>
                    </div>
                </div>
                <div class="col">
                    <div class="form-group">
                        <label>Achternaam</label>
                        <input 
                        class="form-control"
                        id="userNaam" 
                        type="text" 
                        name="userNaam"
                        placeholder="Doe" 
                        value=""
                        required>
                        <div id="form-info"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <label>Email</label>
                        <input 
                        class="form-control"
                        id="userMail"
                        type="email" 
                        name="userMail"
                        placeholder="[email protected]" 
                        value=""
                        maxlength="50"
                        pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$"
                        title="Controleer het opgegeven Emailadres"
                        required>
                        <div id="form-info"></div>
                    </div>
                </div>
            </div>
            <div class="row" style="width:60%">
                <div class="col-md-4">
                    <label for="userGender">Geslacht:</label>
                </div> 
                <div class="col-md-3 genderRadio">
                    <div class="form-group">
                        <label>
                            <input type="radio" id="userGender" name="userGender" value="man" required>
                                Man
                            </label>
                        </div>
                    </div>
                    <div class="col-md-3 genderRadio">
                    <div class="form-group">
                            <label>
                            <input type="radio" id="userGender" name="userGender" value="vrouw" required>
                                Vrouw
                            </label>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label for="userAfdeling">Afdeling:</label>
                </div>
                <div class="col-md-6">
                    <select class="form-control form-control-sm" name="userAfdeling" id="userAfdeling" required>
                        <option value=""></option>
                        <option value="Administratie">Administratie</option>
                            <option value="After-Sales">After-Sales</option>
                            <option value="Carrosserie">Carrosserie</option>
                            <option value="Sales">Sales</option>
                            <option value="Tweedehands">Tweedehands</option>
                    </select>
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-2">
                    <label for="userRole">Machtiging:</label>
                </div>
                <div class="col-md-6">
                    <select class="form-control form-control-sm" name="userRole" id="userRole" required>
                        <option value=""></option>
                        <option value="gebruiker">Gebruiker</option>
                            <option value="admin">Admin</option>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col d-flex justify-content-end">
                    <button class="btn btn-primary" type="submit" name="createUser" id="submit_btn" value=""><i class="fas fa-fw fa-user-plus"></i> Creëer
                    </button>

                </div>
            </div>
        </div>
    </div>
</form>

PHP:

if (isset($_POST['createUser'])) {

    $userGebruikersnaam = strtoupper($_POST['userGebruikersnaam']);
    $userVoorNaam       = htmlspecialchars(ucwords($_POST['userVoorNaam'])); 
    $userNaam           = htmlspecialchars(ucwords($_POST['userNaam']));
    $userMail           = filter_var($_POST['userMail'], FILTER_SANITIZE_EMAIL);
    $userGender         = htmlspecialchars($_POST['userGender']);
    $userAfdeling       = htmlspecialchars($_POST['userAfdeling']);
    $userRole           = htmlspecialchars($_POST['userRole']);
    $userActief         = 0;
    $userCreateDate     = date("Y-m-d");
    /*Random Wachtwoord met Hash*/
    $wachtwoord = randomPassword();
        $optie = ['cost' => 11];
    /*HashedWachtwoord*/
    $userWachtwoord = password_hash($wachtwoord, PASSWORD_DEFAULT, $optie);

    $sql_user = "SELECT * FROM gebruikers WHERE gebruikersnaam ='$userGebruikersnaam'";
    $sql_email = "SELECT * FROM gebruikers WHERE email='$userMail'";
    $res_user = mysqli_query($con, $sql_user);
    $res_email = mysqli_query($con, $sql_email);

    if (mysqli_num_rows($res_user) > 0 ) {
        http_response_code(400);
            echo "Gebruiker bestaat al!";
    } elseif (mysqli_num_rows($res_email) > 0 ) {
            http_response_code(400);
            echo "Email bestaat al!";
        } else{
           // Prepare an insert statement
                $sql = "INSERT INTO gebruikers (gebruikersnaam, email, role, voornaam, naam, actief, 
                wachtwoord, gender, afdeling, datumCreatie) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                if($stmt = $con->prepare($sql)){
                    // Bind variables to the prepared statement as parameters
                    $stmt->bind_param("sssssissss", $userGebruikersnaam, $userMail, $userRole, 
                     $userVoorNaam, $userNaam, $userActief, $userWachtwoord, $userGender, 
                     $userAfdeling, $userCreateDate);
                     $stmt->execute(); 
                     http_response_code(200);
                    echo "Records inserted successfully.";
                    // Close statement
                    $stmt->close();
                } else {
                    http_response_code(400);
                    echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
            }   
        }
    }
 ?>

jQuery:

$(function() {
    // 'Get' het reset formulier.
    //Aanpassing voor insertUser
    var form = $('#createUserForm');
    //Aanpassing voor insertUser
    var formMessages = $('#form-info'); //-->extra div voor text
    var formInputUser = $('#userGebruikersnaam');
    var formInputEmail = $('#userMail');

    // Opzetten van event listener voor het formulier
    $(form).submit(function(e) {
        // Voorkomen dat de browser het formulier verzend.
        e.preventDefault();

        // Serialiseren van de formulier data.
        var formData = $(form).serialize();

        // Verzenden van formulier met AJAX.
        $.ajax({
            type: 'POST',
            //url: $(form).attr('action'),
            url:"../actions/insertUser.php",
            data: formData
        })
        .done(function(response) {
            // Als het gekoppelde PHP script succesvol is box-succes en succes class toevoegen aan
            // formMessages(DIV #form-info) & formInputPass (INPUT #email)
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            $(formInputUser).removeClass('box-error');
            $(formInputUser).addClass('box-succes');
            $(formInputEmail).removeClass('box-error');
            $(formInputEmail).addClass('box-succes');

            // Zetten van antwoord tekst uit het php script.
            $(formMessages).text(response);

            // Formulier leegmaken.
            $('#userGebruikersnaam').val('');
            $('#userMail').val('');
            //window.location.replace("http://stackoverflow.com");
            setTimeout(function(){ window.location.replace("https://www.patrick-smets-group.be/dashboard2/admin/createUser.php");}, 2500);
        })
        .fail(function(data) {
            // Als het gekoppelde PHP script faalt box-error en error class toevoegen aan
            // formMessages(DIV #form-info) & formInputPass (INPUT #email)
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
            $(formInputUser).removeClass('box-succes');
            $(formInputUser).addClass('box-error');
            $(formInputEmail).removeClass('box-succes');
            $(formInputEmail).addClass('box-error');


            // Zetten van antwoord tekst uit het php script.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! Er liep iets mis, probeer het nogmaals.');
            }
        });
    });
});

3

Answers


  1. Try to make the form submit button type as button instead of submit.

    <button class="btn btn-primary" type="button" name="createUser" id="submit_btn" value=""><i class="fas fa-fw fa-user-plus"></i> Creëer
                </button>
    
    Login or Signup to reply.
  2. Comment this line of code in your jquery and check the developer console for any output. if your jquery code is working fine without any syntax error probably this line of code is reloading the page. otherwise, there is something wrong with the syntax just reload the page and check the developer console for any error

    setTimeout(function(){ window.location.replace("https://www.patrick-smets- group.be/dashboard2/admin/createUser.php");}, 2500);
    
    Login or Signup to reply.
  3. You are checking at your backend $_POST['createUser'] but this values is not passed to your backend that’s the reason nothing gets printed . This is because you have use $(form).serialize(); so here serialize() doesn’t include submit button as parameter itself. But you can attached createUser parameter like below :

    $(function() {
      var form = $('#createUserForm');
      $(form).submit(function(e) {
        e.preventDefault();
        var formData = $(form).serialize() + "&createUser=something";
        console.log(formData)
        //also you need to check for null values else when you click on submit button null values will get sended to backend..
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="form" action="../actions/insertUser.php" method="post" id="createUserForm">
      <div class="row">
        <div class="col">
          <div class="row">
            <div class="col">
              <div class="form-group">
                <label>Gebruikersnaam</label>
                <input class="form-control" id="userGebruikersnaam" type="text" name="userGebruikersnaam" placeholder="JODO" value="" maxlength="4" pattern="[A-Za-z]{4}" title="Maximaal 4 letters" required>
                <div id="form-info"></div>
                <small class="small-form-text">Eerste 2 karakters Voornaam &amp; Eerste 2 karakters Achternaam<hr></small>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="form-group">
                <label>Voornaam</label>
                <input class="form-control" id="userVoorNaam" type="text" name="userVoorNaam" placeholder="John" value="" required>
                <div id="form-info"></div>
              </div>
            </div>
            <div class="col">
              <div class="form-group">
                <label>Achternaam</label>
                <input class="form-control" id="userNaam" type="text" name="userNaam" placeholder="Doe" value="" required>
                <div id="form-info"></div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="form-group">
                <label>Email</label>
                <input class="form-control" id="userMail" type="email" name="userMail" placeholder="[email protected]" value="" maxlength="50" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$" title="Controleer het opgegeven Emailadres" required>
                <div id="form-info"></div>
              </div>
            </div>
          </div>
          <div class="row" style="width:60%">
            <div class="col-md-4">
              <label for="userGender">Geslacht:</label>
            </div>
            <div class="col-md-3 genderRadio">
              <div class="form-group">
                <label>
                            <input type="radio" id="userGender" name="userGender" value="man" required>
                                Man
                            </label>
              </div>
            </div>
            <div class="col-md-3 genderRadio">
              <div class="form-group">
                <label>
                            <input type="radio" id="userGender" name="userGender" value="vrouw" required>
                                Vrouw
                            </label>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-2">
              <label for="userAfdeling">Afdeling:</label>
            </div>
            <div class="col-md-6">
              <select class="form-control form-control-sm" name="userAfdeling" id="userAfdeling" required>
                <option value=""></option>
                <option value="Administratie">Administratie</option>
                <option value="After-Sales">After-Sales</option>
                <option value="Carrosserie">Carrosserie</option>
                <option value="Sales">Sales</option>
                <option value="Tweedehands">Tweedehands</option>
              </select>
            </div>
          </div><br>
          <div class="row">
            <div class="col-md-2">
              <label for="userRole">Machtiging:</label>
            </div>
            <div class="col-md-6">
              <select class="form-control form-control-sm" name="userRole" id="userRole" required>
                <option value=""></option>
                <option value="gebruiker">Gebruiker</option>
                <option value="admin">Admin</option>
              </select>
            </div>
          </div>
          <div class="row">
            <div class="col d-flex justify-content-end">
              <button class="btn btn-primary" type="submit" name="createUser" id="submit_btn" value=""><i class="fas fa-fw fa-user-plus"></i> Creëer
                    </button>
    
            </div>
          </div>
        </div>
      </div>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search