Solved

jquery validate works first time but not 2nd submit

Posted on 2014-04-20
12
1,300 Views
Last Modified: 2014-04-23
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
Comment
Question by:brihol44
  • 6
  • 5
12 Comments
 
LVL 24

Expert Comment

by:dgrafx
Comment Utility
replace your success function with:
success: function() {
      $("#getSharing").load("app/inc/inc_sharing.cfm");
}
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
Comment Utility
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
 

Author Comment

by:brihol44
Comment Utility
Tried both of these and they don't work.. Same results.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
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
 

Author Comment

by:brihol44
Comment Utility
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
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Since you do NOT want to submit the form at all, you need to return false in the submit handler
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:brihol44
Comment Utility
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
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Yes like that
0
 

Author Comment

by:brihol44
Comment Utility
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
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
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
 

Author Closing Comment

by:brihol44
Comment Utility
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
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
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

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now