How to submit form with validation in javascript and php?

by hal.littel , in category: PHP General , 9 months ago

How to submit form with validation in javascript and php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 9 months ago

@hal.littel 

To submit a form with validation using JavaScript and PHP, you can follow these steps:


JavaScript:

  1. First, write a JavaScript function that will be called when the form is submitting.
  2. Inside this function, prevent the default form submission using event.preventDefault().
  3. Perform your form validation checks such as validating required fields, checking email format, etc.
  4. If any validation fails, display error messages to the user.
  5. If all validation passes, use the fetch() or XMLHttpRequest API to send a POST request to the PHP server.


Here's a sample code for the JavaScript part:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
document.getElementById('your-form-id').addEventListener('submit', function(event) {
    event.preventDefault(); // prevent form submission

    // Perform form validation
    var form = event.target;
    // example: checking if a required field is empty
    if (form.yourField.value.trim() === '') {
        alert('Please fill in the required fields');
        return;
    }

    // If validation passes, send the form data to PHP
    var formData = new FormData(form);
    fetch('your-php-file.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) {
        return response.text();
    })
    .then(function(data) {
        // Optionally, do something with the response from PHP
        console.log(data);
        // Redirect or show success message to the user
    })
    .catch(function(error) {
        console.error('Error:', error);
    });
});


PHP:

  1. Create a PHP file that will receive the form data and perform server-side validation checks.
  2. Retrieve the form data using $_POST superglobal.
  3. Perform the necessary validation checks, like validating email format, checking the presence of required fields, etc.
  4. If any validation fails, send an appropriate error response back to the JavaScript code.
  5. If all validation passes, process the form data as needed and send a response back to the JavaScript code.


Here's a sample code for the PHP part:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
// Perform server-side validation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $yourField = $_POST['yourField'];

    // Example server-side validation - checking if a field is empty
    if (empty($yourField)) {
        // Send an error response back to JavaScript
        http_response_code(400); // Example error HTTP status code
        echo 'YourField is a required field';
        exit();
    }

    // If validation passes, process the form data and send a success response
    // ...
    echo 'Form submitted successfully';
}
?>


Make sure to adapt the JavaScript code by replacing your-form-id and your-php-file.php with your form's HTML id attribute and the PHP file you've created to handle form submission, respectively.


Remember to enhance the server-side validation according to your specific requirements.