Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Regular Coder
    Join Date
    Feb 2005
    Posts
    136
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How can this code be shortened?

    How can the javascript be shortened? I always try to make code as short and efficient as possible. Can any shortcuts be applied here? Maybe there is a better way to wrap this up in a function to make it more usable?

    Basics of what it is doing:

    1. When the form button is clicked: showing loading span and making ajax call
    2. When ajax is success, hide loading span and show response message from XML
    3. Parsing XML response and adding error class on input if any errors
    4. Response message can be clicked to close


    Code:
    <html>
    <head>
    <style type="text/css">
    form {
    	margin:0;
    	padding:0;
    }
    label {
    	display:block;
    	float:left;
    	width:100px;
    	text-align:right;
    	padding-right:5px;
    	margin-bottom:3px;
    }
    input {
    	margin-bottom:3px;
    	padding:3px;
    	border:1px solid #aaa;
    }
    a {
    	border:1px solid #999;
    	background:#bbb;
    	color:#eee;
    	text-decoration:none;
    	padding:0 5px;
    	margin:3px 5px 0 0;
    	border-radius: 5px;
    	-moz-border-radius: 5px;
    	-webkit-border-radius: 5px;
    }
    fieldset {
    	width:270px;
    	padding:10px;
    }
    .error {
    	border:1px solid #cc6666;
    	background:#ffcccc;
    }
    #ajaxResponse {
    	background:#ffffcc;
    	border:1px solid #ffcc99;
    	padding:10px;
    	margin-bottom:5px;
    	display:block;
    	border-radius: 5px;
    	-moz-border-radius: 5px;
    	-webkit-border-radius: 5px;
    	cursor:pointer;
    	cursor:hand;
    }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    
    	// clears response span when span is clicked
    	$("#ajaxResponse").click(function(){
    		$(this).fadeOut("slow");
    	});
    
    	// hide stuff by default
    	$("#ajaxLoading").hide();
    	$("#ajaxResponse").hide();
    
    	// click trigger
    	$("#trigger").click(function(){
    	
    		// show loading span
    		$("#ajaxLoading").show();
    	
    		// set POST vars
    		var ifirstname = $("[name=firstname]").val();
    		var ilastname = $("[name=lastname]").val();
    		var icompany = $("[name=company]").val();
    	
    		// start ajax
    		$.ajax({
    			url: 'process.cfm',
    			type: 'POST',
    			data: 'signup=1&firstname='+ifirstname+'&lastname='+ilastname+'&company='+icompany,
    			dataType: 'xml',
    			success: function(xml){
    			
    				// clear any errors
    				$("input").removeClass("error");
    			
    				// re-hide stuff
    				$("#ajaxLoading").hide();
    				$("#ajaxResponse").hide();
    			
    				// find which errors are present and outline input
    				$(xml).find("error").each(function(){
    					var iName = $(this).text();
    					$("[name="+iName+"]").addClass("error");				
    				});
    				
    				// display response message
    				var res = $(xml).find("message").text();
    				$("#ajaxResponse").html(res);
    				$("#ajaxResponse").fadeIn('slow');
    			}
    		});
    	});
    });
    </script>
    </head>
    
    <body>
    
    	<form action="" method="POST" name="myForm">
    		<fieldset>
    			<legend>Contact Us</legend>
    			
    			<span id="ajaxResponse"></span>
    		
    			<label>First Name</label>
    			<input type="text" name="firstname" value="Tester"/><br/>
    			
    			<label>Last Name</label>
    			<input type="text" name="lastname" value="Testing"/><br/>
    			
    			<label>Company</label>
    			<input type="text" name="company" value="XYZ Company"/><br/>
    			
    			<label>&nbsp;</label>
    			<a href="#" id="trigger">Submit</a> <span id="ajaxLoading">Loading...</span>
    		</fieldset>	
    	</form>
    
    </body>
    </html>

    The process.cfm page:
    Code:
    <cfset error = 0>
    
    <cfxml variable="ajaxResponse">
        <response>
            <errors>
    	        <cfoutput>
    		<cfif LEN(#FORM.firstname#) LT 1> 
                        <cfset error = 1>               
                        <error>firstname</error>
                    </cfif>                
                    <cfif LEN(#FORM.lastname#) LT 1>    
                        <cfset error = 1>                           
                        <error>lastname</error>
                    </cfif>                
                    <cfif LEN(#FORM.company#) LT 1>
                        <cfset error = 1>               
                        <error>company</error>
                    </cfif>
                </cfoutput>
            </errors>
            
            <message>
                <cfoutput>
                    <cfif error GT 0>
    		    Please correct the fields in red
                    <cfelse>
                        Success!
                    </cfif>
                </cfoutput>
            </message>
        </response>
    </cfxml>
    
    <cfset xmlString = ToString(ajaxResponse)>
    
    <cfcontent type="text/xml" reset="yes">
    <cfoutput>
    	#xmlString#
    </cfoutput>

  • #2
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Why dont you just put the jQuery script inside a .js file and then require it in the header as <script src="[yourfilename]" type="text/javascript"></script> as this way the html sc is small but from what i see the jQuery code can't be shortend as it is as short as it can get.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,449
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    I always try to make code as short and efficient as possible.
    Pardon me, but what's the point??? By using jQuery, you are forcing the user's browser to download the entiery jQuery library. So your own JS code invoking jQuery is miniscule, in comparison.

    And then, to be fair, the entire jQuery library is large, but likely significantly smaller than the <img> files you will use to display your page. If you want to cut down in load time, which is really the only reason to worry about size, look carefully at your image files and see if they can be compressed further. More than likely, that will be your biggest gain. (Of course, you may not be using any images on the page, in which case the jQuery library will indeed be the biggest thing downloaded.)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,449
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    Yes, I see that your code has no <img> tags.

    Okay, so your *ENTIRE* code is 3KB in size.

    The jQuery library you are using is 71KB in size.

    So the browser will take more than 20 times as long to download the jQuery library as it takes to load your entire HTML page. Seems kind of pointless to worry about your own code size, doesn't it?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Regular Coder
    Join Date
    Feb 2005
    Posts
    136
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the replies. I was merely just seeing if there was a way to shorten the code (possibly making it more readable... maybe even more re-usable).

    I like things that are short and flexible. Possible to wrap this up in a nice function that accepts a trigger, loadingDIV, and responseDiv?

    My javaScript/jQuery skills are not the best.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,449
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    Well, I have to tell you that I personally think your code is neat, clean, readable, and more than concise enough. If there are some "tricks" to make it a bit shorter, I think you should be hesitant to use them. All those qualities I listed are what make for *maintainable* code, and to me that's more important than making shorter code. WAY more important.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Regular Coder
    Join Date
    Feb 2005
    Posts
    136
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hehe. Ok. Thank you for your input and opinion!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •