Solved

ColdFusion with jQuery ajax - how to

Posted on 2012-03-20
3
550 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 16

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 16

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Fixing some Issues with regex again 9 32
Fixing Old Legacy Code 1 35
REReplaceNoCase help 1 31
BACKUP of mysql database from mysql server - using Coldfusion 9 36
Today, I was working on some optimization and spam-stopping techniques when I encountered Ben Nadel's post to reduce spam feature using Math (http://www.bennadel.com/blog/197-How-I-Stop-Spammers-On-My-ColdFusion-Blog.htm). While this method is not o…
Hi. There are several upload tutorials using jquery and coldfusion. I found a very interesting one here Upload Your Files using Jquery & ColdFusion and Preview them (http://www.randhawaworld.com/) . I did keep the main js functions but made sever…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

785 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