PHP - Script not working

I can’t figure out where the issue is with this script… Can you guys analyse the bug?

<?php
// Function to check if an email is valid
function isEmailValid($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// Function to generate a random validation code
function generateValidationCode() {
    $code = rand(100000, 999999);
    $novaCode = "NOVA23-" . $code;
    return $novaCode;
}

// Function to fetch detailed errors for debugging
function getDetailedError(Throwable $exception) {
    return sprintf(
        "Exception message: %s\nException code: %s\nException file: %s\nException line: %s\n",
        $exception->getMessage(),
        $exception->getCode(),
        $exception->getFile(),
        $exception->getLine()
    );
}

// Database connection details (Update with your actual credentials)
$host = 'localhost';
$dbUsername = 'root';
$password = 'password';
$dbName = 'database';

// Variables for displaying messages to the user
$message = "";
$messageClass = "";

$updateMessage = "";
$updateMessageClass = "";

$name = "";

try {
    // Establish a database connection using PDO with prepared statements
    $db = new PDO("mysql:host=$host;dbname=$dbName;charset=utf8mb4", $dbUsername, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Handle the request form submission
    if (isset($_POST["request-info"])) {
        // Check if Nominee's Data is set
        if (isset($_POST["c_name"], $_POST["c_cat"], $_POST["c_street"], $_POST["c_city"], $_POST["c_net"],
            $_POST["name"], $_POST["last_name"], $_POST["email"], $_POST["city"])) {

            // Sanitize the inputs
            $c_name = htmlspecialchars($_POST["c_name"]);
            $c_cat = htmlspecialchars($_POST["c_cat"]);
            $c_street = htmlspecialchars($_POST["c_street"]);
            $c_city = htmlspecialchars($_POST["c_city"]);
            $c_net = htmlspecialchars($_POST["c_net"]);
            $name = htmlspecialchars($_POST["name"]);
            $last_name = htmlspecialchars($_POST["last_name"]);
            $email = htmlspecialchars($_POST["email"]);
            $city = htmlspecialchars($_POST["city"]);

            // Handle Errors
            if (!isEmailValid($email)) {
                $message = "Ungültige E-Mail-Adresse!";
                $messageClass = "bad";
            } else {
                // Check if the Nominator is in nova_nominator_24
                $checkNominatorQuery = "SELECT * FROM nova_nominator_24 WHERE EMail = :email AND request_verified = 'YES'";
                $checkNominatorStatement = $db->prepare($checkNominatorQuery);
                $checkNominatorStatement->bindParam(':email', $email);
                $checkNominatorStatement->execute();

                if ($checkNominatorStatement->rowCount() > 0) {
                    $existingUser = $checkNominatorStatement->fetch(PDO::FETCH_ASSOC);
                    $existingUserName = $existingUser['Name'];
                    $message = "Hallo $name, du hast bereits $c_name nominiert!";
                    $messageClass = "bad";
                } else {
                    // Insert Nominee data into nova_nominees_24
                    $insertNomineeQuery = "INSERT INTO nova_nominees_24 (Candidate_Name, Categorie_ID, Street, Internet, City) 
                                           VALUES (:c_name, :c_cat, :c_street, :c_net, :c_city)";
                    $insertNomineeStatement = $db->prepare($insertNomineeQuery);
                    $insertNomineeStatement->bindParam(':c_name', $c_name);
                    $insertNomineeStatement->bindParam(':c_cat', $c_cat);
                    $insertNomineeStatement->bindParam(':c_street', $c_street);
                    $insertNomineeStatement->bindParam(':c_net', $c_net);
                    $insertNomineeStatement->bindParam(':c_city', $c_city);
                    $insertNomineeStatement->execute();

                    // Get the last inserted nominee ID
                    $nomineeId = $db->lastInsertId();
                    
                    $request_verified = "NO";

                    // Generate validation code
                    $validationCode = generateValidationCode();

                    // Insert Nominator data into nova_nominator_24
                    $insertNominatorQuery = "INSERT INTO nova_nominator_24 (Name, LastName, EMail, City, Validation_code, request_verified, Nominee_ID) 
                                             VALUES (:name, :last_name, :email, :city, :validation_code, :request_verified, :nominee_id)";
                    $insertNominatorStatement = $db->prepare($insertNominatorQuery);
                    $insertNominatorStatement->bindParam(':name', $name);
                    $insertNominatorStatement->bindParam(':last_name', $last_name);
                    $insertNominatorStatement->bindParam(':email', $email);
                    $insertNominatorStatement->bindParam(':city', $city);
                    $insertNominatorStatement->bindParam(':validation_code', $validationCode);
                    $insertNominatorStatement->bindParam(':request_verified', $request_verified);
                    $insertNominatorStatement->bindValue(':nominee_id', $nomineeId);
                    $insertNominatorStatement->execute();

                    // Send E-mail with Validation Code
                    $subject = 'Validation Code for Nominierung';
                    $body = "Dear $name,\n\nYour validation code is: $validationCode";
                    $headers = "From: [email protected]"; // Change this to your email address
                    mail($email, $subject, $body, $headers);

                    $message = "Hallo $name, im Namen von $c_name, bedanken wir uns für die Teilnahme an unserer Preisverleihung";
                    $messageClass = "good";
                }
            }
                        // Prepare JSON response
                        $response = [
                            'success' => true,
                            'message' => $message,
                            'messageClass' => $messageClass,
                        ];
            
                        // Send JSON response
                        echo json_encode($response);
            
                        // End the script execution after sending the JSON response
        }
    } elseif (isset($_POST["verify-request"])) {
        // Verify-Request
        if (isset($_POST["email_step3"], $_POST["validation_code"])) {
            $email = htmlspecialchars($_POST["email_step3"]);
            $validation_code = htmlspecialchars($_POST["validation_code"]);
            $request_verified = "YES";

            // Check if the validation code is correct
            $checkValidationCodeQuery = "SELECT * FROM nova_nominator_24 WHERE EMail = :email AND Validation_code = :validation_code";
            $checkValidationCodeStatement = $db->prepare($checkValidationCodeQuery);
            $checkValidationCodeStatement->bindParam(':email', $email);
            $checkValidationCodeStatement->bindValue(':validation_code', $validation_code);
            $checkValidationCodeStatement->execute();

            if ($checkValidationCodeStatement->rowCount() > 0) {
                // Update the request_verified status
                $updateDataQuery = "UPDATE nova_nominator_24 SET request_verified = :request_verified WHERE EMail = :email";
                $updateDataStatement = $db->prepare($updateDataQuery);
                $updateDataStatement->bindParam(':request_verified', $request_verified);
                $updateDataStatement->bindParam(':email', $email);
                $updateDataStatement->execute();

                // Send update email to service team
                $serviceTeamEmail = '[email protected]'; // Change this to your service team's email address
                $subject = 'Nomination Verified';
                $body = "The nomination for $c_name by $name $last_name has been verified.";
                $headers = "From: [email protected]"; // Change this to your email address
                mail($serviceTeamEmail, $subject, $body, $headers);

                $updateMessage = "Vielen Dank, deine Nominierung wurde erfolgreich verifiziert!";
                $updateMessageClass = "good";
            } else {
                $updateMessage = "Die Verifizierung ist fehlgeschlagen. Überprüfe bitte deine Eingaben und versuche es erneut.";
                $updateMessageClass = "bad";
            }
        }
    }
    // Prepare JSON response
    $response = [
        'success' => true,
        'updateMessage' => $updateMessage,
        'updateMessageClass' => $updateMessageClass,
    ];

    // End the script execution after sending the JSON response
} catch (PDOException $e) {
     // Log rotation (optional): Check log file size and rotate if needed
     $errorLogPath = 'error.log';
     $maxLogSize = 1048576; // 1 MB
 
     if (file_exists($errorLogPath) && filesize($errorLogPath) > $maxLogSize) {
         // Rename the current log file with a timestamp
         $newLogName = 'error_' . date('YmdHis') . '.log';
         rename($errorLogPath, $newLogName);
     }
 
    // Log detailed error information to a file
    $errorLog = fopen('error.log', 'a');
    fwrite($errorLog, getDetailedError($e));
    fclose($errorLog);

    // Display a generic error message to the user
    $message = "Es ist ein Fehler aufgetreten. Bitte versuche es später erneut.";
    $messageClass = "bad";
} finally {
    // Close the database connection
    $db = null;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nominierungsformular 2024</title>
    <style>
        /* Add your CSS styles here */
        .hide-current-step {
            transform: translateX(-100%);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .show-next-step {
            transform: translateX(0) !important;
            opacity: 1 !important;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .hide-previews-step {
            transform: translateX(100%);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .show-previews-step {
            transform: translateX(0) !important;
            opacity: 1;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

    </style>
</head>

<body>
    <section id="nominate">
        <div class="n-inf">
            <h1>Nominierungsformular für 2024 in München</h1> <br>
            <p>Damit eine Nominierung in Betracht gezogen werden kann, muss sie bis zum 20. Januar 2023 eingegangen sein.
                Bereits die Nichterfüllung von nur drei der allgemeinen <a href="?page=terms" class="btn">Anforderungskriterien</a> kann zum Ausschluss aus der weiteren Bearbeitung führen.</p><br>
            <p>Für Fragen stehen wir gerne zur Verfügung. Bitte sende eine E-Mail an: <mark> <a href="mailto:[email protected]?subject=NOVA 24 - Anfrage">[email protected]</a></mark></p>
        </div>

        <div id="nomination-form-group">
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="request-info">
                <!-- STEP ONE -->
                <div class="f-steps form_step_1" style="opacity: 1;">
                    <span class="stp-heading"><sup>1</sup> Ich nominiere</span> <br> <br> <br>

                    <!-- Your existing form fields and markup for step 1 -->
                    <div class="input_wrap">
                    <input type="text" name="c_name" id="c_name" autocomplete="off"  placeholder="" class="form_input">
                    <label for="c_name">Name / Firma:</label> <br>
                        <small class="emt-c-name-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <select name="c_cat" id="c_cat">
                        <option value="" selected disabled hidden>Kategorie</option>
                        <option value="1">Club</option>
                        <option value="2">Bar</option>
                        <option value="3">Dj</option>
                        <option value="4">Veranstalter</option>
                        <option value="5">Tanzschule</option>
                        <option value="6">Performance Artist</option>
                        </select>
                        <br>
                            <small class="emt-c-cat-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="text" name="c_street" id="c_street" autocomplete="on" placeholder="" class="form_input">
                        <label for="c_street">Straße + Nr.:</label> <br>
                            <small class="emt-c-street-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="text" name="c_city" id="c_city" autocomplete="on" placeholder="" class="form_input">
                        <label for="c_city">Stadt:</label> <br>
                            <small class="emt-c-city-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="text" name="c_net" id="c_net" autocomplete="off" placeholder="" class="form_input">
                        <label for="c_net">Internet / Social Media / Telefon:</label> <br>
                            <small class="emt-c-net-e-msg"></small>
                    </div> <br> 
                    <div class="btn_wrap">
                        <button type="button" id="showStepTwoButton">Weiter</button>
                    </div>
                </div>

                <!-- STEP TWO -->
                <div class="f-steps form_step_2" style="display: none; opacity: 0; transform: translateX(100%);">
                    <span class="stp-heading"> <sup>2</sup> Deine Informationen</span> <br> <br> <br>

                    <!-- Your existing form fields and markup for step 2 -->
                    <div class="input_wrap">
                    <input type="text" name="name" id="name" autocomplete="off" placeholder="" class="form_input">
                    <label for="name">Vorname:</label> <br>
                        <small class="emt-n-name-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="text" name="last_name" id="last_name" autocomplete="off"  placeholder="" class="form_input">
                        <label for="last_name">Nachname:</label> <br>
                            <small class="emt-n-l-name-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="email" name="email" id="email" autocomplete="on" placeholder="" class="form_input">
                        <label for="email">E-Mail:</label> <br>
                            <small class="emt-n-email-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="tel" name="phone" id="phone" autocomplete="on" placeholder="" class="form_input">
                        <label for="phone">Telefon:</label> <br>
                            <small class="emt-n-phone-e-msg"></small>
                    </div> <br> <br>
                    <div class="input_wrap">
                        <input type="text" name="city" id="city" autocomplete="on" placeholder="" class="form_input">
                        <label for="city">Stadt:</label> <br>
                            <small class="emt-n-city-e-msg"></small>
                    </div> <br> 

                    <div class="btn_wrap">
                        <!-- Use type="button" to prevent form submission -->
                        <button type="button" id="showStepOneButton" >Zurück</button>
                        <!-- Use type="button" to prevent form submission -->
                        <button type="button" id="showStepThreeButton">Abschicken</button>
                    </div>
                </div>

                <div class="errors">
                    <span class="<?php echo $messageClass ?>">
                        <?php echo $message; ?>
                    </span>
                </div>
            </form>

            <!-- VALIDATION STEP -->
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="verify-request" style="display: none">
                <!-- STEP THREE -->
                <div class="f-steps form_step_3" style="opacity: 0; transform:translateX(100%)">
                    <!-- Your existing form fields and markup for step 3 -->
                    <span class="stp-heading"> <sup>3</sup> Anfrage Validieren</span> <br> <br>
                    <p>Um sicherzustellen, dass deine Anfrage legitim ist, haben wir einen Bestätigungscode an deine E-Mail-Adresse gesendet.</p>
                <br> <br>

                <div class="input_wrap">
                    <input type="email" name="email_step3" id="email_step3" autocomplete="on" placeholder="" class="form_input">
                    <label for="email_step3">E-Mail:</label>
                </div> <br> <br>

                <div class="input_wrap">
                    <input type="text" name="validation_code" id="validation_code"  placeholder="" required class="form_input">
                    <label for="validation_code">Validierungscode:</label>            
                </div> <br> 

                    <div id="result"></div>

                    <div class="btn_wrap">
                        <button type="submit" name="verify">Validieren</button>
                    </div>
                </div>

                <div class="errors">
                    <span class="<?php echo $updateMessageClass ?>">
                        <?php echo $updateMessage; ?>
                    </span>
                </div>
            </form>
        </div>
    </section>
<!-- Add this script section to your HTML file -->
<script>
document.addEventListener('DOMContentLoaded', function (){
    let isValid = true;

function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function validatePhoneNumber(phone) {
    const phoneRegex = /^[0-9]+$/;
    return phoneRegex.test(phone);
}

    const firstForm = document.getElementById('request-info');
    const secondForm = document.getElementById('verify-request');
    const firstStep = document.querySelector('.form_step_1');
    const secondStep = document.querySelector('.form_step_2');
    const thirdStep = document.querySelector('.form_step_3');

function validateField(value, errorElement, errorMessage) {
    errorElement.textContent = '';
    if (value === '') {
        errorElement.textContent = errorMessage;
        return false;
    }
    return true;
}

function ShowStepTwo(event) {
    event.preventDefault();
    const candidateName = document.getElementById('c_name').value.trim();
    const candidateCat = document.getElementById('c_cat').value;
    const candidateStreet = document.getElementById('c_street').value.trim();
    const candidateCity = document.getElementById('c_city').value.trim();
    const candidateNet = document.getElementById('c_net').value.trim();

    const errors = [
        validateField(candidateName, document.querySelector('.emt-c-name-e-msg'), 'Dieses Feld darf nicht leer sein!'),
        validateField(candidateCat, document.querySelector('.emt-c-cat-e-msg'), 'Eine Kategorie wählen!'),
        validateField(candidateStreet, document.querySelector('.emt-c-street-e-msg'), 'Bitte Straße und Hausnummer eingeben!'),
        validateField(candidateCity, document.querySelector('.emt-c-city-e-msg'), 'Bitte Stadt eingeben!'),
        validateField(candidateNet, document.querySelector('.emt-c-net-e-msg'), 'Kontaktdaten eintragen!'),
    ];

    if (errors.every(Boolean)) {
            firstStep.classList.add('hide-current-step');
            setTimeout(() => {
                firstStep.style.display = 'none';
            }, 300);

            secondStep.style.display = 'block';
            setTimeout(() => {
                secondStep.classList.add('show-next-step');
            }, 300);
        }
    }

function ShowStepOne() {
        secondStep.classList.remove('show-next-step');
        setTimeout(() => {
            secondStep.style.display = 'none';
    }, 300);

    firstStep.style.display = 'block';
    setTimeout(() => {
        firstStep.classList.remove('hide-current-step');
    }, 300);
}
function ShowStepThree(event) {
    event.preventDefault();
    isValid = true;

    const n_name = document.getElementById('name').value.trim();
    const n_lname = document.getElementById('last_name').value.trim();
    const n_email = document.getElementById('email').value.trim();
    const n_phone = document.getElementById('phone').value.trim();
    const n_city = document.getElementById('city').value.trim();

    const NominatorNameElement = document.getElementById('name');
    const NominatorLnameElement = document.getElementById('last_name');
    const NominatorEmailElement = document.getElementById('email');
    const NominatorPhoneElement = document.getElementById('phone');
    const NominatorCityElement = document.getElementById('city');

    const NominatorNameError = document.querySelector('.emt-n-name-e-msg');
    const NominatorLnameError = document.querySelector('.emt-n-l-name-e-msg');
    const NominatorEmailError = document.querySelector('.emt-n-email-e-msg');
    const NominatorPhoneError = document.querySelector('.emt-n-phone-e-msg');
    const NominatorCityError = document.querySelector('.emt-n-city-e-msg');

    NominatorNameError.textContent = '';
    NominatorLnameError.textContent = '';
    NominatorEmailError.textContent = '';
    NominatorPhoneError.textContent = '';
    NominatorCityError.textContent = '';

    if (n_name === '') {
        NominatorNameError.textContent = 'Bitte gebe deinen Vornamen ein!';
        NominatorNameElement.classList.add('error');
        isValid = false;
    }

    if (n_lname === '') {
        NominatorLnameError.textContent = 'Bitte gebe deinen Nachnamen ein!';
        NominatorLnameElement.classList.add('error');
        isValid = false;
    }

    if (n_email === '') {
        NominatorEmailError.textContent = 'Bitte gebe deine E-Mail Adresse ein!';
        NominatorEmailElement.classList.add('error');
        isValid = false;
    } else if (!validateEmail(n_email)) {
        NominatorEmailError.textContent = 'Ungültige E-Mail-Adresse!';
        NominatorEmailElement.classList.add('error');
        isValid = false;
    }

    if (n_phone === '') {
        NominatorPhoneError.textContent = 'Bitte gebe deine Telefonnummer ein!';
        NominatorPhoneElement.classList.add('error');
        isValid = false;
    } else if (!validatePhoneNumber(n_phone)) {
        NominatorPhoneError.textContent = 'Ungültige Telefonnummer!';
        NominatorPhoneElement.classList.add('error');
        isValid = false;
    }

    if (n_city === '') {
        NominatorCityError.textContent = 'Trage deine Stadt ein!';
        NominatorCityElement.classList.add('error');
        isValid = false;
    }


    if (isValid) {
        // Use Ajax to submit the second form (verify-request) and handle the response
        const secondForm = document.getElementById('verify-request');
        const formData = new FormData(secondForm);
        const actionUrl = secondForm.getAttribute('action');

        submitFormData(actionUrl, formData);

            secondStep.classList.add('hide-current-step');
            setTimeout(() => {
            firstForm.style.display = 'none';
            secondForm.style.display = 'block';
        }, 300);

        setTimeout(() => {
            thirdStep.classList.add('show-next-step');
        }, 400);

    }
}

function submitFormData(actionUrl, formData) {
    fetch(actionUrl, {
        method: 'POST',
        body: formData,
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Handle successful submission (e.g., display success message)
                console.log('Form submitted successfully:', data.message);
            } else {
                // Handle errors or display a message
                console.error('Form submission failed:', data.updateMessage);
            }
        })
        .catch(error => {
        console.error('Error during form submission:', error);
    });
}


document.getElementById('showStepTwoButton').addEventListener('click', function (event) {
    event.preventDefault();
    ShowStepTwo();
});

document.getElementById('showStepOneButton').addEventListener('click', function (event) {
    event.preventDefault();
    ShowStepOne();
});

document.getElementById('showStepThreeButton').addEventListener('click', function (event) {
    event.preventDefault();
    ShowStepThree(event);
});

});

</script>

</body>

</html>

What symptom or error are you getting?

The form data is not being put in to the tables and no email is sent… but i get no errors…

The error message is cut off in the picture. I suspect it states that the string wasn’t valid json? The reason for this is that the response sent out by the php code must only be the json encoded data. Because the ajax request is to the same URL as the current page, the php code must halt execution after outputting the json data. There are comments in the code at the points where this must occur, but there is no code to do this.

If this is some code you found, were given to use, or were given as an exam, it contains several fundamental mistakes. We are not here to fix code for these cases. If this is code you found and want to implement, get the author to provide support. If this is code you wrote for the purpose of learning, you need to start small, with a form with one form field of one type, then get your code to fully work with the one field. You can then add a from field of a different type and get the code to work for that field type. Once you have mastered how to process each different type of form field, you can worry about all the code needed for the repetitive fields of the various types. After you master how to create a complete application using just html and php/sql, you can worry about using ajax to submit forms.

Some points about the posted code -

  1. The only database exceptions you should catch and handle in your code are for user recoverable errors, such as when inserting/updating duplicate or out of range user data. In all other cases simply let php catch and handle the exceptions, where php will ‘automatically’ display/log the database errors the same as php errors.
  2. When you make the database connection, set the emulated prepared query setting to false (you want to use real prepared queries) and set the default fetch mode to assoc (so that you don’t need to specify it in each fetch statement.)
  3. There are no form fields named “request-info” or “verify-request” so the form processing code will never get executed. You should instead test if a post method for was submitted. If there can be more than one form on a page, use a hidden field, such as ‘action’, with a unique value for each form to control which form processing code to execute.
  4. Don’t write out an isset() statement for every field. The only fields that won’t be set are unchecked checkbox/radio. All other fields will be set after the form has been submitted.
  5. htmlspecialchars() is an OUTPUT function. Do NOT use it on input data. Use it only on data being used in a html context, right before using it.
  6. Do not write out line after line of code for every field. Keep the form data as a set, in a php array variable, then use elements in this array variable throughout the rest of the code.
  7. You need to trim all input data, mainly so that you can detect if it is all white-space characters. Fter you do item #6 on this list, you can accomplish this with one single line of code.
  8. Don’t create verbose variable names. You should deal with one query at a time, before going onto the next query. You can use and reuse simple variable names like $sql, $stmt, …
  9. Use implicit binding by simply supplying an array of the input data to the -.execute([…]) call.
  10. The rowCount() method is not guaranteed to work with select queries for all database types. Instead, just fetch and test if there is fetched data.
  11. Don’t copy variables to other variables for nothing. Just use the original variables.
  12. The set of INSERT queries needs to be executed as a transaction, so that they can be rolled back if there is an error with either query.
  13. A configuration value, such as the From: email address should be defined near the top of the code, in an initialization section, or if there are a number of configuration values, in a separate configuration .php file that gets required when needed.
  14. The values you put into the email body should have htmlentities() applied to them, right before being put into the email body.
  15. You need to test the value returned from the mail() call. If it is a false value, you need to setup a failure message for the user and log all the information about the error so that you (the programmer/developer) can find and fix whatever is causing the email to fail. You would only setup the success message if the the call returns a true value.
  16. As already stated, when you have output the json encoded data, you need to exit/die to stop php code execution.
  17. The validation json response code is in the wrong location.
  18. Don’t use $_SERVER[‘PHP_SELF’]. To get a form to submit to the same page it is on, simply leave out the entire action=’…’ attribute.
  19. Client-side validation is a nicety for legitimate visitors. Since you must trim and validate data on the server before using it, all you should do in the client is add the ‘required’ attribute to any field that must not be empty.
Sponsor our Newsletter | Privacy Policy | Terms of Service