Skip to main content

Simple example of handling an AJAX POST request contact form; sanitizing and validating data input.

<?php

if ($_POST) {
    header('Content-Type: application/json; charset=UTF-8');
    header('X-Frame-Options: SAMEORIGIN');
    header('X-Content-Type-Options: nosniff');

    $jsonOutput = '';

    $emailTo = 'email@example.com';
    $emailSubject = 'Contact Form';

    // vars for input data
    $phone = '';
    $topic = '';
    $email = '';
    $message = '';

    //
    // Check for Ajax request headers, exit if not.
    $isAjaxRequest = isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    if (!$isAjaxRequest) {
        // exit script ouputting json data
        $jsonOutput = json_encode(
            array(
                'type' => 'error',
                'text' => 'Request must come from Ajax',
            )
        );
        die($jsonOutput);
    }

    //
    // Check required $_POST vars are set, exit if any missing.
    if (!isset($_POST['name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['message'])) {
        $jsonOutput = json_encode(
            array(
                'type' => 'error',
                'text' => 'Input fields are empty!', )
        );
        die($jsonOutput);
    }

    //
    // Check optional $_POST vars, set empty values for missing.
    if (!isset($_POST['phone'])) {
        $phone = '';
    } else {
        $phone = filter_var(trim($_POST['phone']), FILTER_SANITIZE_STRING);
    }

    if (!isset($_POST['topic'])) {
        $topic = '';
    } else {
        $topic = filter_var(trim($_POST['topic']), FILTER_SANITIZE_STRING);
    }

    //
    // Sanitize input values.
    $name = filter_var(trim($_POST['name']), FILTER_SANITIZE_STRING);
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $message = filter_var(trim($_POST['message']), FILTER_SANITIZE_STRING);

    //
    // Extra validation rules.
    if (empty($name) || strlen($name) < 3) {
        $jsonOutput = json_encode(
            array(
                'type' => 'error',
                'text' => 'Name is too short.', )
        );
        die($jsonOutput);
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $jsonOutput = json_encode(
            array(
                'type' => 'error',
                'text' => 'Invalid email address.', )
        );
        die($jsonOutput);
    }
    if (empty($message) || strlen($message) < 5) {
        $jsonOutput = json_encode(
            array(
                'type' => 'error',
                'text' => 'Message is too short.', )
        );
        die($jsonOutput);
    }

    //
    // Send email
    $sendEmail = @mail(
        $emailTo,
        $emailSubject,
        $message."\r\n\n".'Name: '.$name."\r\nEmail: ".$email."\r\nPhone: ".$phone."\r\nReason: ".$topic,
        'From: '.$email.''."\r\n".'Reply-To: '.$email.''."\r\n".'X-Mailer: PHP/'.phpversion()
    );

    if (!$sendEmail) {
        $jsonOutput = json_encode(
            array(
                'type' => 'error',
                'text' => 'Could not send message.', )
        );
        die($jsonOutput);
    } else {
        $jsonOutput = json_encode(
            array(
                'type' => 'message',
                'text' => 'Message sent.', )
        );
        die($jsonOutput);
    }
}