Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1780
  • Last Modified:

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.
0
brihol44
Asked:
brihol44
  • 6
  • 5
1 Solution
 
dgrafxCommented:
replace your success function with:
success: function() {
      $("#getSharing").load("app/inc/inc_sharing.cfm");
}
0
 
Michel PlungjanIT ExpertCommented:
What would that change? The functionality is identical whether he calls a function or executes the statement directly.

If you load a new form you need to hook it up of course.


$(function() {
   initVal();
});
function refreshSharingContent() {
   $("#getSharing").load("app/inc/inc_sharing.cfm",initVal);
}
function initVal() {
    $("#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

0
 
brihol44Author Commented:
Tried both of these and they don't work.. Same results.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Michel PlungjanIT ExpertCommented:
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
0
 
brihol44Author Commented:
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

0
 
Michel PlungjanIT ExpertCommented:
Since you do NOT want to submit the form at all, you need to return false in the submit handler
0
 
brihol44Author Commented:
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

0
 
Michel PlungjanIT ExpertCommented:
Yes like that
0
 
brihol44Author Commented:
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
0
 
Michel PlungjanIT ExpertCommented:
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

0
 
brihol44Author Commented:
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);
}
0
 
Michel PlungjanIT ExpertCommented:
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);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now