0

I have a form with two fields, which I try to submit using ajax. I have jquery form validator plugin, which works fine with all other forms. When I try an ajax submission, the validation doesn't seem to be working. The sacript I use is:

$("#add-edit-template").click( function(event)
    {
        var x;
        x = $('.sp-preview-inner').css('backgroundColor');
        if(x)
        {
        hexc(x);
        $('#addEditTemplateForm').append("<input type='hidden' name='templateColor' value='"+ color+"' />");
        }
        $("#addEditTemplateForm").submit(function(e)
        {
            e.preventDefault();$("div#divLoading").addClass('show');    
            var postData = $("#addEditTemplateForm").serializeArray();
            var formURL = $(this).attr("action");
            $.ajax(
             {
            url : formURL,
            type: "POST",
            data : postData,
            dataType : "html",
            success:function(htmlData) 
            {
            $('#ph_widgets').replaceWith(htmlData);
            $("#templateSuccess").show();
            $("#phButtons").show();
            $('#listWidgets').dataTable({"iDisplayLength" : 25, "aaSorting": []});
            initDraggabletable("#selectedWidgetTable");
            },
            error: function( xhr, status, errorThrown ) 
            {
                console.log( "Error: " + errorThrown );
                console.log( "Status: " + status );
                console.dir( xhr );
            },
            });
            $("div#divLoading").removeClass('show'); 
            e.preventDefault(); //STOP default action
        });
    });

I need the click function since I am taking a value from a div, which is also required for me . I tried to add

 $.validate
    ({
    form : '#addEditTemplateForm'
    })

Immediately after the click and also before the ajax call , but the submission is not getting prevented and the validation is not preventing that. I found may solutions online, but nothing worked for me. Is there any way to fix this...Thanks in advance

1
  • 2
    Try using callback feature of Javascript i.e run ajax request on the success of form validation Commented Oct 27, 2015 at 5:51

2 Answers 2

1

Do something like this:

Your onclick function:

$("#add-edit-template").click(function(event) {
  var x;
  x = $('.sp-preview-inner').css('backgroundColor');
  if (x) {
    hexc(x);
    $('#addEditTemplateForm').append("<input type='hidden' name='templateColor' value='" + color + "' />");
  }

  $("#addEditTemplateForm").submit(); // trigger submit
});

Your validation with the callback function

$.validate({
  form : '#addEditTemplateForm',
  onSuccess : function($form) {
    // if your form is valid
    $("div#divLoading").addClass('show');
    var postData = $("#addEditTemplateForm").serializeArray();
    var formURL = $(this).attr("action");
    $.ajax({
      url: formURL,
      type: "POST",
      data: postData,
      dataType: "html",
      success: function(htmlData) {
        $('#ph_widgets').replaceWith(htmlData);
        $("#templateSuccess").show();
        $("#phButtons").show();
        $('#listWidgets').dataTable({
          "iDisplayLength": 25,
          "aaSorting": []
        });
        initDraggabletable("#selectedWidgetTable");
      },
      error: function(xhr, status, errorThrown) {
        console.log("Error: " + errorThrown);
        console.log("Status: " + status);
        console.dir(xhr);
      },
    }).always({
      $("div#divLoading").removeClass('show');
    });

    return false; // Will stop the submission of the form
  }
 })

You can see lot of callbacks here

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

1 Comment

I tried this, but now validation works, but if validation, the form submission occurs as default and not through ajax
0

Have you tried,

$("#add-edit-template").click( function()
        {
        var x;
        x = $('.sp-preview-inner').css('backgroundColor');
        if(x)
        {
        hexc(x);
        $('#addEditTemplateForm').append("<input type='hidden' name='templateColor' value='"+ color+"' />");
       }
       var isValid = false;
       var found = false;
       $("#addEditTemplateForm").on('validation', function(evt, valid) 
       {
       if(!valid)
       {
        found = false;
        console.log('found'+found);
       }
       if(found)
       {
        $("#addEditTemplateForm").submit(function(e)
        {
            $(".alert").hide();
            e.preventDefault();
            $("div#divLoading").addClass('show');   
            var postData = $("#addEditTemplateForm").serializeArray();
            var formURL = $(this).attr("action");
            $.ajax(
            {
            url : formURL,
            type: "POST",
            data : postData,
            dataType : "html",
            success:function(htmlData) 
            {
            $('#ph_widgets').replaceWith(htmlData);
            $("#templateSuccess").show();
            $("#phButtons").show();
            $('#listWidgets').dataTable({"iDisplayLength" : 25, "aaSorting": []});
            initDraggabletable("#selectedWidgetTable");
            $("div#divLoading").removeClass('show');
            },
            error: function( xhr, status, errorThrown ) 
            {
                console.log( "Error: " + errorThrown );
                console.log( "Status: " + status );
                console.dir( xhr );
            },
        });

            e.preventDefault(); //STOP default action

        });
        }
        });
    });

1 Comment

now the validation works, but the form submission is not happening through ajax, the default submission occurs, thanks, problem is half solved now

Your Answer

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