Adding Second button in form using JS

I’m trying to add 2 buttons to a form, one that will “save/update” the form and one that will “save/update and send an e-mail” confirming the update (using a function that opens a mailhandler.php file that sends an e-mail). I know my current code has no way of determining which button was pushed and I’m not sure how to rectify that. Both buttons will only save the changes made. Here is what I currently have. In the index.php file I have the following:

<button type="submit" id="btn1">Save Report</button>
<button type="submit" id="btn2">Save and E-Mail Report</button>  
'''
and a webapp.js
'''
function emailFunction() {
window.open("MailHandler.php");
}
$(document).ready(function(){
  // On page load: datatable
  var table_records = $('#table_records').dataTable({
    "ajax": "data.php?job=get_records",
    "columns": [
      { "data": "c_customer_number" },
      { "data": "c_customer_name",   "sClass": "c_customer_name" },
      { "data": "functions",      "sClass": "functions" }
    ],
    "aoColumnDefs": [
      { "bSortable": false, "aTargets": [-1] }
    ],
    "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
    "oLanguage": {
      "oPaginate": {
        "sFirst":       " ",
        "sPrevious":    " ",
        "sNext":        " ",
        "sLast":        " ",
      },
      "sLengthMenu":    "Records per page: _MENU_",
      "sInfo":          "Total of _TOTAL_ records (showing _START_ to _END_)",
      "sInfoFiltered":  "(filtered from _MAX_ total records)"
    }
  });
  var form_record = $('#form_record');
  form_record.validate();
  // Show message
  function show_message(message_text, message_type){
    $('#message').html('<p>' + message_text + '</p>').attr('class', message_type);
    $('#message_container').show();
    if (typeof timeout_message !== 'undefined'){
      window.clearTimeout(timeout_message);
    }
    timeout_message = setTimeout(function(){
      hide_message();
    }, 8000);
  }
  // Hide message
  function hide_message(){
    $('#message').html('').attr('class', '');
    $('#message_container').hide();
  }
  // Show loading message
  function show_loading_message(){
    $('#loading_container').show();
  }
  // Hide loading message
  function hide_loading_message(){
    $('#loading_container').hide();
  }
  // Show lightbox
  function show_lightbox(){
    $('.lightbox_bg').show();
    $('.lightbox_container').show();
  }
  // Hide lightbox
  function hide_lightbox(){
    $('.lightbox_bg').hide();
    $('.lightbox_container').hide();
  }
  // Lightbox background
  $(document).on('click', '.lightbox_bg', function(){
    hide_lightbox();
  });
  // Lightbox close button
  $(document).on('click', '.lightbox_close', function(){
    hide_lightbox();
  });
  // Escape keyboard key
  $(document).keyup(function(e){
    if (e.keyCode == 27){
      hide_lightbox();
    }
  });
  // Hide iPad keyboard
  function hide_ipad_keyboard(){
    document.activeElement.blur();
    $('input').blur();
  }
  // Edit Save button
  $(document).on('click', '.function_edit a', function(e){
    e.preventDefault();
    // Get Report information from database
    show_loading_message();
    var id      = $(this).data('id');
    var request = $.ajax({
      url:          'data.php?job=get_record',
      cache:        false,
      data:         'id=' + id,
      dataType:     'json',
      contentType:  'application/json; charset=utf-8',
      type:         'get'
    });
    request.done(function(output){
      if (output.result == 'success'){
        $('.lightbox_content h2').text('Edit Record Info');
        $('#form_record').attr('class', 'form edit');
        $('#form_record').attr('data-id', id);
        $('#form_record .field_container label.error').hide();
        $('#form_record .field_container').removeClass('valid').removeClass('error');
        $('#form_record #c_customer_name').val(output.data[0].c_customer_name);
        $('#form_record #c_customer_number').val(output.data[0].c_customer_number);
        hide_loading_message();
        show_lightbox();
      } else {
        hide_loading_message();
        show_message('Information request failed', 'error');
      }
    });
    request.fail(function(jqXHR, textStatus){
      hide_loading_message();
      show_message('Information request failed: ' + textStatus, 'error');
    });
  });
  // Edit Save submit form
  $(document).on('submit', '#form_record.edit', function(e){
    e.preventDefault();
    // Validate form
    if (form_record.valid() == true){
      // Save information to database
      hide_ipad_keyboard();
      hide_lightbox();
      show_loading_message();
      var id        = $('#form_record').attr('data-id');
      var form_data = $('#form_record').serialize();
      var request   = $.ajax({
        url:          'data.php?job=edit_record&id=' + id,
        cache:        false,
        data:         form_data,
        dataType:     'json',
        contentType:  'application/json; charset=utf-8',
        type:         'get'
      });
      request.done(function(output){
        if (output.result == 'success'){
          // Reload datatable
          table_records.api().ajax.reload(function(){
            hide_loading_message();
            var c_customer_name = $('#c_customer_number').val();
            show_message("Info '" + c_customer_name + " edited/added successfully.", 'success');
          }, true);
        } else {
          hide_loading_message();
          show_message('Edit request failed', 'error');
        }
      });
      request.fail(function(jqXHR, textStatus){
        hide_loading_message();
        show_message('Edit request failed: ' + textStatus, 'error');
      });
    }
  });
});
	// Email Record
  $(document).on('click', '.function_edit a', function(e){
    e.preventDefault();
    // Get Report information from database
    show_loading_message();
    var id      = $(this).data('id');
    var request = $.ajax({
      url:          'data.php?job=get_record',
      cache:        false,
      data:         'id=' + id,
      dataType:     'json',
      contentType:  'application/json; charset=utf-8',
      type:         'get'
    });
    request.done(function(output){
      if (output.result == 'success'){
        $('.lightbox_content h2').text('Edit Record Info');
        $('#form_record').attr('class', 'form edit');
        $('#form_record').attr('data-id', id);
        $('#form_record .field_container label.error').hide();
        $('#form_record .field_container').removeClass('valid').removeClass('error');
        $('#form_record #c_customer_name').val(output.data[0].c_customer_name);
        $('#form_record #c_customer_number').val(output.data[0].c_customer_number);
        hide_loading_message();
        show_lightbox();
      } else {
        hide_loading_message();
        show_message('Information request failed', 'error');
      }
    });
    request.fail(function(jqXHR, textStatus){
      hide_loading_message();
      show_message('Information request failed: ' + textStatus, 'error');
    });

  // Edit email submit form

  $(document).on('submit', '#form_record.edit', function(e){
    e.preventDefault();
    // Validate form
    if (form_record.valid() == true){
      // Save information to database
      hide_ipad_keyboard();
      hide_lightbox();
      show_loading_message();
      var id        = $('#form_record').attr('data-id');
      var form_data = $('#form_record').serialize();
      var request   = $.ajax({
        url:          'data.php?job=email_record&id=' + id,
        cache:        false,
        data:         form_data,
        dataType:     'json',
        contentType:  'application/json; charset=utf-8',
        type:         'get'
      });
      request.done(function(output){
        if (output.result == 'success'){
          // Reload datatable
          table_records.api().ajax.reload(function(){
            hide_loading_message();
            var c_customer_name = $('#c_customer_number').val();
            show_message("Info '" + c_customer_name + " edited/added successfully.", 'success');
			emailFunction();
          }, true);
        } else {
          hide_loading_message();
          show_message('Edit request failed', 'error');
        }
      });
      request.fail(function(jqXHR, textStatus){
        hide_loading_message();
        show_message('Edit request failed: ' + textStatus, 'error');
      });
    }
  });
});	
'''
and lastly a data.php file
'''
<?php
// Database details
$db_server   = 'localhost';
$db_username = 'root';
$db_password = '*****';
$db_name     = 'customerdb';
// Get job (and id)
$job = '';
$id  = '';
if (isset($_GET['job'])){
  $job = $_GET['job'];
  if ($job == 'get_records' 	||
      $job == 'get_record'   	||
      $job == 'edit_record'   	||	  
      $job == 'email_record')	{
    if (isset($_GET['id'])){
      $id = $_GET['id'];
      if (!is_numeric($id)){
        $id = '';
      }
    }
  } else {
    $job = '';
  }
}
// Prepare array
$mysql_data = array();
// Valid job found
if ($job != ''){
  // Connect to database
  $db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
  if (mysqli_connect_errno()){
    $result  = 'error';
    $message = 'Failed to connect to database: ' . mysqli_connect_error();
    $job     = '';
  }
  // Execute job
  if ($job == 'get_records'){
    // Get records
    $query = "SELECT * FROM customer_info ORDER BY c_customer_number";
    $sql = mysqli_query($db_connection, $query);
    if (!$sql){
      $result  = 'error';
      $message = 'query error';
    } else {
      $result  = 'success';
      $message = 'query success';
      while ($record = mysqli_fetch_array($sql)){
        $functions  = '<div class="function_buttons"><ul>';
        $functions .= '<li class="function_edit"><a data-id="' . $record['HEADID'] . '" data-name="' . $record['c_customer_name'] . '"><span>Edit</span></a></li>';
        $functions .= '</ul></div>';
        $mysql_data[] = array(
          "c_customer_number"  	=> $record['c_customer_number'],
          "c_customer_name"  	=> $record['c_customer_name'],
          "functions"     		=> $functions
        );
      }
    }
  } elseif ($job == 'get_record'){
    // Get record
    if ($id == ''){
      $result  = 'error';
      $message = 'id missing';
    } else {
      $query = "SELECT * FROM customer_info WHERE HEADID = '" . mysqli_real_escape_string($db_connection, $id) . "'";
      $sql = mysqli_query($db_connection, $query); 
      if (!$sql){
        $result  = 'error';
        $message = 'query error';
      } else {
        $result  = 'success';
        $message = 'query success';
        while ($record = mysqli_fetch_array($sql)){
          $mysql_data[] = array(
            "c_customer_name"  	=> $record['c_customer_name'],
            "c_customer_number" => $record['c_customer_number']
          );
        }
      }
    }
  } elseif ($job == 'edit_record'){
    // Edit record
    if ($id == ''){
      $result  = 'error';
      $message = 'id missing';
    } else {
      $query = "UPDATE customer_info SET ";	
    if (isset($_GET['c_customer_name'])) 	{ $query .= "c_customer_name = '" 	. mysqli_real_escape_string($db_connection, $_GET['c_customer_name']) 	. "', ";}
    if (isset($_GET['c_customer_number']))	{ $query .= "c_customer_number = '" . mysqli_real_escape_string($db_connection, $_GET['c_customer_number']) . "'";}
      $query .= "WHERE HEADID = '" . mysqli_real_escape_string($db_connection, $id) . "'";
      $sql  = mysqli_query($db_connection, $query);
      if (!$sql){
        $result  = 'error';
        $message = 'query error';
      } else {
        $result  = 'success';
        $message = 'query success';
      }
    }
  } elseif ($job == 'email_record'){
    // Edit record
    if ($id == ''){
      $result  = 'error';
      $message = 'id missing';
    } else {
      $query = "UPDATE customer_info SET ";	
    if (isset($_GET['c_customer_name'])) 	{ $query .= "c_customer_name = '" 	. mysqli_real_escape_string($db_connection, $_GET['c_customer_name']) 	. "', ";}
    if (isset($_GET['c_customer_number']))	{ $query .= "c_customer_number = '" . mysqli_real_escape_string($db_connection, $_GET['c_customer_number']) . "'";}
      $query .= "WHERE HEADID = '" . mysqli_real_escape_string($db_connection, $id) . "'";
      $sql  = mysqli_query($db_connection, $query);
      if (!$sql){
        $result  = 'error';
        $message = 'query error';
      } else {
        $result  = 'success';
        $message = 'query success';
      }
    }
  } 
  // Close database connection
  mysqli_close($db_connection);
}
// Prepare data
$data = array(
  "result"  => $result,
  "message" => $message,
  "data"    => $mysql_data
);
// Convert PHP array to JSON array
ini_set('memory_limit', '500M');
$json_data = json_encode($data);
print $json_data;
?>

I think that going with a function might be my best bet but it still just refreshes the site instead of updating it. I also tried removing $(document).on(‘ready’, ‘#form_record’, function(e){ from the functions as was suggested from users from another site but that also didn’t work. Any suggestions would be most appreciated, thank you.

    <button type="submit" id="btn1" onClick="save()">Save Report</button>
    <button type="submit" id="btn2" onClick="email()">Save and E-Mail Report</button>    

and webapp.js is this:

function emailFunction() {
window.open("MailHandler.php");
}
$(document).ready(function(){
// On page load: datatable
var table_records = $('#table_records').dataTable({
"ajax": "data.php?job=get_records",
"columns": [
{ "data": "c_customer_number" },
{ "data": "c_customer_name",   "sClass": "c_customer_name" },
{ "data": "functions",      "sClass": "functions" }
],
"aoColumnDefs": [
  { "bSortable": false, "aTargets": [-1] }
],
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"oLanguage": {
  "oPaginate": {
    "sFirst":       " ",
    "sPrevious":    " ",
    "sNext":        " ",
    "sLast":        " ",
  },
  "sLengthMenu":    "Records per page: _MENU_",
  "sInfo":          "Total of _TOTAL_ records (showing _START_ to _END_)",
  "sInfoFiltered":  "(filtered from _MAX_ total records)"
}
  });
var form_record = $('#form_record');
form_record.validate();
// Show message
// Save button
$(document).on('click', '.function_edit a', function(e){
e.preventDefault();
// Get information from database
show_loading_message();
var id      = $(this).data('id');
var request = $.ajax({
  url:          'data.php?job=get_record',
  cache:        false,
  data:         'id=' + id,
  dataType:     'json',
  contentType:  'application/json; charset=utf-8',
  type:         'get'
});
request.done(function(output){
  if (output.result == 'success'){

    $('.lightbox_content h2').text('Edit Info');
    $('#form_record').attr('class', 'form edit');
    $('#form_record').attr('data-id', id);
    $('#form_record .field_container label.error').hide();
    $('#form_record 
.field_container').removeClass('valid').removeClass('error');
    $('#form_record #c_customer_name').val(output.data[0].c_customer_name);
    $('#form_record 
#c_customer_number').val(output.data[0].c_customer_number);
    hide_loading_message();
    show_lightbox();
  } else {
    hide_loading_message();
    show_message('Information request failed', 'error');
  }
});
request.fail(function(jqXHR, textStatus){
  hide_loading_message();
  show_message('Information request failed: ' + textStatus, 'error');
});
});
// Edit submit form
function save(){ 
$(document).on('ready', '#form_record', function(e){
e.preventDefault();
// Validate form
if (form_record.valid() == true){
  // Send information to database
  hide_ipad_keyboard();
  hide_lightbox();
  show_loading_message();
  var id        = $('#form_record').attr('data-id');
  var form_data = $('#form_record').serialize();
  var request   = $.ajax({
    url:          'data.php?job=edit_record&id=' + id,
    cache:        false,
    data:         form_data,
    dataType:     'json',
    contentType:  'application/json; charset=utf-8',
    type:         'get'
  });
  request.done(function(output){

  if (output.result == 'success'){
    // Reload datatable
    table_records.api().ajax.reload(function(){
      hide_loading_message();
      var c_customer_name = $('#c_customer_number').val();
        show_message("Info '" + c_customer_name + " edited/added successfully.", 'success');
//          emailFunction();
      }, true);

    } else {
      hide_loading_message();
      show_message('Edit request failed', 'error');
    }

  });
  request.fail(function(jqXHR, textStatus){
    hide_loading_message();
    show_message('Edit request failed: ' + textStatus, 'error');
  });
}
});
}
// save/email submit form
function email(){ 
$(document).on('ready', '#form_record', function(e){
e.preventDefault();
// Validate form
if (form_record.valid() == true){
  // Send information to database
  hide_ipad_keyboard();
  hide_lightbox();
  show_loading_message();
  var id        = $('#form_record').attr('data-id');
  var form_data = $('#form_record').serialize();
  var request   = $.ajax({
    url:          'data.php?job=edit_record&id=' + id,
    cache:        false,
    data:         form_data,
    dataType:     'json',
    contentType:  'application/json; charset=utf-8',
    type:         'get'
  });
  request.done(function(output){

    if (output.result == 'success'){
      // Reload datatable
      table_records.api().ajax.reload(function(){
        hide_loading_message();
        var c_customer_name = $('#c_customer_number').val();
        show_message("Info '" + c_customer_name + " edited/added successfully.", 'success');
        emailFunction();
      }, true);

    } else {
      hide_loading_message();
      show_message('Edit request failed', 'error');
    }
});
  request.fail(function(jqXHR, textStatus){
    hide_loading_message();
    show_message('Edit request failed: ' + textStatus, 'error');
  });
}
});
}
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.