Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET

ASP.NET Real-time Currency Converter using API (Google, Yahoo), Web service, and jQuery Ajax

Rate me:
Please Sign up or sign in to vote.
4.96/5 (36 votes)
15 Jul 2012CPOL5 min read 177.2K   14K   54   34
ASP.NET Real-time Currency Converter using API (Google, Yahoo), Web service, and jQuery Ajax explained in detail
In this article, I’m going to show an ASP.NET Real-time Currency Converter using Google’s/Yahoo’s API, jQuery Ajax, Webservice, $.ajax beforeSend Success Error, Webservice ScriptService Attribute, WebClient DownloadString

Image 1

Table of Contents

Introduction

Google, Yahoo provides many APIs that can be used in our applications. Here, I’m going to show a Real-time Currency Converter using Google’s/Yahoo’s API.

For this article, I have created a web application from scratch that will pull data from Google/Yahoo and will display in user interface using jQuery Ajax and Web service. For your reference, I have attached the source code with this article. Your votes, suggestions and feedback are highly appreciated to improve the quality of this and upcoming articles, please don't forget.

Let me try to explain the steps for you…

Background

Google is using their own hidden API for showing the real-time currency rate in their search engine. Why it's hidden, because this API doesn't come with an official document. If you haven’t checked this service yet, then click here or else see the below given screenshot.

Image 2

Yahoo’s real-time currency converter API will give you a .csv file with the currency conversion rate. Click here to see Yahoo’s Online Currency Converter or else see the below given screenshot.

Image 3

Using the Code

In this project, the main components are ASPX, CSS, jQuery and Web service. The Currency Converter solution will look like the below screen:

Image 4

HTML/ASPX

As you can see from the screenshot belo, the UI contains very few controls. Two dropdowns, one text box and one button, the result is just displayed in a table cell <td>.

Image 5

Here, Textbox is used to capture the amount which needs to be converted to the desired currency from the current currency and two dropdowns are prefilled with the Currency Code and Country Names. Once you click on the Convert button, it will call a jQuery Ajax method which calls a webmethod internally. You can get the country list and codes from the attached file.

CSS

I just created this CSS for a better look and feel to the UI.

CSS
.main
{
    font-family: tahoma;
    font-size: 12px;
    border: solid 1px #03325C;
    border-collapse: collapse;
    color: #094D23;
    width: 400px;
}
.main th
{
    border-color: #03325C #03325C #03325C #03325C;
    border-style: solid solid solid solid;
    border-width: 1px 1px 1px 1px;
    color: #EDF7FF;
    padding: 4px 5px 4px 10px;
    vertical-align: bottom;
    text-align: center;
    background-color: #0E3252;
}
.result
{
    border-color: #989898 #989898 #989898 #989898;
    border-style: solid solid solid solid;
    border-width: 1px 1px 1px 1px;
    color: #1A0229;
    padding: 4px 5px 4px 10px;
    vertical-align: bottom;
    text-align: left;
    background-color: #C7CCD1;
    font-weight:bold;
}
.center
{
    text-align: center;
}
.controls
{
    font-family: tahoma;
    font-size: 12px;
    color: #032610;
} 

jQuery

Here, I’m explaining the jQuery Ajax code that is used to call the web service which returns rate from Google’s API or Yahoo’s API.

JavaScript
$(document).ready(function () {
    $('#submit').click(function () {
        var errormsg = "";
        var amount = $('#txtAmount').val();
        var from = $('#drpFrom').val();
        var to = $('#drpTo').val();
        $.ajax({ type: "POST",
            url: "WebService.asmx/ConvertGOOG",
            data: "{amount:" + amount + ",fromCurrency:'" + 
                    from + "',toCurrency:'" + to + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $('#results').html("Converting...");
            },
            success: function (data) {
                $('#results').html(amount + ' ' + from + '=' + data.d.toFixed(2) + ' ' + to);
            },
            error: function (jqXHR, exception) {
                if (jqXHR.status === 0) {
                    errormsg = 'Not connect.\n Verify Network.'; ;
                } else if (jqXHR.status == 404) {
                    errormsg = 'Requested page not found. [404]'; ;
                } else if (jqXHR.status == 500) {
                    errormsg = 'Internal Server Error [500].'; ;
                } else if (exception === 'parsererror') {
                    errormsg = 'Requested JSON parse failed.'; ;
                } else if (exception === 'timeout') {
                    errormsg = 'Time out error.'; ;
                } else if (exception === 'abort') {
                    errormsg = 'Ajax request aborted.'; ;
                } else {
                    errormsg = 'Uncaught Error.';
                }
                $('#results').html(errormsg);
                $('<a href="#" >Click here for more details</a>').click(function () {
                    alert(jqXHR.responseText);
                }).appendTo('#results');
            }
        });
    });
}); 

In the above code, the click() event is tied to the Submit button and jQuery val() function is used to retrieve the control values and it's passed to the webservice method. By using $.ajax, we are making a jQuery Ajax call to a .NET webservice. Here, before initiating the Ajax call, I'm setting the result value as "Converting..." using the beforeSend setting of $.ajax. If the call is success, then the currency rate will display in the result cell, else the error will display.

Google

We can call the Google Web Method by setting the url setting of jQuery Ajax call as below:

JavaScript
url: "WebService.asmx/ConvertGOOG",

Yahoo

We can call the Yahoo Web Method by setting the url setting of jQuery Ajax call as below:

JavaScript
url: "WebService.asmx/ConvertYHOO", 

When the element with ID “submit” (Convert button) is clicked, then this method will get called. By using val() function of jQuery, the HTML controls values are stored to a variable and that variable is passed to the Web service method. We are calling the jQuery Ajax call by $.ajax , the web service name and method are mentioned in url setting of jQuery.ajax() function. So when we click the result, cell will display “Converting...”, if the call is a success, then the expected output will be shown in the result <td> otherwise it will display an Error Description and a hyperlink that will show the error cause in detail. I have tried to handle some of the errors in jQuery Ajax Call.

Error Setting of jQuery Ajax Call

This block is used to catch the jQuery Ajax call to the Web Method. This code will set the error description and will add a hyperlink for more error details, you can see the sample output below:

JavaScript
error: function (jqXHR, exception) {
    if (jqXHR.status === 0) {
        errormsg = 'Not connect.\n Verify Network.'; ;
    } else if (jqXHR.status == 404) {
        errormsg = 'Requested page not found. [404]'; ;
    } else if (jqXHR.status == 500) {
        errormsg = 'Internal Server Error [500].'; ;
    } else if (exception === 'parsererror') {
        errormsg = 'Requested JSON parse failed.'; ;
    } else if (exception === 'timeout') {
        errormsg = 'Time out error.'; ;
    } else if (exception === 'abort') {
        errormsg = 'Ajax request aborted.'; ;
    } else {
        errormsg = 'Uncaught Error.';
    }
    $('#results').html(errormsg);
    $('<a href="#" >Click here for more details</a>').click(function () {
        alert(jqXHR.responseText);
    }).appendTo('#results');
} 

Image 6

Webservice

Here, the convert method will accept three input parameters. The parameters are amount, fromCurrency and toCurrency.

Google

ConvertGOOG Web Method is used to handle the Google API call to return the currency rate. The received response is parsed and only the rate part is returned from this function. For your quick reference, I have given the Debugging screenshot below so that you can see the response and the url passed from this method.

Image 7

Yahoo

ConvertYHOO Web Method is used to handle the Yahoo API call to return the currency rate. The received response is parsed and only the rate part is returned from this function. For your quick reference, I have given the Debugging screenshot below so that you can see the response and the url passed from this method.

Image 8

The expected format of the rate is a proper decimal number, if any other format (e.g., 9 433.56 - space came in between number) comes, then we need to handle the same in Web Method.

Summary

I hope this article helped you to understand Real-time currency converter using APIs in ASP.NET.

Please give your valuable votes, suggestions and feedback for further improvements. Thanks for reading.

History

  • 15th July, 2012: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Technical Manager/ Software Architect | CodeProject MVP | Visual Studio Marketplace Contributor | Author | Geek | Netizen | Husband | ChessPlayer

Most of my articles are listed on top 5 of the respective 'Best articles of the month' and some of my articles are published on ASP.NET WebSite's Article of the Day section.

Check my contributions in Visual Studio Marketplace and Code Project

Technical Blog: https://shemeerns.wordpress.com/
Facebook: http://facebook.com/shemeernsblog
Twitter : http://twitter.com/shemeerns
Google+ : http://google.com/+Shemeernsblog

Comments and Discussions

 
Questionexception Pin
Member 129907511-Apr-18 8:19
Member 129907511-Apr-18 8:19 
QuestionHistorical currency value Pin
Member 109318051-Jan-15 1:47
Member 109318051-Jan-15 1:47 
GeneralMy Comment Pin
Goutham Bhamidipati28-Dec-14 20:44
Goutham Bhamidipati28-Dec-14 20:44 
QuestionError : Operation has timed out Pin
Member 1093180524-Dec-14 0:03
Member 1093180524-Dec-14 0:03 
QuestionGoogle API code not working Pin
Member 776634114-Dec-14 20:09
Member 776634114-Dec-14 20:09 
QuestionHow can i add web service refrence in my code Pin
Member 1115545515-Oct-14 5:18
Member 1115545515-Oct-14 5:18 
QuestionWeb Service - Real-time Currency Converter using API Pin
Ravi.Kumar02115-Jan-14 7:50
professionalRavi.Kumar02115-Jan-14 7:50 
QuestionIntegration Issue Pin
MikeIK10-Oct-13 2:47
MikeIK10-Oct-13 2:47 
GeneralMy vote of 5 Pin
Alen Joy18-Jun-13 19:28
Alen Joy18-Jun-13 19:28 
GeneralMy vote of 5 Pin
jay@begginer13-Mar-13 22:02
jay@begginer13-Mar-13 22:02 
GeneralMy vote of 5 Pin
ravithejag15-Jan-13 16:52
ravithejag15-Jan-13 16:52 
GeneralRe: My vote of 5 Pin
Shemeer NS20-Jan-13 19:44
professionalShemeer NS20-Jan-13 19:44 
GeneralMy vote of 5 Pin
stevepb31-Dec-12 5:54
stevepb31-Dec-12 5:54 
GeneralRe: My vote of 5 Pin
Shemeer NS2-Jan-13 18:46
professionalShemeer NS2-Jan-13 18:46 
Question500 Internal Error Pin
Member 96659677-Dec-12 7:04
Member 96659677-Dec-12 7:04 
AnswerRe: 500 Internal Error Pin
Shemeer NS7-Dec-12 21:39
professionalShemeer NS7-Dec-12 21:39 
GeneralRe: 500 Internal Error Pin
Luk Wei Heng29-Jul-13 23:46
Luk Wei Heng29-Jul-13 23:46 
GeneralMy vote of 5 Pin
Member 843555818-Oct-12 14:12
Member 843555818-Oct-12 14:12 
GeneralRe: My vote of 5 Pin
Shemeer NS5-Nov-12 9:45
professionalShemeer NS5-Nov-12 9:45 
QuestionProblem BDT Convertion Pin
csharpbd11-Aug-12 7:52
professionalcsharpbd11-Aug-12 7:52 
AnswerRe: Problem BDT Convertion Pin
Shemeer NS11-Aug-12 9:10
professionalShemeer NS11-Aug-12 9:10 
http://www.google.com/ig/calculator?hl=en&q=5BDT%3D%3FAED[^]

The response was an error Frown | :(

{lhs: "",rhs: "",error: "4",icc: false}

somehow Google API not working for BDT conversion...

but Yahoo API works perfectly...
GeneralRe: Problem BDT Convertion Pin
csharpbd11-Aug-12 12:01
professionalcsharpbd11-Aug-12 12:01 
BugWhite Space making problem , Here is the solution Pin
Darshit Pandya25-Jul-12 21:41
Darshit Pandya25-Jul-12 21:41 
GeneralRe: White Space making problem , Here is the solution Pin
Shemeer NS25-Jul-12 23:54
professionalShemeer NS25-Jul-12 23:54 
GeneralMy vote of 5 Pin
rspercy6517-Jul-12 13:39
rspercy6517-Jul-12 13:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.