0

I have my code validating the necessary data, but I want to manage the submit based on the response from AJAX. The response is an array of boolean values, for any false value, I want to prevent the form from submitting. I was looking at this solution here, but I would prefer not using a plugin, if possible.

$(document).ready( function () {
    console.log('ready');
    var submitButton = $('#tagProductForm');

    submitButton.on('submit', function (e) {
       e.preventDefault();

       var tags = ($('.tag').map(function () { return $(this).val(); })).get();

       $.ajax({
           type: "POST",
           url: "validateTag.php",
           data: 'jData=' + JSON.stringify(tags)            
       })
       .done(function( response ) {
           response = response.replace(/[[\]]/g,'');
           var responseArray = response.split(",");
           var size = responseArray.length;
           var valid = true;
           if(size != 0){                 
              for(var i = 0; i < size; ++i){
                 if(responseArray[i] == 'false'){
                    $('#tag' + i).attr('style','border:3px solid #FF0000');
                       // set valid to false
                 }
              }
              // if valid is false, prevent form from submitting
           }
        })
       .fail(function() {
           $('#response').html('error');
       })
   });
});
Community
  • 1
  • 1
Brent Connor
  • 628
  • 2
  • 8
  • 23
  • Can you give us an example ?? – ismnoiet Mar 09 '15 at 19:36
  • What am I missing..Your already submitting the form in AJAX..So re-submit? – Tez Wingfield Mar 09 '15 at 19:51
  • Sorry, I'm a JS/JQ noob. How would I re-submit? – Brent Connor Mar 09 '15 at 19:54
  • We may need to dig a little further and understand the issue and help you understand the process along the way. Where you have the comment "Prevent the form from submitting" Is confusing as you have already submitted it? .done function merely is saying to handle additional logic once successfully submitted. So the question is, once you have submitted, you want to check if that a "tag" exists? – Tez Wingfield Mar 09 '15 at 20:09
  • As far as I understood it, line 6 `e.preventDefault();` prevents the form from submitting. Should I be handling this differently? I saw some examples using `submitHandler()` and a `.validate()` functions, but I thought validate was a plugin. – Brent Connor Mar 09 '15 at 20:16
  • So I've added an answer and should work. Give me a shout if you need any more help. – Tez Wingfield Mar 09 '15 at 20:23

3 Answers3

0

You can use:

$('#tagProductForm').submit(function() {
   var tags = ($('.tag').map(function () { return $(this).val(); })).get();

   $.ajax({
       type: "POST",
       url: "validateTag.php",
       data: 'jData=' + JSON.stringify(tags)            
   })
   .done(function( response ) {
       response = response.replace(/[[\]]/g,'');
       var responseArray = response.split(",");
       var valid = true;
       if(responseArray.length > 0){                 
          for(var i = 0; i < size; ++i){
             if(responseArray[i] == 'false'){
                $('#tag' + i).attr('style','border:3px solid #FF0000');
                // set valid to false
                valid = false;
             }
          }
          // if valid is false, prevent form from submitting
          if (!valid){
            return false;
          }
       }
    })
   .fail(function() {
       $('#response').html('error');
   })
});

This is also a little cleaner way to add the handler, as you typically don't submit a button, but rather, submit a form.

Noah B
  • 331
  • 1
  • 9
0

You should be able to do:

if (!valid){
    return false;
}

assuming in you for loop you actually set, valid = false.

marcusshep
  • 1,916
  • 2
  • 18
  • 31
  • The issue is in the original post. Yes my answer will work, because if a form is attempting to submit, returning false will cancel the submission. – marcusshep Mar 09 '15 at 20:10
  • When I refer to "Highlight the issue", I merely meant, was explain what was wrong rather than a quick fix. – Tez Wingfield Mar 09 '15 at 20:12
-1
$(document).ready(function()
{   
   var isValid = false;
   $(.tags).blur(function(e) 
        {

           var tags = ($('.tag').map(function () { return $(this).val(); })).get();

               $.ajax({
                   type: "POST",
                   url: "validateTag.php",
                   data: 'jData=' + JSON.stringify(tags),
                   async: 'false'           
               })
               .done(function( response ) {
                   response = response.replace(/[[\]]/g,'');
                   var responseArray = response.split(",");
                   var size = responseArray.length;
                   isValid = true;
                   if(size != 0){                 
                      for(var i = 0; i < size; ++i){
                         if(responseArray[i] == 'false'){
                            $('#tag' + i).attr('style','border:3px solid #FF0000');
                               // set valid to false
                               isValid = false;
                         }
                      }
                   }
                })
               .fail(function() {
                   $('#response').html('error');
               })
           });
        });

        $('.submitSelector').click(function(e) 
        {
          e.preventDefault();
          if(isValid == true)
          {
            //Submit the form
                // DoWork / Redirect
          } 
        });
}}); 

Ok, So now we preventDefault() to give some room to play with. Considering you want to post to server check values and then cancel form submit whilst using submit button, is quite tricky. Before you even consider submitting ideally you need to validate the values separately. Check values/validate on blur. Then button click to submit the form if values are valid.

Tez Wingfield
  • 2,129
  • 5
  • 26
  • 46
  • `e.preventDefault` doesn't prevent the form from submitting. AJAX will run once when anywhere in the form is clicked. – Brent Connor Mar 09 '15 at 20:29
  • Slight oversight, i'll get this fixed. – Tez Wingfield Mar 09 '15 at 20:37
  • I could not get this to work when I tried it, and have since switched to initiating validation using onblur in the HTML form. I will test this answer though, in case future people find it. – Brent Connor Mar 11 '15 at 20:33
  • With this script, the form submitted even though I input data that should have been false and should have prevented the form from submitting. – Brent Connor Mar 11 '15 at 20:40
  • Yes, this is quite tricky. Considering it's all in one action. get tags > submit > check if false > cancel submit. Either way you need to submit/post to the server with valid tags. I'll update my answer when I get chance. – Tez Wingfield Mar 12 '15 at 06:27