Link to home
Start Free TrialLog in
Avatar of brihol44
brihol44

asked on

jquery validate works first time but not 2nd submit

Ok, so I think I have a pretty easy question here but I'm awarding the max because it might not be.

Basically, I have on my sharing.cfm page...

function refreshSharingContent() {
    $("#getSharing").load("app/inc/inc_sharing.cfm");
}


$("#sharingForm").validate({

        submitHandler: function(form) {

            var data = $("#sharingForm").serialize();

            $.ajax({
                type: "POST",
                url: "app/func/func_sharing.cfc?method=sendInvite",
                data: data,
                cache: false,
                success: function() {
                    refreshSharingContent();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
                }
            });
        }

    });

Open in new window

on my "inc_sharing.cfm" file I have the actual form. So...

1. Everything works perfectly on the first submit.
2. On the 2nd submit I seem to lose the async or ajax functionality and it fully submits the page.

IF I... put that snippet of code on "inc_sharing.cfm" it works perfectly all the time. I really would like to keep my code clean so I'm banging my head trying to figure out with keeping my main master.js in tact as far as not spaghetti coding things on various pages.
Avatar of dgrafx
dgrafx
Flag of United States of America image

replace your success function with:
success: function() {
      $("#getSharing").load("app/inc/inc_sharing.cfm");
}
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of brihol44
brihol44

ASKER

Tried both of these and they don't work.. Same results.
I cannot help you more without seeing the page or at least the error messages from the console. "It did not work" does not give me much to go on
ok I understand, there's no error message just to let you know. Everything works fine on the first submit. The 2nd submit the form loses the ajax functionality and does a standard full page refresh without submitting anything. And again like I mentioned if I put that snippet of code I did supply on the "inc_sharing.cfm" page everything works perfectly.

<cfinclude template="app/inc/inc_header.cfm">

<script src="assets/plugins/jquery-validate/jquery.validate.min.js"></script>

<div class="container">
	<div id="getSharing"><cfinclude template="app/inc/inc_sharing.cfm"></div>
</div><!-- /.container -->

<script>
$(function() {

	function refreshSharingContent() {
		$("#getSharing").load("app/inc/inc_sharing.cfm");
	}

    $("#sharingForm").validate({

        submitHandler: function(form) {

            var data = $("#sharingForm").serialize();

            $.ajax({
                type: "POST",
                url: "app/func/func_sharing.cfc?method=sendInvite",
                data: data,
                cache: false,
                success: function() {
                    $("#getSharing").load("app/inc/inc_sharing.cfm");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
                }
            });

        }

    });

});
</script>

Open in new window


inc_sharing.cfm

    <div class="row">
        <div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
            <h2>Share</h2>

            <form id="sharingForm"  method="post" action="">
            <div class="control-group-container">
            <div id="addinput">
                <div class="input-group input-group-lg">

                  <input type="email" name="p_new_1" id="p_new_1" class="form-control" placeholder="Enter Email Address" required/>

                  <span class="input-group-btn">
                    <button class="btn btn-default" type="button" id="addNew"><span class="glyphicon glyphicon-plus"></span></button>
                  </span>

                </div><!-- /input-group -->
             </div>
             </div>
             <div class="row">
                <input type="hidden" name="numberOfFields" id="numberOfFields" value="1" />
                <div style="margin-top: 40px;" class="col-xs-12 col-md-12"><input type="submit" id="sendInvites" name="share" value="Send Invitation To Above Emails" class="btn btn-default btn-block btn-lg" /></div>
            </div>
            </div>
            </form>
        </div>
    </div>

Open in new window

Since you do NOT want to submit the form at all, you need to return false in the submit handler
You mean like so? I'm pretty sure I tried that but I'll be able to try later this evening. Thx

<script>
$(function() {

	function refreshSharingContent() {
		$("#getSharing").load("app/inc/inc_sharing.cfm");
	}

    $("#sharingForm").validate({

        submitHandler: function(form) {

            var data = $("#sharingForm").serialize();

            $.ajax({
                type: "POST",
                url: "app/func/func_sharing.cfc?method=sendInvite",
                data: data,
                cache: false,
                success: function() {
                    $("#getSharing").load("app/inc/inc_sharing.cfm");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
                }
            });

            return false; 

        }

    });

});
</script>

Open in new window

Yes like that
Ok, I tried that and it didn't work. I guess I have to spaghetti code my stuff and put that snippet on the other page to make it all work right.

Here's another same type of scenario as one last result if that sparks any other ideas.

http://stackoverflow.com/questions/10609567/how-do-i-get-my-jquery-validator-code-to-run-a-second-time-after-a-form-has-alre
I just realise you posted your code - I do not see my changes anywhere

$(function() {
   initVal();
});
function refreshSharingContent() {
   $("#getSharing").load("app/inc/inc_sharing.cfm",initVal);
}

Also I do not see any reason to use validate at all since you seem to just abuse the validator to ajax

So IF you need validation do this
function initVal() {
   $("#sharingForm").validate({
     rules: {
     }
   });
   $("#sharingForm").on("submit",function(e) {
     if ($(this).valid() {
       e.preventDefault(); // cancel submission
       var data = $(this).serialize();
        $.ajax({
          type: "POST",
          url: "app/func/func_sharing.cfc?method=sendInvite",
          data: data,
          cache: false,
          success: function() {
            $("#getSharing").load("app/inc/inc_sharing.cfm",initVal); // call the initVal!!!
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
          }
        });
     });
  }
}
$(function() {
  initVal();
});

Open in new window

and if not, just remove the validation stuff:
function initForm() {
   $("#sharingForm").on("submit",function(e) {
       e.preventDefault(); // cancel submission
       var data = $(this).serialize();
        $.ajax({
          type: "POST",
          url: "app/func/func_sharing.cfc?method=sendInvite",
          data: data,
          cache: false,
          success: function() {
            $("#getSharing").load("app/inc/inc_sharing.cfm",initForm); // call the initForm!!!
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
          }
        });
     });
}
$(function() {
  initForm();
});

Open in new window

Sorry, mplungjan... I did try that code but for some reason it wasn't working the first time. I've noticed that even after changing the code trying to come up with a different solution, I've had to do SHIFT refresh because 1 refresh wasn't enough to see a change.

Thank you, thank you! ... if you do have a minute can you please explain why I do that for each piece below... I do have some other pages where I'm having to embed js on the .load page so I'm wondering if I can correct my code (no spaghetti) on those pages as well. Just might help to understand it a bit more. And again sorry, I'll be more careful in the future.

$(function() {
   initVal();
});
function refreshSharingContent() {
   $("#getSharing").load("app/inc/inc_sharing.cfm",initVal);
}
When you load a form, into a div using Ajax, all the event handlers of the previous content of the div are removed. You then simply need to re-attach them to the new form.

The load command works like this:

$("#someID").load("someURL",function() { something I want to do after load });

I just reused the function since we needed to do it on page load too

$("#someID").load("someURL",nameOfAFunctionIDefinedEalierWithoutTheBrackets);

I could have done

$("#someID").load("someURL",function() {
  initVal();
});

instead of

$("#someID").load("someURL",initVal);