<file_sep>#Objective

To create a database where students can signup and can make it easier for signups to go straight to mailerlite
 
<file_sep>const cool = require('cool-ascii-faces');
const express = require('express');
const path = require('path');
var mysql = require('mysql');
var bodyParser = require('body-parser');

var Mailerlite = require('mailerlite-nodejs-api');
var $apiKey = process.env.MAILERLITE_KEY;
var $campaign_id = process.env.CAMPAIGN_ID;

var mailerlite = new Mailerlite($apiKey);
var $ML_Subscribers = mailerlite.subscribers;
var $ML_Campaigns = mailerlite.campaigns;
var $ML_lists = mailerlite.lists;

var pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USERNAME,
  password: <PASSWORD>,
  database: process.env.DB_DATABASE,
});

const PORT = process.env.PORT || 5000
// const { Pool } = require('pg');
// const pool = new Pool({
//   connectionString: process.env.DATABASE_URL,
//   ssl: true
// });



express()
  .use(express.static(path.join(__dirname, 'public')))
  .use(bodyParser.json())       // to support JSON-encoded bodies
  .use(bodyParser.urlencoded({     // to support URL-encoded bodies
      extended: true
    }))
  .use(express.json())      // to support JSON-encoded bodies
  .use(express.urlencoded()) // to support URL-encoded bodies
  .all('*',function(req,res,next){
    if (!req.get('Origin')) return next();

    res.set('Access-Control-Allow-Origin','http://myapp.com');
    res.set('Access-Control-Allow-Methods','GET,POST');
    res.set('Access-Control-Allow-Headers','X-Requested-With,Content-Type');

    if ('OPTIONS' == req.method) return res.send(200);

    next();
  })
  .set('views', path.join(__dirname, 'views'))
  .set('view engine', 'ejs')
  .get('/', (req, res) => res.render('pages/index'))
  .get('/cool', (req, res) => res.send(cool()))
  .get('/times', (req, res) => {
    let result = ''
    const times = process.env.TIMES || 5
    for (i = 0; i < times; i++) {
      result += i + ' '
    }
    res.send(result)
  })
  .get('/db', async (req, res) => {
    pool.getConnection(function(err, conn) {
      if (err) throw err; // not connected!
      var sql = "SELECT * FROM IEEE_Club_Members";
      // Use the connection
      conn.query(sql, function (error, results, fields) {
        console.log(results);
        // When done with the connection, release it.
        conn.release();

      // Handle error after the release.
      if (error) throw error;
        console.log(results);
        res.send(results)
        // Don't use the connection here, it has been returned to the pool.
      });
    });
  })
  .post('/new_subscriber', async (req, res) => {
      res.header("Access-Control-Allow-Origin", "*");
      var netid = "'"+req.body.netid+"'";
      var fname = "'"+req.body.fname+"'";
      var lname = "'"+req.body.lname+"'";
      var email = "'"+req.body.email+"'";
      var year = "'"+req.body.year+"'";
      var timestamp = new Date().getTime();
      console.log(netid)
      pool.getConnection(function(err, conn) {
        if (err) throw err; // not connected!
        var sql = "INSERT INTO IEEE_Club_Members values ("+netid+","+fname+","+lname+","+email+","+year+","+timestamp+")";
        sql+= " ON DUPLICATE KEY UPDATE Email="+email;
        // Use the connection
        conn.query(sql, function (error, results, fields) {
          // When done with the connection, release it.
          conn.release();

        // Handle error after the release.
        if (error) throw error;
        console.log('1 record inserted');
          // Don't use the connection here, it has been returned to the pool.
        });
      });

      var subscriber = [{
              'email': req.body.email,
              'name': req.body.fname,
              'fields':{'graduating_year':year}
      }];
      console.log($campaign_id);
      $ML_Subscribers.setId($campaign_id).addAll(subscriber,1,function (r){
        console.log(r);
        res.status(200).send('success');
      });

  })
  .post('/delete_subscriber', async (req, res) => {
      res.header("Access-Control-Allow-Origin", "*");
      var netid = "'"+req.body.netid+"'";
      var fname = "'"+req.body.fname+"'";
      var lname = "'"+req.body.lname+"'";
      var email = "'"+req.body.email+"'";
      var year = "'"+req.body.year+"'";
      var timestamp = new Date().getTime();
      console.log(netid)
      pool.getConnection(function(err, conn) {
        if (err) throw err; // not connected!
        var sql = "DELETE FROM IEEE_Club_Members WHERE netid="+netid;
        // Use the connection
        conn.query(sql, function (error, results, fields) {
          // When done with the connection, release it.
          conn.release();

        // Handle error after the release.
        if (error) throw error;
        console.log('1 record removed');
          // Don't use the connection here, it has been returned to the pool.
        });
      });

      var subscriber = [{
              'email': req.body.email,
              'name': req.body.fname,
      }];
      console.log($campaign_id);
      $ML_Subscribers.unsubscribe(subscriber,1,function (r){
        console.log(r);
        res.status(200).send('success');
      });

  })
  .listen(PORT, () => console.log(`Listening on ${ PORT }`))
<file_sep>var netid= document.getElementById('net');
var fst= document.getElementById('first');
var lst=document.getElementById('last');
var email=document.getElementById('mail');
var grads=document.getElementById('grad');
var submitQuery = document.querySelector('input[type="submit"][value="Submit"]');
// var unsubscribeQuery = document.querySelector('input[type="submit"][value="Unsubscribe"]');

//var url = "http://localhost:5000"
 var url = "https://emails-ieee.herokuapp.com"

function handle_form_submission(){
    console.warn('TEST');
    alert('Submit button pressed');
    return false; //do not submit the form
 }

function valid(){
  var missing = "";
  var isValid = true;
  if (!(netid.checkValidity())) {
      $('#net').css({ "background": '#FFFF00'});
      missing +="NetID,";
      isValid = false;
    }
  if (!(fst.checkValidity())) {
      $('#first').css({ "background": '#FFFF00'});
      missing +="First Name,";
      isValid = false;
  }
   if (!(lst.checkValidity())) {
        $('#last').css({ "background": '#FFFF00'});
        missing +="Last Name,";
        isValid = false;
    }
    if (!(mail.checkValidity())) {
         $('#mail').css({ "background": '#FFFF00'});
         missing +="Email,";
         isValid = false;

     }
     if (!(grads.checkValidity())) {
          $('#grad').css({ "background": '#FFFF00'});
          missing +="Graduation Year,";
          isValid = false;
      }

      if(!isValid){
        alert("Missing:" + missing);
        return false;
      }
  return true;
}
function reset(){
  console.log("clicked");
  $('#myForm')[0].reset()


}



submitQuery.addEventListener ('click',function(){
  // Sending and receiving data in JSON format using POST method
//
  json = {netid: netid.value,fname: fst.value,lname: lst.value,email:email.value,year:grads.value};
  if(valid()){
    $.ajax({
      type: "POST",
      crossDomain: true,
      url: url+"/new_subscriber",
      data: json,
      success: function(jsondata){
        alert('success');
        console.log('success');
        reset();
      }
    });
 }
});



unsubscribeQuery.addEventListener ('click',function(){
  // Sending and receiving data in JSON format using POST method
//

  json = {netid: netid.value,fname: fst.value,lname: lst.value,email:email.value,year:grads.value};
  if(valid()){
    $.ajax({
      type: "POST",
      crossDomain: true,
      url: url+"/delete_subscriber",
      data: json,
      success: function(jsondata){
        alert('success');
        console.log('success');
        reset();
      }
    });
 }

});
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Sep 01, 2018 at 02:00 AM
-- Server version: 10.1.34-MariaDB
-- PHP Version: 7.1.19

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `ieee`
--

-- --------------------------------------------------------

--
-- Table structure for table `IEEE_Club_Members`
--

CREATE TABLE `IEEE_Club_Members` (
  `netid` varchar(25) NOT NULL,
  `fname` char(25) NOT NULL,
  `lname` char(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  `year` int(4) NOT NULL,
  `Time Stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `IEEE_Club_Members`
--


--
-- Indexes for dumped tables
--

--
-- Indexes for table `IEEE_Club_Members`
--
ALTER TABLE `IEEE_Club_Members`
  ADD UNIQUE KEY `netid` (`netid`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
