Link to home
Start Free TrialLog in
Avatar of andieje
andieje

asked on

how to dynamically change the code in document.ready after an ajax callback

Hello

I have a page where I am making an ajax callback. The page loads various javascript libraries and has some code in the document.ready function

<script type="text/javascript">
        $(document).ready(function(){
	
            $("#form").submit( function () {  
			
			
				$.ajax({
  					url: 'ajax/process_form.php',
					type: "POST",
					data: $("#login").serialize(),
					
  					
  					success: function(result) {
						
					//result returns another form to be loaded onto the page	
					

             			}else{
                  			$("#errorMessage").html(result);
            			}
  					},

Open in new window

However the returned html is another form and I need to change the code in the document,ready function. How do I 'overwrite' the old document,ready and retrigger it.

I could have the document.ready code in a div tag and then overwrite it  with my new document.ready it in the success part of the ajax call and then trigger it with $(document).trigger("ready");

Or in the success part of the jquery.ajax call i could have this code
$.getScript( "ajax/doc_ready.js" ) which has the appropriate document.ready for the 'new' page after the ajax submission.

I don't know if either of these methods will cause document.ready to be fired at the right time after an ajax postback


I hope that makes sense. This must happen such a lot that I assumed I would easily find a standard design patter. However people dont seem to load code which needs to re-trigger document.ready with different content after an ajax call.

Thanks very much in advance for your help
Avatar of Gary
Gary
Flag of Ireland image

document.ready only fires at page load so trying to change it is a pointless exercise as it will never fire again.

What exactly is it you are trying to do when the ajax has finished?
Avatar of andieje
andieje

ASKER

when i load a new form into the page after my ajax postback i have to set up all its validation and its submit function. When i load a page for the first time i normally do this i the document.ready as you can see in the example. Where do I do this in the page when my form is loaded via an ajax call

So for example I load a form dynamically into the page following my ajax call and I somehow have to add this type of code to the page too to handle validation and submission of the form

$("#form").submit( function () {  
                  
                  
                        $.ajax({
                                url: 'ajax/process_form.php',
                              type: "POST",
                              data: $("#login").serialize(),
                              
                                
                                success: function(result) {
                                    
                              //result returns another form to be loaded onto the page      
                              

                               }else{
                                    $("#errorMessage").html(result);
                              }
                                }, etc

Open in new window


As i said when i first load a page this goes inn document.ready but I dont know where to put it when the form is loaded dynamically via ajax.

Thanks a lot. I hope that makes sense
So in the ajax success just call your validation plugin again after you have added the new form.
Don't know which plugin you are using but something along the lines of

$("#new-form-id").validate();
Try this : $(document).trigger("ready");
Or as suggested by Gary :

function init(){
    // your code here
}
$(document).ready(init);

So in the success ajax callback, you've :

success: function() {
        init();
}
Avatar of andieje

ASKER

@gary
But the problem is that the code called by the newly generated dynamic form also has to be added to the form

so dont the validate rules for the new form have to be added in the document.ready form method

Iffi just call this inn the success funtion of the ajacx callback
$("#new-form-id").validate();

Where do i add the rules for my forms. In the past when i have added a new form to the page i have typically echoed it back incuding  its validation with jquery like this in the success function

script>
	$(document).ready(function() {

		
		jQuery.validator.setDefaults({
    		errorPlacement: function(error, element) {
       			 error.appendTo('#invalid_' + element.attr('id'));
				
  				  }
		});

		jQuery.validator.addMethod('checkVehicleRegistration', function(val, element) {
			
				var x = $.ajax({
				type: "POST",
				async: false,
				url: "ajax/validation/checkVehicleRegistration.php",
				data: "vehicle_reg=" + val,
				success: function(resp) {

				},
				error: function(e) {alert('checkVehicleRegistration failed' + e);}
			});	
			
			if (x.responseText == '0') {return true;} else {return false;}
			
		}, 'Registration already exists');
		
		
		jQuery.validator.addMethod('checkCustomerEmail', function(val, element) {
				if (val == '' || val == $('#old_email').val()) {
					
					return true;
				} else {
					
				
					var x = $.ajax({
					type: "POST",
					async: false,
					url: "ajax/validation/checkCustomerEmail.php",
					data: "customer_email=" + val,
					success: function(resp) {
	
					},
					error: function(e) {alert('checkCustomerEmail failed' + e);}
					});	
					
					if (x.responseText == '0') {return true;} else {return false;}
				}
			
			
		}, 'Email in use');
		
		$("#details_form").validate({
			onkeyup: false,
			onfocusout: false,
			rules: {
			
				name: {
					required: true
				},
				phone: {
					required: true
				},
				customer_email: {
					email: true,
					checkCustomerEmail: true
				},
				vehicle_reg: {
					required: true
				
				}

			},
			messages:{
				
				name: {
					required: "Name required"
				},
			
				phone: {
					required: "Phone required"
				},
				customer_email: {
					email: "Invalid email",
					checkCustomerEmail: "Email in use"
				},

				vehicle_reg: {
					required: "Registration required"
				}

			} 
				

			
  						
		});



});


		

</script>

Open in new window


If i jut call newformid.validate where do i add its vaidation rules

Am i making myself clear? Sorry . The problem that the code in the doucment.ready is dynamic with each page load. I did think that on first page load i couod I incude the rules for all forms even if they are not present on the page. This crashed the page though as it refered to objects that werfe not present.

Thanks for all your help. Its greaty appreciate. I am not a php or jquery programmer so its a bit of a steep curve for me :)
You can have as many document.ready blocks as you need so you could just wrap the whole validation script in your form. This way, when you load your form (either normally or with ajax), the document.ready block inside the form will get fired. The benefit of this is that the validation code is directly tied to your form - if you have 10 different forms, they'll each have their own code 'embedded' in themselves

<form>
....
</form>
<script>
$(document).ready(function() {
//validation code goes here
})

Open in new window

Avatar of andieje

ASKER

sorry chris but I dont understand your answer. Will the document.ready get fired if it is inside the form? In your example tje document.ready is not inside the form. However this does sound like the right way of doing it. I just dont fully understand jquery so I just use other people's bits and pieces of codes here and there without a proper understanding

Thanks ;)
A document.ready block will get fired where ever it is. If you have 4 document.ready blocks scattered throughout your page, they'll all get fired.

The idea here is that by putting a document ready block inside the code that's returned by your AJAX call, it will only get fired when that part is loaded. It doesn't matter that it's not inside the form, just that it's part of the HTML that's returned from your AJAX call. Once the HTML snippet is loaded by AJAX, it will fire the document.ready block contained within that snippet
I wonder if you are thinking of js like php where it has to be in order of your html code.  That is not the case.    You can set up your validation code for your forms inside your <script> tags that are either in your <head> or just above the closing </body>.  

In the sample below, you can have multiple ready functions or you can place your form validation under just one.

Notice the code is setting up for validation of form2 but it is not there until you inject it via ajax.   The javascript is already loaded in the browser and is waiting for form2 to be validated.  It should be ok to validate form2 after the ajax call without a page refresh.

<script>
$(document).ready(function() {
    
     //validation code goes here form1
})
$(document).ready(function() {
     //validation code goes here form2
})

<form id="form1">
</form>
<div id="Form2GoesHere">
  <!-- form 2 gets inserted here after ajax call -->
</form>

Open in new window

@Scott

The problem with that approach is that the validation is being attached to form 2 before it exists. It won't then bind the validation to the form after it's been loaded by AJAX.
You can make the validation a stand alone function and call it when the new form is injected   http://jsbin.com/modocaqe/1/edit?html,output

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <meta charset="utf-8">
  <script>
    $(function () {

    $.ajax({
        url: "http://jsbin.com/wuzozobu/1.js",
        dataType: "html"
    }).done(function (data) {
        $("#form2here").html(data);
        test(data);

    });

});
// validate
function test(theData) {
    var $response = $(theData);
    var form2 = $response.find("input#test").val();
    if ($("#test").val() === "stuff") {
        alert("yes");
    }
}
    </script>
  <title>JS Bin</title>
</head>
<body>
  <div id="form2here"></div>
</body>
</html>

Open in new window

Avatar of andieje

ASKER

Regarding this comment: ID: 39949921

I didnt know I could do that so that is the way to go I think :)

How can i be sure the document.ready will be fired at the right time? Will it be fired after the form has loaded? Does jquery take care of this?
SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland 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
ASKER CERTIFIED SOLUTION
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 andieje

ASKER

Thanks very much. I didn't know any of that!!