Solved

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

Posted on 2014-03-23
17
1,967 Views
Last Modified: 2014-03-25
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
0
Comment
Question by:andieje
  • 5
  • 4
  • 2
  • +3
17 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39948785
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?
0
 

Author Comment

by:andieje
ID: 39948793
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
0
 
LVL 58

Expert Comment

by:Gary
ID: 39948802
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();
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39948856
Try this : $(document).trigger("ready");
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39948862
Or as suggested by Gary :

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

So in the success ajax callback, you've :

success: function() {
        init();
}
0
 

Author Comment

by:andieje
ID: 39949742
@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 :)
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39949898
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

0
 

Author Comment

by:andieje
ID: 39949906
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 ;)
0
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.

 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39949921
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
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39949933
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

0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39949953
@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.
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39950113
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

0
 

Author Comment

by:andieje
ID: 39951081
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?
0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 250 total points
ID: 39951118
It's definitely the way to go. As for making sure it fires at the right time - that's exactly the point of the document.ready block - it gets fired when the document is ready.

A ready() block that's contained in the AJAX response will be fired when that 'document' is ready - i.e. it's loaded into the DOM.
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 250 total points
ID: 39951234
greetings  andieje, , you are at a point for using AJAX in a more complex way, as you (in ajax success) not only Change-Add an HTML Form, BUT you need to also have different validation inputs and values set in code for your jQuery.validator, this may can get complicated, since you use AJAX returns to do the "validation"  as -

jQuery.validator.addMethod('checkIt', function(val, element) {
  var x = $.ajax({type: "POST", async: false,
  url: "ajax/validation/checkIt.php", data: "Check_It=" + val,
  success: function(resp) { if (resp == '0') {return true;} else {return false;} }

For me it is not a good Idea to send javascript code as a string back from the server, and then try to execute that javascript string as code with eval( ) OR write it to a div like this  $("#divID").html("<script>"+JS_string+"</script>"); , , although both of those ways can give you some workable code, BUT if the code is complex, or you do NOT keep track of javascript variables, or you do several many ajax calls to javascript, then I have seen the browser JS engine get confused (or the javascript code was mal-formed) so JS things do not work right.

What I usuall do is create a JS function that takes an array or object from ajax as the parameter, and that function will set up the NEW javascript functioning -
function setValidate(obj_from_ajax) {
  jQuery.validator.addMethod(obj_from_ajax.input, function(val, element) {
    var x = $.ajax({type: "POST", async: false,
    url: obj_from_ajax.url, data: obj_from_ajax.post + val,
    success: function(resp) { if (resp == '0') {return true;} else {return false;} }
  });
  }, 'Registration already exists');
}

Open in new window

 the code above is untested, and WILL not be enough to do what you need because I have left out things like -
$(obj_from_ajax.formID).validate({

and many other things, you might call it like -
$.ajax({url: 'ajax/process_form.php', type: "POST",
  data: $("#login").serialize(),
  success: function(result) {
    var objAjx = func2parse(result);// JSON maybe?
    setValidate(objAjx);
}else{

But there is much more to do in the code depending on several factors needed in the new validate, my code above is a simplified to give you an idea.
0
 

Author Closing Comment

by:andieje
ID: 39954420
Thanks very much. I didn't know any of that!!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

758 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

17 Experts available now in Live!

Get 1:1 Help Now