Solved

ColdFusion with jQuery ajax - how to

Posted on 2012-03-20
3
540 Views
Last Modified: 2012-03-22
Hi Experts,

I have a coldfusion page that I include the jquery library in. I have a section where there are text inputs for the user to enter info, and then save to database. I don't have a form tag in here but just 3 input fields.

I started implementing jquery solution to this but not sure on how to proceed. First, I need to validate all 3 of the text fields. If any of those fails validation, I need to display an alert box with all the error fields and then also add a line in red just below the failed input's text box (like an addClass in jquery or something), and return false.

Second, if all the validation is successful, then I need to do a $.ajax and call a method in a cfc, pass in the params, then in the cfc's method do the database actions and then return an alert box that data was successfully saved as well as add a div with text in green and a check mark.

Here's what I have so far:

<!---.cfm with text inputs--->
<script type="text/javascript" src="/js/userInput.js"></script>
<div id="successORfail"><!---this is where I need to display the results of the operation---></div>
<cfoutput query="schoolData">
<table>
    <tr>
        <td>
               <input type="text" name="txt1" id="txt1" value="#school_name#" />
              <!---this is where I need to display in red if txt1 fails validation--->
        </td>
    </tr>
    <tr>
        <td>
               <input type="text" name="txt2" id="txt2" value="#school_dist#" />
              <!---this is where I need to display in red if txt2 fails validation--->
        </td>
    </tr>
    <tr>
        <td>
               <input type="text" name="txt3" id="txt3" value="#school_principal_info#" />
              <!---this is where I need to display in red if txt3 fails validation--->
        </td>
    </tr>
    <tr>
         <td><input type="button" name="save" id="save" value="save info" /></td>
    </tr>
</table>
</cfoutput>
<!---end .cfm page--->
<!---userInput.js file--->
$(document).ready(function(){
      $("#save").click(function(){
       /*this is where I need to do the validation:
         txt1: not blank and regular expression to make sure there are no special characters except underscore(_)
         txt2: same as above
         txt3: not mandatory but if not blank, check if there is a URL, and if there is URL then check it is formatted correctly (www.myurl.com/xxx/yyy/zzz etc)
         If validation fails, then display alert box with any/all of the reasons for fail; then add a line of text under any/all of the text boxes that have failed validation with reason in red.
         return false.
         If validation is successful, then move on to the ajax call.*/
        
            $.ajax(
                  {
                        type: "get",
                        url: "schools.cfc",
                        data: {
                              method: "savetodb",
                              name: $("#txt1").val(),
                              dist: $("#txt2").val(),
                              principal: $("#txt3").val()
                        },
                        dataType: "json",
                        
                        success: function(objResponse){
                              //if(objResponse.SUCCESS){
                                    alert(objResponse);
                                    var msgSuccess = "<img src='green.png' width='26' height='26'>";
                                    msgSuccess = msgSuccess + "&nbsp;" + "<span style='font-weight:bold;font-size:13px'>" + "Saved!" + "</span>";
                                    $("#successORfail").html(msgSuccess);
                              /*}
                              else{
                                    alert("Error occurred!");
                              }*/
                        }
                  });
            return false;
      });
});
<!---end .js file--->
<!---schools.cfc file--->
<cfcomponent>
      <cffunction name="savetodb" access="remote" returnformat="json" returntype="string" output="false">
            <cfargument name="name" type="string" required="yes">
        <cfargument name="dist" type="string" required="yes">
        <cfargument name="principal" type="string" required="yes">

            <cftry>
                  <!---a bunch of db queries, success or fail--->
                  <cfset myResult="Success" />
            <cfcatch type="any">
                  <cfset myResult = "There was an error!" />
            </cfcatch>
            </cftry>
 
            <cfreturn myResult>
      </cffunction>
</cfcomponent>
0
Comment
Question by:roger_v
  • 2
3 Comments
 
LVL 15

Expert Comment

by:Gurpreet Singh Randhawa
ID: 37746009
do it this, as you are making ajax call, just do the checking in the server side and the message will be returned to the page itself, why doing double job, So try it like this

as an example for ur understanding, i am just taking one field
<style>
.error { color: red; padding-left: 10px; }
</style>
<tr>
        <td>
               <input type="text" name="txt1" id="txt1" value="#school_name#" />
              <span class="error"> </span>
        </td>
    </tr>

in your ajax call: do it like this

$(document).ready(function() {
$('.error').hide();
$('#submit').click(function () {
var name = $('.uname').val();
var data='uname='+name;
$.ajax({
type:"POST",
url:"validateuser.cfm",
data:data,
success:function(html) {
$('.error').show();
$('.error').text(html);
}
});
return false;
});
});

now on ur validate.cfm page do a regex check like this

<cfif NOT RefindNoCase("^[a-zA-Z0-9]+$",form.uname)>
Error! Only Alphabets and numbers are allowed
<cfelse>
ur cfc code
</cfif>
0
 
LVL 1

Author Comment

by:roger_v
ID: 37747890
Hi myselfrandhawa,

The reason I'm doing it this way is because the user wants it like this. User wants both a javascript alert box with any/all input errors, followed by text in red color underneath each input box that has failed validation.

The 2 main road bumps I've hit are:
1. Looping through all the fields and doing regex check in jquery
2. Showing the errors below the text fields
0
 
LVL 15

Accepted Solution

by:
Gurpreet Singh Randhawa earned 500 total points
ID: 37748560
btw ajax call is somewhat user will experience as such as client-side like if i am using the value returned by the ajax page to be displayed in div, i can do the same in alert

$.ajax({
type:"POST",
url:"validateuser.cfm",
data:data,
success:function(html) {
var msg = $('.error').text(html);
alert(msg);
}
});
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

PROBLEM:  How to open a cfwindow or run a function on double click of a cfgrid row. One of my clients wanted to be able to double click on a row item to get more detailed information about a transaction and to be able to modify the line items i…
Sometimes databases have MILLIONS of records and we need a way to quickly query that table to return the results me need. Sure you could use CFQUERY but it takes too long when there are millions of records. That is why SOLR was invented. Please …
This video discusses moving either the default database or any database to a new volume.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

746 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

10 Experts available now in Live!

Get 1:1 Help Now