1

I have the following problem, I have performed a function to update my data with PHP and Codeigniter, using AJAX too .. everything works fine, but it turns out that I want to validate my form using jquery-validate before performing the AJAX request, for that already I have my validation rules and my code is as follows:

function edit(id = null) {

    if (!id) {
        alert('error');
        return;
    }

    $.ajax({
        url: 'roles/get_data_id/' + id,
        type: 'post',
        dataType: 'json',
        success: function(response) {
            $("#edit_name").val(response.Name);
            $("#edit_description").val(response.Description);      

            $("#form_edit").unbind('submit').bind('submit', function() {
                var form = $(this); 

                $.ajax({
                    url: form.attr('action') + '/' + id,
                    type: 'post',
                    data: form.serialize(),
                    dataType: 'json',
                    success: function(response) {
                        if(response.success === true) {
                            $("#modal_edit").modal('hide');

                            alert('The data were updated');

                            $("#form_edit")[0].reset();
                            table_data.ajax.reload(null, false);  
                        } else {
                            $("#modal_edit").modal('hide');
                            alert('Error updating data');
                        }
                    }// /succes
                }); // /ajax
                return false;  
            });       
        }
    });
}

The code works fine .. update my data .. now my question is where to add the following code with my validation rules:

$('#form_edit').validate({
    highlight: function (input) {
        $(input).parents('.form-line').addClass('error');
    },
    unhighlight: function (input) {
        $(input).parents('.form-line').removeClass('error');
    },
    errorPlacement: function (error, element) {
        $(element).parents('.form-group').append(error);
    }
});

This is my current code:

function edit(id = null) {

  if (!id) {
    alert('error');
    return;
  }

  $.ajax({
    url: 'roles/get_data_id/' + id,
    type: 'post',
    dataType: 'json',
    success: function(response) {
      $("#edit_name").val(response.Name);
      $("#edit_description").val(response.Description);

      $('#form_edit').validate({
        highlight: function(input) {
          $(input).parents('.form-line').addClass('error');
        },
        unhighlight: function(input) {
          $(input).parents('.form-line').removeClass('error');
        },
        errorPlacement: function(error, element) {
          $(element).parents('.form-group').append(error);
        },
        submitHandler: function() {

          $.ajax({
            url: form.attr('action') + '/' + id,
            type: 'post',
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success === true) {
                  $("#modal_edit").modal('hide');

                  alert('The data were updated');

                  $("#form_edit")[0].reset();
                  table_data.ajax.reload(null, false);
                } else {
                  $("#modal_edit").modal('hide');
                  alert('Error updating data');
                }
              } // /succes
          }); // /ajax
          return false;
        }
      });
    }
  });
}

this code my form:

<div class="modal fade" id="modal_edit" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="smallModalLabel">Edit rol</h4>
      </div>
      <form id="form_edit" action="<?php echo base_url();?>rol/edit" method="POST">
        <div class="modal-body">
          <div class="form-group form-float">
            <label class="form-label">Name</label>
            <div class="form-line">
              <input type="text" id="edit_name" name="edit_name" class="form-control" maxlength="20" minlength="5" required>
            </div>
          </div>
          <div class="form-group form-float">
            <label class="form-label">Description</label>
            <div class="form-line">
              <textarea id="edit_description" name="edit_description" rows="3" class="form-control no-resize" required></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-link waves-effect">update</button>
          <button type="button" class="btn btn-link waves-effect" data-dismiss="modal">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>
1
  • You have an .ajax() function inside the submitHandler of .validate(), which you've put inside of another .ajax() function! Commented Jan 28, 2017 at 17:15

2 Answers 2

2

You can use the submitHandler provided by the jQuery validation, this way the AJAX will fire only when the validation rules are passed:

$('#form_edit').validate({
  highlight: function(input) {
    $(input).parents('.form-line').addClass('error');
  },
  unhighlight: function(input) {
    $(input).parents('.form-line').removeClass('error');
  },
  errorPlacement: function(error, element) {
    $(element).parents('.form-group').append(error);
  },
  submitHandler: function() {
    //your AJAX code goes here
    edit(your_id_param_goes_here);
  }

});
Sign up to request clarification or add additional context in comments.

11 Comments

The validation works, but it sends me to the action in a blank page, I would have to change that inside the ajax
@FernandoBanegas, ok. So there's a problem? Do you need more help?
Yes, I have placed the code you mentioned. And the validations work, but I do not update the data, apparently the action post, does not work
@FernandoBanegas you said the AJAX works in your question. So it should work now too.
Of course it worked, but now that adds the code, does not update, and instead of updating and displaying the alert, send me a blank page with the url of my function, I will upload the code as I have so far
|
0

I have made you a WORKING DEMO, I hope you will figure out how to continue from there.

HTML Changes:

<form id="form_edit">
<button id="submitForm" type="submit" class="btn btn-link waves-effect">update</button>

JavaScript:

 $(document).ready(function() {

$("#submitForm").on("click", edit);

    // introduce the validation rules to the form! 
    $('#form_edit')
        .validate({
            highlight: function(input) {
                $(input).parents('.form-line').addClass('error');
            },
            unhighlight: function(input) {
                $(input).parents('.form-line').removeClass('error');
            },
            errorPlacement: function(error, element) {
                $(element).parents('.form-group').append(error);
            },
            submitHandler: function(form) {
                //Will execute only when the form passed validation.
                OnSubmit(form);
            }
        });


    function OnSubmit(form) {
        $.ajax({
            url: form.attr('action') + '/' + id,
            type: 'post',
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success === true) {
                    $("#modal_edit").modal('hide');
                    alert('The data were updated');
                    $("#form_edit")[0].reset();
                    table_data.ajax.reload(null, false);
                } else {
                    $("#modal_edit").modal('hide');
                    alert('Error updating data');
                }
            } // /success
        }); // /ajax
    }


    function edit(id = null) {

        if (!id) {
            alert('error');
            return;
        }

        $.ajax({
            url: 'roles/get_data_id/' + id,
            type: 'post',
            dataType: 'json',
            success: function(response) {
                $("#edit_name").val(response.Name);
                $("#edit_description").val(response.Description);      

                return false;  
            }
        });       
    }

});

11 Comments

I have the following error : Uncaught SyntaxError: Unexpected token function. I do not know if I should write a ',' at the end of my validation rules .. before starting the OnSubmit function
I have a problem with the syntax error, it does not work, in the edit function I retrieve the data according to the id and I take them to my form in my modal window .. but now it does not take anything and I get this error: Uncaught ReferenceError: edit is Not defined
@FernandoBanegas You didn't post the call to the edit function , but you can try make it global.
I will put the code in my question, from my form in the modal
Copy the code of my form in the question, so that it is understood better. I'm learning to use ajax and this is driving me crazy
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.