0

I am working on a form located in the notify button here

I am testing the form now and I get every submission in my email, but on the frontend my success message is showing on the screen.

I would like for this form to work exactly like the contact form on the site where the success message pops up in a placeholder.. or at the bottom of the form

the html and js for the form are below. I have a feeling like I messed up on the class and/or id somewhere. I got all of this code online and have been editing it to make it do what I need it to do LOL! now I am stuck

HTML

 <form action="php/newsletter-process.php" id="newsletter-form" method="post">

              <input type="text" class="form-control form-control-custom" tabindex="-1"
                     id="text-field-nl" name="text-field-nl">

                <!-- Input Name -->
                <div class="nl-form-group" id="name-field">
                  <label for="form-name" class="sr-only">Name</label>
                  <input type="text" class="form-control form-control-light"
                         id="form-name" name="form-name" placeholder="Name">
                </div>
                <!-- /End Input Name -->

                <!-- Input Email -->
                <div class="nl-form-group" id="email-field">
                  <label for="form-email" class="sr-only">Email</label>
                  <input type="email" class="form-control form-control-light"
                         id="form-email" name="form-email" placeholder="Email">
                </div>
                <!-- /End Input Email -->

                <!--Check Interest-->
              <div class="nl-form-group">
                <p>Which are you more interested in?</p>
                    <input type="checkbox" id="workbook" name="interest-type[]" value="Digital Workbook"/> Digital Workbook<br/>
                    <input type="checkbox" id="vclass" name="interest-type[]" value="Virtual Class Session"/>Virtual Class Session
              </div>
              <!-- /End Input Group -->

                <!-- Submit Button -->
                <div class="btn-row">
                  <div class="form-group">
                    <button type="submit" class="btn btn-light" role="button">
                      Send Message
                    </button>
                  </div>
                </div>
                <!-- /End Submit Button -->

              <!-- Message Alert -->
              <!--div id="message-newsletter" class="message-wrapper text-white message">
                <span><i class="icon icon-sm icon-arrows-slim-right-dashed"></i><label
                    class="message-text" for="email"></label></span>
              </div-->
              <div id="message-newsletter" class="message-wrapper text-white message">
                <i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
                <span class="message-text"></span>
              </div>
              <!-- /End Message Alert -->


            </form>
            <!-- /End Newsletter Form -->

JS

/*
 --------------------------------
 Ajax Contact Form
 --------------------------------
 + https://github.com/pinceladasdaweb/Ajax-Contact-Form
 + A Simple Ajax Contact Form developed in PHP with HTML5 Form validation.
 + Has a fallback in jQuery for browsers that do not support HTML5 form validation.
 + version 1.0.1
 + Copyright 2014 Pedro Rogerio
 + Licensed under the MIT license
 + https://github.com/pinceladasdaweb/Ajax-Contact-Form
 */

(function ($, window, document, undefined) {
  'use strict';

  var form = $('#newsletter-form'),
    messageContainer = $('#message-newsletter'),
    messageText = $('#message-newsletter .message-text');

  form.submit(function (e) {

    // remove the error class
    form.find('.nl-form-group').removeClass('error');
    messageContainer.removeClass('error');

    var errorAll = '';

    // get the form data
    var formData = {
      'name': $('input[name="form-name"]').val(),
      'email': $('input[name="form-email"]').val(),
      'textfield': $('input[name="text-field"]').val()

    };

    // process the form
    $.ajax({
      type: 'POST',
      url: 'php/newsletter-process.php',
      data: formData,
      dataType: 'json',
      encode: true
    }).done(function (data) {
      // handle errors
      if (!data.success) {

       if (data.errors.name) {
          $('#name-field').addClass('error');
          errorAll = data.errors.name;
        }

        if (data.errors.email) {
          $('#email-field').addClass('error');
          errorAll = errorAll + ' ' + data.errors.email;
        }

        messageContainer.addClass('error');
        messageText.html(errorAll);
      } else {
        // display success message
        messageText.html(data.confirmation);

        $('#newsletter-form .form-control').each(function () {
          $(this).fadeIn().val($(this).attr('placeholder'));
        });
      }
      });
      messageContainer.slideDown('slow', 'swing');
      setTimeout(function () {
        messageContainer.slideUp('slow', 'swing');
      }, 10000);
    }).fail(function (data) {
      // for debug
      console.log(data)
    });

    e.preventDefault();
  });
}(jQuery, window, document));

PHP

<?php
$subjectPrefix = 'App It Out Notify';
$emailTo       = 'taking this out';

$errors = array(); // array to hold validation errors
$data   = array(); // array to pass back data

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name    = stripslashes(trim($_POST['form-name']));
    $email   = stripslashes(trim($_POST['form-email']));
    $spam    = $_POST['textfield'];

    foreach($_POST['interest-type'] as $inttype) {
    $check_boxes .= $inttype." ";
    }

    if (empty($name)) {
        $errors['form-name'] = 'Name is required.';
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['form-email'] = 'Email is invalid.';
    }

    // if there are any errors in our errors array, return a success boolean or false
    if (!empty($errors)) {
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {
        $subject = "Message from $subjectPrefix";
        $body    = '
            <strong>Name: </strong>'.$name.'<br />
            <strong>Email: </strong>'.$email.'<br />
            <strong>Email: </strong>'.$check_boxes.'<br />
        ';

        $headers  = "MIME-Version: 1.1" . PHP_EOL;
        $headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
        $headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
        $headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
        $headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
        $headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
        $headers .= "Return-Path: $emailTo" . PHP_EOL;
        $headers .= "Reply-To: $email" . PHP_EOL;
        $headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
        $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;


        if (empty($spam)) {
          mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
        }

        $data['success'] = true;
        $data['confirmation'] = 'Congratulations. Your message has been sent successfully';
    }

    // return all our data to an AJAX call
    echo json_encode($data);
}
ToniDavisJ
  • 13
  • 8
  • There is nothing named `jason_encode`. (it's an acronym, JavaScript Object Notation, not a name) – CertainPerformance Jul 24 '18 at 22:54
  • 2
    Who's Jason?... – samrap Jul 24 '18 at 22:56
  • 1
    sorry.. fixed the title.. json_encode($data); is what I was referring to.. my mistake.. I have edited my post to include my php – ToniDavisJ Jul 24 '18 at 22:59
  • when you say "it doesn't work" - can you be more descriptive - what do you expect, what do you observe instead, what requests do you see in the developer tools console - I think the problem is that you're not preventing the default form submit action – Jaromanda X Jul 24 '18 at 23:00
  • I would like for the success message to pop up in my alert section
    – ToniDavisJ Jul 24 '18 at 23:01
  • what do you observe in the browser, and the browser developer tools – Jaromanda X Jul 24 '18 at 23:02
  • right now my success goes to http://appitout.tdjdev1.com/php/newsletter-process.php and the screen shows {"success":true,"confirmation":"Congratulations. Your message has been sent successfully"} – ToniDavisJ Jul 24 '18 at 23:03
  • @JaromandaX there are no console errors – ToniDavisJ Jul 24 '18 at 23:05
  • you're form has an action (action="php/newsletter-process.php") I don't see the default post action being stopped any where. – gmfm Jul 24 '18 at 23:06
  • is there a better way to go about getting my success message to show up where I have the span for the message alert? – ToniDavisJ Jul 24 '18 at 23:10
  • https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission – gmfm Jul 24 '18 at 23:11
  • @gmfm The form submission is being stopped. – Mike Jul 24 '18 at 23:12
  • You have syntax errors. Remove line 67. Then it should work. – Mike Jul 24 '18 at 23:22
  • @Mike I removed the } and }); that were causing errors and now there is no success message.. and i do not get an email.. but my arrow does show up on the alert area with the red background that would indicate errors.. – ToniDavisJ Jul 24 '18 at 23:31
  • @ToniDavisJ Then you removed too much. You just had to remove line 67. – Mike Jul 24 '18 at 23:40

2 Answers2

0

Change your button type to "button" to not reload the page.

<button type="button" class="btn btn-light" role="button">
   Send Message
</button>

Use the Ajax 'success' and 'error' properties to handle the request success/errors

$.ajax({
    type: 'POST',
    url: '...',
    data: {...},
    datatype: 'JSON',
    success: function(data){...},
    error: function(){...},
});

Use the success/error function to push your success message into the HTML

<div id="message-newsletter" class="message-wrapper text-white message">
  <i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
  <span class="message-text" id="messageText"></span>
</div>

JS

document.getElementById('messageText').innerHTML = <success or error message>
0

Your code is a little bit messed up, what you can do is:

Step one

Serialize your form data, change your formData variable to:

var formData = $("form#newsletter-form").serialize();

also change the sent data and the url in your ajax:

$.ajax({
    type: 'POST',
    url: 'index.php' /*Now, we are requesting the index page instead of the php page.*/,
    data: {'submission': formData},
    datatype: 'JSON',
    success: function(data){...},
    error: function(){...},
});

Step two

Instead of writing a messed up php code you can create a functions like this:

<?php
    class classname{
        public function funcName($formdata,$errors,$data){

            $get = explode('&',  $formdata); // explode with and

            foreach ( $get as $key => $value) {
              $valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] =  substr( $value, strpos( $value, '=' ) + 1 ) ;
            }
            // access your query param

            $name    = stripslashes(trim($valn['name']));
            $email   = stripslashes(trim($valn['email']));
            $spam    = $valn['spam'];

            foreach($_POST['interest-type'] as $inttype) {
            $check_boxes .= $inttype." ";
            }

            if (empty($name)) {
                $errors['form-name'] = 'Name is required.';
            }

            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors['form-email'] = 'Email is invalid.';
            }

            // if there are any errors in our errors array, return a success boolean or false
            if (!empty($errors)) {
                $data['success'] = false;
                $data['errors']  = $errors;
            } else {
                $subject = "Message from $subjectPrefix";
                $body    = '
                    <strong>Name: </strong>'.$name.'<br />
                    <strong>Email: </strong>'.$email.'<br />
                    <strong>Email: </strong>'.$check_boxes.'<br />
                ';

                $headers  = "MIME-Version: 1.1" . PHP_EOL;
                $headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
                $headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
                $headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
                $headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
                $headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
                $headers .= "Return-Path: $emailTo" . PHP_EOL;
                $headers .= "Reply-To: $email" . PHP_EOL;
                $headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
                $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;


                if (empty($spam)) {
                  mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
                }

                $data['success'] = true;
                $data['confirmation'] = 'Congratulations. Your message has been sent successfully';
            }

            // return all our data to an AJAX call
            echo json_encode($data);
        }
    }
?>

Now, we need to request the function from the index.php. so, add this php code to your index page

<?php

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

        header('Content-Type: application/json; charset=utf-8');
        $subjectPrefix = 'App It Out Notify';//I don't know if you need this in your php file if so you can add it.
        $emailTo       = 'taking this out';//I don't know if you need this in your php file if so you can add it.

        $errors = array(); // array to hold validation errors
        $data   = array(); // array to pass back data

        require_once('yourphppage.php');

        $conform = new classname;
        $search->funcName($_POST['data'],$errors,$data);

        die();

    }

?>
Ahmad Salameh
  • 121
  • 2
  • 13