Codded
Codded

Reputation: 1256

jquery validation with modal formwith ajax submitHandler

I have a form within a modal that i am trying to validate before the form gets submitted to ajax db etc.

I am trying to validate the form $("#new_request_form").validate({ on the save button. if it validate then submit the form.

Can anybody tell me what i am missing?

Thanks in advance!

$(document).ready(dialogForms);
function dialogForms() {    
 $('a.menubutton').click(function() {
    var a = $(this);
    $.get(a.attr('href'),function(resp){
      var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
      $('body').append(dialog);
      dialog.find(':submit').hide();
      dialog.dialog({
        title: a.attr('title') ? a.attr('title') : '',
        modal: true,
        buttons: {
          'Save': function() {
                $("#new_request_form").validate({
                 submitHandler: function(form) {
                     submitFormWithAjax($(this).find('form'));
                    $(this).dialog('close');
                 }
                });

                },
          'Cancel': function() {$(this).dialog('close');}
        },
        close: function() {$(this).remove();},
        width: 600,
        height: 500,        
        show: "fade",
        hide: "fade"
      });

var $ac_start_date = '<?php echo $ac_end_date ?>',
    $ac_start_date_flip = '<?php echo $ac_end_date_flip ?>',
    $ac_start_parsed = Date.parse($ac_start_date),
    _today = new Date().getTime();

// For Opera and older winXP IE n such
if (isNaN($ac_start_parsed)) { 
    $ac_start_parsed  = Date.parse($ac_start_date_flip);
}

var _aDayinMS = 1000 * 60 * 60 * 24; 

// Calculate the difference in milliseconds
var difference_ms = Math.abs($ac_start_parsed - _today);

// Convert back to days and return
var DAY_DIFFERENCE = Math.round(difference_ms/_aDayinMS);       

// do initialization here
$("#startdate").datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '0:+100',
            minDate: '+1d',         
            maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});

// do initialization here
$("#enddate").datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '0:+100',
            minDate: '+1d',         
            maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});

}, 'html');
return false;
});
}

function submitFormWithAjax(form) {
  form = $(form);
  $.ajax({
    url: form.attr('action'),
    data: form.serialize(),
    type: (form.attr('method')),
    dataType: 'script',
    success: function(data){
    $(this).dialog('close');
    // Refresh table
   }
  });
  return false;
}

FORM

<?php
require_once("../config.php");
include_once("scripts/connection.php");
?>

<p class="validateTips">All form fields are required.</p>
<div>
<form id="new_request_form" action="insert_new_request.php" method="POST" class="new_request">
<fieldset>
   <legend><p class="subheadertext">Request Holiday</p></legend>

<table width="100%" border="0">

<?php
$username = $USER->firstname.' '.$USER->lastname;

$is_academic_result = mysql_query('SELECT * FROM holiday_entitlement_academic WHERE employee = \'' . $username . '\'');

if($is_academic = mysql_fetch_array($is_academic_result)) {
    switch($is_academic['units']) {
        case 'days':
                  echo'<tr>
                    <td width="150px" valign="middle"><label for="days">Days:</label></td>
                    <td valign="top">
                    <select id="days" name="days">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    </select>
                    </td>
                  </tr>
                    <tr>
                      <td width="150px" valign="middle"><label for="startdate">Start Date:</label></td>
                      <td valign="top"><input type="text" name="startdate" id="startdate" class="required" readonly="readonly"/></td>
                    </tr>';
            break;
        case 'hours':
                  echo'<tr>
                    <td width="150px" valign="middle"><label for="days">Hours:</label></td>
                    <td valign="top"><input type="text" name="hours" id="hours" class="required" /></td>
                  </tr>
                    <tr>
                      <td width="150px" valign="middle"><label for="startdate">Start Date:</label></td>
                      <td valign="top"><input type="text" name="startdate" id="startdate" class="required" readonly="readonly"/></td>
                    </tr>
                    <tr>
                      <td width="150px" valign="middle"><label for="startdate">End Date:</label></td>
                      <td valign="top"><input type="text" name="enddate" id="enddate" class="required" readonly="readonly"/></td>
                    </tr>';
            break;
        default:
            break;
}
} 

?>
  </table>

  <input type="hidden" id="acyear" name="acyear" value="<?php echo $academic_start_date; ?>"/>
  <input type="hidden" id="user" name="user" value="<?php echo $USER->id; ?>"/>
  <input type="hidden" id="employee" name="employee" value="<?php echo $USER->firstname.' '.$USER->lastname; ?>"/>
 </fieldset>
</form>
</div>

EDIT - What it does

with the following when you click save it does not do anything, the modal stays up and even if you fill the form it does not do anything:

  'Save': function() {
            $("#new_request_form").validate({
             submitHandler: function(form) {
                 submitFormWithAjax($(this).find('form'));
                $(this).dialog('close');
             }
            });

        },

With the following the form gets submitted and works as expected just no validation:

 'Save': function() {
                 submitFormWithAjax($(this).find('form'));
                $(this).dialog('close');

            },

Upvotes: 0

Views: 1292

Answers (1)

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

I guess when calling submitHandler function, you have passed the wrong selector. $(this) represent the form itself so there is no need to find the form in it.

So Replace this code

submitFormWithAjax($(this).find('form'));

With

submitFormWithAjax($(this));

Or Alternately

submitFormWithAjax($("#new_request_form"));

This will fix you problem.

Upvotes: 1

Related Questions