Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Wednesday, November 27, 2013

Displaying multibyte characters or returning multibyte characters by AJAX call in ColdFusion

Sometimes we need to display a multibyte characters like Japanese or Chinese in our application or we have to build a application which can be converted into Japanese, Chinese or to some other non-English language.

If we are going to show any non-English language directly in our ColdFusion code then we will get some corrupted text.
Example: In below code I am simply trying to show a Japanese sentence.
<cfset x = "ユーザー名および/またはパスワードが正しくありません。もう一度やり直してください。" />
<cfoutput>#x#</cfoutput>
When I run above code I got following output in my browser.

Our browser is not displaying any Japanese character which we wants to display instead it's showing some other characters. How to display that?

It's very simple, just add "<cfprocessingdirective pageencoding="UTF-8">" at the start of the page like below:
<cfprocessingdirective pageencoding="UTF-8">
<cfset x = "ユーザー名および/またはパスワードが正しくありません。もう一度やり直してください。" />
<cfoutput>#x#</cfoutput>
When I run the code I got following output.

So, I am getting the desired output by using "cfprocessingdirective". It's always advisable to put this tag in onRequest method of Application.cfc in our application so that we don't have to place it in all cfm pages of our application.

Our cfm page now able to display multibyte characters in browser. What about AJAX calls? What will happen when we will make an AJAX call to a ColdFusion component which returns some multibyte characters?

Let's explore...
Here is my "testchar.cfm" code:
<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
        <script>
        $(document).ready(function() {

            //Making AJAX call to function returnChar present in component testchar.cfc which returns
            //the same Japanese string.
            $("#reloadC").click(function() {
                $.ajax({
                    type: "post",
                    url: './testChar.cfc?method=returnChar',
                    success: function(data) {
                        $('#multi-char').html(data);
                    },
                    dataType: 'json'
                });
            });
        });
        </script>
    </head>
    <body>
        <h3>Display Multibyte Character</h3><hr/>
        <p>Press Refresh button to get multibyte characters from AJAX call</p>

        <!--- Press refresh button to get multibyte characters from AJAX call --->
        <input type="button" name="reloadC" id="reloadC" value="Refresh" />
        <div id="multi-char" style="width:500px"></div>
    </body>
</html>
Here is our "testchar.cfc" code:
<cfcomponent output="true">
    <cffunction name="returnChar" access="remote" returnformat="JSON">
        <cfset x = "ユーザー名および/またはパスワードが正しくありません。もう一度やり直してください。" />
        <cfreturn x />
    </cffunction>
</cfcomponent>
When I runs the testChar.cfm page and clicks the refresh button I gets following output.

So, again I am getting unwanted result. So, how to solve in ColdFusion component?
Here we have to place "cfprocessingdirective" tag after cfcomponent tag and before starting of any function like below.
<cfcomponent output="true">
<cfprocessingdirective pageEncoding = "UTF-8" suppressWhiteSpace = "yes">
    <cffunction name="returnChar" access="remote" returnformat="JSON">
        <cfset x = "ユーザー名および/またはパスワードが正しくありません。もう一度やり直してください。" />
        <cfreturn x />
    </cffunction>
</cfprocessingdirective>
</cfcomponent>

No change is required in the "testChar.cfm" page.

When I runs the testChar.cfm again and clicks the refresh button then I gets following output.

Hope it may save your time!!!

Thursday, October 31, 2013

Creating a Random Captcha with refresh Option

We all know that creating captcha is not a tough job in ColdFusion. But, one newbie in ColdFsion just asked me to help in creating a random captcha for his application.

I thought to share with others.

I have divided the entire code into three parts.

  1. captcha.cfm - Page where we will display the captcha image.
  2. Util.cfc - It contains a user defined function "generateRandomText" to generate random captcha text.
  3. refreshCaptcha.cfm - Page which will handle AJAX call while refreshing captcha image.

Lets see the "captcha.cfm" below:

Here, in above code I have used "ImageCreateCaptcha" function, which is added in ColdFusion 10 for captcha generation.

Lets see the "Util.cfc"

In this file, I have written a function called "generateRandomText"  for generating captcha string. Logic is very simple, you can modify it according to your requirement.

Next, come to "refreshCaptcha.cfm":

We are making AJAX call to this file which again generates random captcha image and sends to browser for display.

So, this is whole story for generating and refreshing captcha image in ColdFusion!!!

Tuesday, March 06, 2012

Escape plus(+) sign in url

Escape plus(+) sign in URL

When we pass some special characters to server side(in URL) for processing we prefer to use the JavaScript function escape(). The work of escape() is to convert the special characters into corresponding ASCII characters.  The server side code automatically does the conversion from ASCII to the original characters.

       But when we pass a plus(+) sign in the escape() function it doesn't converts the plus(+) sign to the corresponding ASCII character. Rather it replaces the plus (+) sign with a space character. Which cause many issue during the AJAX call to the server side.

Also, if we are thinking to avoid escape() function and pass the string directly to then also it will not work.

Solution:
  When we are escaping a string before escaping that we will convert all the plus(+) sign with the corresponding ASCII character . Then during escape function call it will work like the normal way.

e.g- 
var  strQueryString = "SELECT 1+1 FROM EMPLOYEES";
  1. escape(strQueryString).replace(new RegExp( "\\+", "g" ),"%2B") (will convert plus sign to ASCII)
  2. escape(strQueryString) (will not convert plus sign to ASCII)

You can simply see the difference by the above  code.

Friday, January 13, 2012

Asynchronous AJAX CALL Issue

I was working with some jQuery server side validation I got an issue of asynchronous AJAX call.
Let me describe with the following code:
 
//Validate Media path from server
$('input[name$="btnSubmit"]').click(function(){
   var stCurrentMediaPath = $('#dspForm_vcMedia_File_Path').val();
   var isValidPath = false;
  
    if(stCurrentMediaPath.length){
 
         //AJAX call to validate the Media path before form submission
        $.ajax({
            type: "GET",
            url: "index.cfm?inc=AddTaskAJAXListener&ajax=true",
            data: "method=validatePhysicalPath&vcPhysicalPath=" + escape(stCurrentMediaPath),
            statusCode: { 404: function() {
                alert('page not found');}
            },
            success:function(response){
                response = jQuery.trim(response).toLowerCase();
               
                if(response.toLowerCase() == 'yes'){
                    isValidPath = true;
                } else {
                    alert('Provided Media Path does not exist in system.');
                    isValidPath = false;
                }
            }
        });
        /*If the isValidPath is false then do the necessary action if true then submit the form. */
    }
});
 
But I got an issue: isValid is always false it takes the initial value which I have assigned at the time of declaring that variable. This is happening because our AJAX call is asynchronous call. The flow of execution of the block of code does not wait for the AJAX call to return. The flow initiates the AJAX call but does not wait for the result. So each time we will get isValid = false.

    So, our next step is how we can make the code flow linear execution(wait for AJAX call to finish). We can do that by making a synchronous AJAX call.

Please follow the block of code which will make the synchronous AJAX call:

//Validate Media path from server
$('input[name$="btnSubmit"]').click(function(){
   var stCurrentMediaPath = $('#dspForm_vcMedia_File_Path').val();
   var isValidPath = false;
   
    //Sync AJAX call to validate the Media path before form submission
    if(stcurrentMediaPath.length){
        $.ajax({
            async: false,//This part will make the synchronous AJAX call
            type: "GET",
            url: "index.cfm?inc=AddTaskAJAXListener&ajax=true",
            data: "method=validatePhysicalPath&vcPhysicalPath=" + escape(stCurrentMediaPath),
            statusCode: { 404: function() {
                alert('page not found');}
            },
            success:function(response){
                response = jQuery.trim(response).toLowerCase();
               
                if(response.toLowerCase() == 'yes'){
                    isValidPath = true;
                } else {
                    alert('Provided Media Path does not exist in system.');
                    isValidPath = false;
                }
            }
        });
        /*If the isValidPath is false then do the necessary action if true then submit the form. */
    }
});

Hope this will help you.

Followers