Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Thursday, 14 April 2016

AngularJS vs jQuery

1. Don't design your page, and then change it with DOMmanipulations


In jQuery, you design a page, and then you make it dynamic. This is because jQuery was designed for augmentation and has grown incredibly from that simple premise.

But in AngularJS, you must start from the ground up with your architecture in mind. Instead of starting by thinking "I have this piece of the DOM and I want to make it do X", you have to start with what you want to accomplish, then go about designing your application, and then finally go about designing your view.

2. Don't augment jQuery with AngularJS


Similarly, don't start with the idea that jQuery does X, Y, and Z, so I'll just add AngularJS on top of that for models and controllers. This is really tempting when you're just starting out, which is why I always recommend that new AngularJS developers don't use jQuery at all, at least until they get used to doing things the "Angular Way".

I've seen many developers here and on the mailing list create these elaborate solutions with jQuery plugins of 150 or 200 lines of code that they then glue into AngularJS with a collection of callbacks and$applys that are confusing and convoluted; but they eventually get it working! The problem is that inmost cases that jQuery plugin could be rewritten in AngularJS in a fraction of the code, where suddenly everything becomes comprehensible and straightforward.

The bottom line is this: when solutioning, first "think in AngularJS"; if you can't think of a solution, ask the community; if after all of that there is no easy solution, then feel free to reach for the jQuery. But don't let jQuery become a crutch or you'll never master AngularJS.

3. Always think in terms of architecture


First know that single-page applications are applications. They're not webpages. So we need to think like a server-side developer in addition to thinking like a client-side developer. We have to think about how to divide our application into individual, extensible, testable components.

So then how do you do that? How do you "think in AngularJS"? Here are some general principles, contrasted with jQuery.

The view is the "official record"


In jQuery, we programmatically change the view. We could have a dropdown menu defined as a ullike so:
<ul class="main-menu">
    <li class="active">
        <a href="#/home">Home</a>
    </li>
    <li>
        <a href="#/menu1">Menu 1</a>
        <ul>
            <li><a href="#/sm1">Submenu 1</a></li>
            <li><a href="#/sm2">Submenu 2</a></li>
            <li><a href="#/sm3">Submenu 3</a></li>
        </ul>
    </li>
    <li>
        <a href="#/home">Menu 2</a>
    </li>
</ul>

In jQuery, in our application logic, we would activate it with something like:
$('.main-menu').dropdownMenu();

When we just look at the view, it's not immediately obvious that there is any functionality here. For small applications, that's fine. But for non-trivial applications, things quickly get confusing and hard to maintain.

In AngularJS, though, the view is the official record of view-based functionality. Our ul declaration would look like this instead:
<ul class="main-menu" dropdown-menu>
    ...</ul>

These two do the same thing, but in the AngularJS version anyone looking at the template knows what's supposed to happen. Whenever a new member of the development team comes on board, she can look at this and then know that there is a directive called dropdownMenu operating on it; she doesn't need to intuit the right answer or sift through any code. The view told us what was supposed to happen. Much cleaner.

Developers new to AngularJS often ask a question like: how do I find all links of a specific kind and add a directive onto them. The developer is always flabbergasted when we reply: you don't. But the reason you don't do that is that this is like half-jQuery, half-AngularJS, and no good. The problem here is that the developer is trying to "do jQuery" in the context of AngularJS. That's never going to work well. The view is the official record. Outside of a directive (more on this below), you never, ever, neverchange the DOM. And directives are applied in the view, so intent is clear.

Remember: don't design, and then mark up. You must architect, and then design.

Data binding


This is by far one of the most awesome features of AngularJS and cuts out a lot of the need to do the kinds of DOM manipulations I mentioned in the previous section. AngularJS will automatically update your view so you don't have to! In jQuery, we respond to events and then update content. Something like:
$.ajax({
  url: '/myEndpoint.json',
  success: function ( data, status ) {
    $('ul#log').append('<li>Data Received!</li>');
  }
});

For a view that looks like this:
<ul class="messages" id="log">
</ul>

Apart from mixing concerns, we also have the same problems of signifying intent that I mentioned before. But more importantly, we had to manually reference and update a DOM node. And if we want to delete a log entry, we have to code against the DOM for that too. How do we test the logic apart from the DOM? And what if we want to change the presentation?

This a little messy and a trifle frail. But in AngularJS, we can do this:
$http( '/myEndpoint.json' ).then( function ( response ) {
    $scope.log.push( { msg: 'Data Received!' } );
});

And our view can look like this:
<ul class="messages">
    <li ng-repeat="entry in log">{{ entry.msg }}</li>
</ul>

But for that matter, our view could look like this:
class="messages">

class="alert" ng-repeat="entry in log"> {{ entry.msg }}

</div>

And now instead of using an unordered list, we're using Bootstrap alert boxes. And we never had to change the controller code! But more importantly, no matter where or how the log gets updated, the view will change too. Automatically. Neat!

Though I didn't show it here, the data binding is two-way. So those log messages could also be editable in the view just by doing this: <input ng-model="entry.msg" />. And there was much rejoicing.

Distinct model layer


In jQuery, the DOM is kind of like the model. But in AngularJS, we have a separate model layer that we can manage in any way we want, completely independently from the view. This helps for the above data binding, maintains separation of concerns, and introduces far greater testability. Other answers mentioned this point, so I'll just leave it at that.

Separation of concerns


And all of the above tie into this over-arching theme: keep your concerns separate. Your view acts as the official record of what is supposed to happen (for the most part); your model represents your data; you have a service layer to perform reusable tasks; you do DOM manipulation and augment your view with directives; and you glue it all together with controllers. This was also mentioned in other answers, and the only thing I would add pertains to testability, which I discuss in another section below.

Dependency injection


To help us out with separation of concerns is dependency injection (DI). If you come from a server-side language (from Java to PHP) you're probably familiar with this concept already, but if you're a client-side guy coming from jQuery, this concept can seem anything from silly to superfluous to hipster. But it's not. :-)

From a broad perspective, DI means that you can declare components very freely and then from any other component, just ask for an instance of it and it will be granted. You don't have to know about loading order, or file locations, or anything like that. The power may not immediately be visible, but I'll provide just one (common) example: testing.

Let's say in our application, we require a service that implements server-side storage through a RESTAPI and, depending on application state, local storage as well. When running tests on our controllers, we don't want to have to communicate with the server - we're testing the controller, after all. We can just add a mock service of the same name as our original component, and the injector will ensure that our controller gets the fake one automatically - our controller doesn't and needn't know the difference.

Speaking of testing...

4. Test-driven development - always


This is really part of section 3 on architecture, but it's so important that I'm putting it as its own top-level section.

Out of all of the many jQuery plugins you've seen, used, or written, how many of them had an accompanying test suite? Not very many because jQuery isn't very amenable to that. But AngularJS is.

In jQuery, the only way to test is often to create the component independently with a sample/demo page against which our tests can perform DOM manipulation. So then we have to develop a component separately and then integrate it into our application. How inconvenient! So much of the time, when developing with jQuery, we opt for iterative instead of test-driven development. And who could blame us?

But because we have separation of concerns, we can do test-driven development iteratively in AngularJS! For example, let's say we want a super-simple directive to indicate in our menu what our current route is. We can declare what we want in the view of our application:
<a href="/hello" when-active>Hello</a>

Okay, now we can write a test for the non-existent when-active directive:
it( 'should add "active" when the route changes', inject(function() {
    var elm = $compile( '<a href="/hello" when-active>Hello</a>' )( $scope );

    $location.path('/not-matching');
    expect( elm.hasClass('active') ).toBeFalsey();

    $location.path( '/hello' );
    expect( elm.hasClass('active') ).toBeTruthy();
}));

And when we run our test, we can confirm that it fails. Only now should we create our directive:
.directive( 'whenActive', function ( $location ) {
    return {
        scope: true,
        link: function ( scope, element, attrs ) {
            scope.$on( '$routeChangeSuccess', function () {
                if ( $location.path() == element.attr( 'href' ) ) {
                    element.addClass( 'active' );
                }
                else {
                    element.removeClass( 'active' );
                }
            });
        }
    };
});

Our test now passes and our menu performs as requested. Our development is both iterative andtest-driven. Wicked-cool.

5. Conceptually, directives are not packaged jQuery


You'll often hear "only do DOM manipulation in a directive". This is a necessity. Treat it with due deference!

But let's dive a little deeper...

Some directives just decorate what's already in the view (think ngClass) and therefore sometimes do DOM manipulation straight away and then are basically done. But if a directive is like a "widget" and has a template, it should also respect separation of concerns. That is, the template too should remain largely independent from its implementation in the link and controller functions.

AngularJS comes with an entire set of tools to make this very easy; with ngClass we can dynamically update the class; ngModel allows two-way data binding; ngShow and ngHideprogrammatically show or hide an element; and many more - including the ones we write ourselves. In other words, we can do all kinds of awesomeness without DOM manipulation. The less DOM manipulation, the easier directives are to test, the easier they are to style, the easier they are to change in the future, and the more re-usable and distributable they are.

I see lots of developers new to AngularJS using directives as the place to throw a bunch of jQuery. In other words, they think "since I can't do DOM manipulation in the controller, I'll take that code put it in a directive". While that certainly is much better, it's often still wrong.

Think of the logger we programmed in section 3. Even if we put that in a directive, we still want to do it the "Angular Way". It still doesn't take any DOM manipulation! There are lots of times when DOM manipulation is necessary, but it's a lot rarer than you think! Before doing DOM manipulationanywhere in your application, ask yourself if you really need to. There might be a better way.

Here's a quick example that shows the pattern I see most frequently. We want a toggleable button. (Note: this example is a little contrived and a skosh verbose to represent more complicated cases that are solved in exactly the same way.)
.directive( 'myDirective', function () {
    return {
        template: '<a class="btn">Toggle me!</a>',
        link: function ( scope, element, attrs ) {
            var on = false;

            $(element).click( function () {
                on = !on;
                $(element).toggleClass('active', on);
            });
        }
    };
});

There are a few things wrong with this:

  1. First, jQuery was never necessary. There's nothing we did here that needed jQuery at all!

  2. Second, even if we already have jQuery on our page, there's no reason to use it here; we can simply use angular.element and our component will still work when dropped into a project that doesn't have jQuery.

  3. Third, even assuming jQuery was required for this directive to work, jqLite (angular.element) will always use jQuery if it was loaded! So we needn't use the $ - we can just use angular.element.

  4. Fourth, closely related to the third, is that jqLite elements needn't be wrapped in $ - the elementthat is passed to the link function would already be a jQuery element!

  5. And fifth, which we've mentioned in previous sections, why are we mixing template stuff into our logic?

This directive can be rewritten (even for very complicated cases!) much more simply like so:
.directive( 'myDirective', function () {
    return {
        scope: true,
        template: '<a class="btn" ng-class="{active: on}" ng-click="toggle()">Toggle me!</a>',
        link: function ( scope, element, attrs ) {
            scope.on = false;

            scope.toggle = function () {
                scope.on = !scope.on;
            };
        }
    };
});

Again, the template stuff is in the template, so you (or your users) can easily swap it out for one that meets any style necessary, and the logic never had to be touched. Reusability - boom!

And there are still all those other benefits, like testing - it's easy! No matter what's in the template, the directive's internal API is never touched, so refactoring is easy. You can change the template as much as you want without touching the directive. And no matter what you change, your tests still pass.

w00t!

So if directives aren't just collections of jQuery-like functions, what are they? Directives are actuallyextensions of HTML. If HTML doesn't do something you need it to do, you write a directive to do it for you, and then use it just as if it was part of HTML.

Put another way, if AngularJS doesn't do something out of the box, think how the team would accomplish it to fit right in with ngClick, ngClass, et al.

Summary


Don't even use jQuery. Don't even include it. It will hold you back. And when you come to a problem that you think you know how to solve in jQuery already, before you reach for the $, try to think about how to do it within the confines the AngularJS. If you don't know, ask! 19 times out of 20, the best way to do it doesn't need jQuery and to try to solve it with jQuery results in more work for you.

Sunday, 3 April 2016

Knockout VS jQuery

Knockout.js is a javascript library that allows us to bind html elements against any data model. It provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM(UI) and any changes to the DOM are automatically reflected to the data model.

Why Knockout


consider a simple example of shopping-cart interface for an e-commerce website. When the user deletes an item from the shopping cart, you have to remove the item from the underlying data model and remove the associated html element from the shopping cart and also update the total price. If you are not using knockout for doing this you have to write event handlers and listeners for dependency tracking.

The Knockout.js provides a simple and convenient way to manage this kind of complex, data-driven interfaces. Instead of manually tracking, each element of the HTML page rely on the affected data and will automatically updated the DOM when any changes to the data model occurs.

Knockout Features




  1. Declarative Bindings


    This allows you to bind the elements of UI to the data model in a simple and convenient way. When you use JavaScript to manipulates DOM, this may cause broken code if you later change the DOM hierarchy or element IDs. But with declarative bindings even if you change the DOM then all bound elements stay connected. You can bind data to a DOM by simply including a data-bind attribute to any DOM element.


  2. Dependency Tracking


    This automatically updates the right parts of your UI whenever your data model changes. This is achieved by the two way bindings and special type of variables called observables. You don't worry about adding event handlers and listeners for dependency tracking.


  3. Templating


    This comes in handy when your application becomes more complex and you need a way to display a rich structure of view model data, thus keeping your code simple.

    Knockout can use alternative template engines for its template binding. Knockout has a native, built-in template engine which you can use right away and can be customize how the data and template are executed to determine the resulting markup.


  4. Extensible


    This implements custom behaviors as new declarative bindings for easy reuse in just a few lines of code. Knockout is also flexible to integrate with other libraries and technologies.

Knockout VS jQuery


Knockout.js is not a replacement of jQuery, Prototype, or MooTools. It doesn’t attempt to provide animation, generic event handling, or AJAX functionality (however, Knockout.js can parse the data received from an AJAX call). Knockout.js is focused only on designing scalable and data-driven UI.

Moreover Knockout.js is compatible with any other client-side and server-side technology. Knockout.js acts as a supplement to the other web technologies like jQuery, MooTools.

MVVM Design Pattern


Knockout.js uses a Model-View-ViewModel (MVVM) design pattern in which the model is your stored data, and the view is the visual representation of that data (UI) and ViewModel acts as the intermediary between the model and the view.

Actually, the ViewModel is a JavaScript representation of the model data, along with associated functions for manipulating the data. Knockout.js creates a direct connection between the ViewModel and the view, which helps to detect changes to the underlying model and automatically update the right element of the UI.
What do you think?

I hope you will enjoy the article and understand what is knockout. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

jQuery Vs AngularJS

jQuery


jQuery is a lightweight and feature-rich JavaScript Library that helps web developers by simplifying the usage of client-side scripting for web applications using JavaScript. It extensively simplifies using JavaScript on a website and it’s lightweight as well as fast.

So, using jQuery, we can:

  • easily manipulate the contents of a webpage

  • apply styles to make UI more attractive

  • easy DOM traversal

  • effects and animation

  • simple to make AJAX calls and

  • utilities and much more… etc.

As mentioned earlier, jQuery is a JavaScript library, so we can use this library in our application partially/fully to fulfill a single or many of the features it provides (as listed above). For example, we can simply use jQuery library in our application to give some effects and animations or simply making AJAX-based calls or using all of the above listed features. It’s just like a plugin.

AngularJS


AngularJS is a product by none other the Search Engine Giant Google and it’s an open source MVC-based framework (considered to be the best and only next generation framework). AngularJS is a great tool for building highly rich client-side web applications.

As being a framework, it dictates us to follow some rules and a structured approach. It’s not just a JavaScript library but a framework that is perfectly designed (framework tools are designed to work together in a truly interconnected way).

In comparison of features jQuery Vs AngularJS, AngularJS simply offers more features:

  • Two-Way data binding

  • REST friendly

  • MVC-based Pattern

  • Deep Linking

  • Template

  • Form Validation

  • Dependency Injection

  • Localization

  • Full Testing Environment

  • Server Communication

When to Use jQuery or AngularJS?


Most of the time, people fail to comprehend the real value of these technologies during application development. AngularJS is best suited for the web application development as it works on the HTML code and JSON data which helps in developing for interactive and robust applications but using the same for a simple website development results in slow loading and quite erratic websites.

While jQuery is a fast and feature-rich language which has a a commendable JavaScript library and a great tool for creating feature-rich websites. It has in-built features such as HTML document traversal, event handling, manipulation, animation and Ajax support and others which make it easier and simpler to develop hardcore websites. Therefore before utilizing any of these highly intuitive and robust languages, it is necessary to frame a sound approach dedicated either to develop an advanced web application or website development.

Don’t Use AngularJS in jQuery Fashion


jquery enjoys a huge presence of plugins which makes it easier for the developer to plug these in the websites and let it do the remaining job. On the other hand, AngularJS possesses a completely different structure which makes it harder to find any plugins or to create one which can be simply placed on the website and left for good. AngularJS has jqLite which possess the jQuery functionalities and it can be used for developing different plugins as per the need of websites but stay away for developing or patching codes of old plugins and embedding it on the website.

Saturday, 5 March 2016

jQuery Interview Questions and Answers



In this article, I have explained 100+ jQuery interview questions and answers with examples. I have tried to explain every possible jQuery interview question here that will help you to build your technical skill set and can help you in your interview.



jQuery Basic





    1. What is jQuery?

      jQuery is not a language but it is a well written code. jQuery is a set of JavaScript libraries that have been designed specifically to simplify HTML document traversing, animation, event handling, and Ajax interactions. jQuery is fast and lightweight. There are many other JavaScript code libraries such as MooTools, but jQuery has become the most popular because it is so easy to use.


    2. Why do we use jQuery?
      Or
      What are the advantages if jQuery

      We use jQuery due to following advantages:

      • It is easy to use and learn.

      • It helps to improve the performance of the application.

      • It simplifies the task of creating highly responsive web pages.

      • It helps to develop most browser compatible web page as it works across modern browsers.

      • It helps to implement UI related critical functionality without writing hundreds of lines of codes.

      • It abstracts away browser-specific features, allowing you to concentrate on design.

      • It leverages your existing knowledge of CSS

      • It performs multiple operations on a set of elements with one line of code (known as statement chaining)

      • It is extensible so you can use third-party-plug-ins to perform specialized tasks or write your own.


    3. How JavaScript and jQuery are different?

      JavaScript is a language while jQuery is a set of JavaScript libraries that have been designed specifically to simplify work like HTML document traversing, animation, event handling, and Ajax interactions.


    4. Is jQuery a replacement of JavaScript?

      No, jQuery is not a replacement of JavaScript. jQuery is a set of libraries which is written on top of JavaScript and have been designed specifically to simplify work.


    5. jQuery is a JavaScript library file or JSON library file?

      jQuery is a library of JavaScript file.


    6. jQuery library is client side or server side?

      jQuery is client side scripting.


    7. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?

      No, if things can be done easily with css and javascript then you should not prefer jQuery because jQuery has some size and there is no point of wasting bandwidth.


    8. Which operating system is more compatible with jQuery?

      Windows, Mac and Linux are more compatible with the jQuery.


    9. How can start work on jQuery?

      First we need to download jQuery. jQuery comes in two versions:

      • Development

      • Production (which is compressed and minified)

      jQuery file can be downloaded from jQuery Official website.

      Typically, we download both versions and then use each one for its intended purpose.After downloading of jquery file, to start work on jquery, you need to add reference of that file in your webpage.


    10. Whether we need to add jQuery file in both Master and Content page?

      jQuery file should be added to the Master page and can use access from the content page directly without having any reference to it.


    11. What is use of $ sign?

      The jQuery library provides the jQuery function, which allows you to select elements using selectors.
      var paragrapths = jQuery('p');

      But generally when you see jQuery code then you will see that $ sign is used mostly:
      var paragrapths = $('p');

      $ sign in the code above is just a shorter and more convenient name for the jQuery function. Actually, in the jQuery source code, you'll find this code:
      //Expose jQuery to the global object
      window.jQuery = window.$ = jQuery;

      This code allows to use $ sign in place of jQuery keyword.


    12. Can we use our own specific character in the place of $ sign in jQuery?

      Yes. We can use our own special character in place of $ sign. It is possible using jQuery.noConflict().


    13. What is jQuery.noConflict?

      As we can use other client side libraries like MooTools, Prototype with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().
      jQuery.noConflict();
      // Use jQuery via jQuery(...)
      jQuery(document).ready(function(){
         jQuery("div").hide();
      });  

      You can also use your own specific character in the place of $ sign in jQuery.
      var $j = jQuery.noConflict();
      // Use jQuery via jQuery(...)
      $j(document).ready(function(){
         $j("div").hide();
      });  


    14. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?

      Yes


    15. What is the difference between .js and .min.js?
      Or
      What is the difference between simple jquery file and minified jquery file?

      .min.js is basically the minified version of jQuery file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.


    16. What is the advantage of using minimized version of jQuery?

      Minimized version is very small (approx 50% less) in size so it loads quickly, saves bandwidth and improve performance of website.


    17. Why there are two different version of jQuery library?

      jQuery library comes in 2 different versions.

      • Development

      • Production/Deployment

      As jQuery is open source, the development version is useful at development time and if you want to change something then you can make those changes in development version.

      But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.


    18. How can we debug jQuery?

      There are 2 ways to debug jQuery:

      • Add debugger; keyword to the line where you need to start debugging and then run Visual Studio in Debug mode with F5 function key.

      • Insert a break point after attaching the process


    19. What is the use of jquery-x.x.x.-vsdoc.js file?

      .vsdoc file is used to provide intellisense support. We can even delete this file but if we will delete this file then we will loose the support of intellisense.

jQuery Load Function





    1. Which is the starting point of code execution in jQuery?

      The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.


    2. Can we have multiple document.ready() function on the same page?

      Yes, We can have any number of document.ready() function on the same page.


    3. Is there any difference between body onload() and document.ready() function?

      These are the differences between onload() and document.ready():

      • We can have as many document.ready() function in a page but we can have only single onload function in one body.

      • document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.


    4. What is the difference between window.onload event and document.ready() function?


    5. Is it possible to hold or delay document.ready execution for sometime?

      jQuery.holdReady() function allows us to hold or delay execution of document.ready function. This function was introduced with release of jQuery 1.6. You need to pass value true or false in function as parameter to specify whether you want hold or resume.
      $.holdReady(true);
      $.getScript("someplugin.js", function() {
         $.holdReady(false);
      });

CDN





    1. What is a CDN?

      CDN Stands for Content Distribution Network or also called Content Delivery Network is a group of computers placed at various points connected with network containing copies of data files to maximize bandwidth in accessing the data. In CDN, a client accesses a copy of data nearer to the client location rather than all clients accessing from the one particular server. This helps to achieve better performance of data retrieval by client.


    2. What is the advantage of using CDN?


      • It reduces the load from your server.

      • It saves bandwidth. jQuery framework will load faster from these CDN.

      • It will be cached, if the user has visited any site which is using jQuery framework from any of these CDN


    3. Which are the popular jQuery CDN?

      There are 3 popular jQuery CDNs.

      • Google

      • Microsoft

      • jQuery


    4. How to load jQuery from CDN?

      Microsoft CDN
      http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js

      Google CDN
      http://ajax.googleapis.com/ajax/libs/jquery/1.8.9/jquery.min.js

      jQuery CDN
      http://code.jquery.com/jquery-1.9.1.min.js


    5. How to load jQuery locally when CDN fails?

      It is a good approach to always use CDN but there may be a possibility (rare) that CDN is down. In that case you code will not work as jquery file will not be loaded. We can overcome this issue by following code:
      http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
      
      if (typeof jQuery == 'undefined') {
          document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
      }

      It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.


    6. Can we use protocol less URL while referencing jQuery from CDNs?

      Yes we can. See code below:
      //ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js


    7. What is the advantage of using protocol less URL while referencing jQuery from CDNs?

      Let's have an example. Your site is using HTTP protocol and you are moving from HTTP to HTTPS. Now you will have to make sure that correct protocol used for referencing jQuery library is HTTPS. "protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS.

Selector/Filters





    1. What is selector in jQuery?

      jQuery selectors retrieve content from the web page so that it can be manipulated using other functions. jQuery selectors return an array of objects that match the selection criteria.


    2. What is filter in jQuery?

      jQuery filters operate on a selector to further refine the results array that the selector returns.


    3. Can we use filters in jQuery without using of selectors?

      Yes we can use filters in jQuery without using of selectors.


    4. How many types of selectors are there?

      There are many types of selectors. Please click here to know about each selectors.


    5. How do you select element by ID selector in jQuery?

      We need to use # (hash) symbol to select element by ID selector in jQuery.
      $("#test")

      This selector selects element that has test as id attribute.


    6. How do you select element by class in jQuery?

      We need to use . (dot) symbol to select element by class name in jQuery.
      $(".test")

      This selector selects all the elements on which class test is applied.


    7. How can you select all elements in a page by jQuery?

      You can use * (asterisk symbol) to select all page elements.
      $("*").css("border","1px solid red");

      The code will select all page elements and will apply border on them.


    8. What does $("div") will select?

      This will select all the div elements on page.


    9. What does $("div.parent") will select?

      All the div element with parent class.


    10. What are the fastest selectors in jQuery?

      ID and element selectors are the fastest selectors in jQuery


    11. What are the slow selectors in jQuery?

      class selectors are the slow compare to ID and element.


    12. How jQuery selectors are executed?

      Selector execution is started from last. For Example:
      $("div#test .abc");

      jQuery will first find all the elements with class .abc and after that it will further refine selected elements by using first selector. It will reject all the other elements which are not in div#test.


    13. document.getElementByID('txtFirstName') is fast or $('#txtFirstName')?

      As jQuery is written on top of JavaScript and it internally uses JavaScript only so JavaScript is always fast. In this scenario, jQuery method $('#txtFirstName') will internally makes a call todocument.getElementByID('txtName').


    14. What is the difference between $(this) and 'this' in jQuery?

      this and $(this) both are same. When 'this' is wrapped in $() then it becomes a jQuery object and you can use the features of jQuery. The only difference is the way they are used.
      $(document).ready(function(){
          $('#divTest').click(function(){
             alert($(this).text());
          });
      });

      In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method so we have used the native JavaScript to get the text of div element.
      $(document).ready(function(){
          $('#divTest').click(function(){
             alert(this.innerText);
          });
      });


    15. How do you check if an element is empty?

      There are 2 ways to check an element if it is empty:

      Using ":empty" filter
      $(document).ready(function(){
         if ($('#div').is(':empty')){
            //div is empty
         }
      }); 

      Using "$.trim()" method
      $(document).ready(function(){
         if($.trim($('#div').html())==') {
            //div is empty
         }
      }); 


    16. What is the difference between eq() and get() methods in jQuery?

      eq() returns the element as a jQuery object that means that you can use jQuery functions on it.

      get() return a DOM element. As it is a DOM element and it is not a jQuery-wrapped object So jQuery functions can't be used.


    17. What is the difference between $('div') and $('<div/>') in jQuery?

      $('<div/>'): It creates a new div element. This is not added to DOM tree unless you don't append it to any DOM element.

      $('div'): This is a selector and selects all the div elements of page.


    18. What is the difference between parent() and parents() methods in jQuery?

      The basic difference is the parent() function travels only one level in the DOM tree, where parents()function search through the whole DOM tree.

Traversing Document Information





    1. How do you check if an element exists or not in jQuery?

      We can check existence of an element by using size() function or length property

      "length" property
      $(document).ready(function(){
         if ($('#div').length > 0){
            //div exists
         }
      });

      size() property
      $(document).ready(function(){
         if ($('#div').size()> 0){
            //div exists
         }
      });


    2. What is the difference between jquery.size() and jquery.length?

      size() method and .length property both returns number of element in the object but the .length property is preferred to use because it does not have the overhead of a function call.


    3. What is the use of $.each() function?

      The $.each() function is used to iterate over any collection, whether it is an object or an array.


    4. What is the difference between find() and children() methods?

      Both find() and children() methods are used to filter the child of the matched elements. But find()method is used to find all levels down the DOM tree but children() find single level down the DOM tree.

Animation and Effects





    1. How do you implement animation functionality?

      animate() function is used to create custom animation for many CSS properties on page element. It changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

      Only numeric values can be animated (like "margin:30px"). String values cannot be animated (like"background-color:red").
      animate(params, duration, easing, callback)


      • params: The css properties on the elements to animate

      • duration: Specifies the speed of the animation. Default value is 400 milliseconds. Possible values: milliseconds, "slow“, "fast"

      • easing: Specifies the speed of the element in different points of the animation. Default value is "swing". Possible values: "swing" - moves slower at the beginning/end, but faster in the middle "linear" - moves in a constant speed

      • callback: The function to call when the animation is complete

      Example of animation:
      $("btnClick").click(function(){
         $("#divTest").animate({height:"200px"});
      });


    2. How do you disable jQuery animation?

      "jQuery.fx.off" property is used to disable animation. If it is true then all animation methods will immediately set elements to their final state when called, rather than displaying an effect.


    3. How do you stop the currently-running animation?

      We can stop currently-running animation by using stop() method.


    4. What is finish method in jQuery?

      The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.


    5. What is the difference between calling stop(true,true) and finish method?

      The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.


    6. What are the methods used to provide effects?

      These are some methods used to provide effects:

      • show()

      • hide()

      • toggle()

      • slideDown()

      • slideUp()

      • slideToggle

      • fadeIn

      • fadeOut

      • fadeTo

Manipulating Content





    1. What is the difference between .empty(), .remove() and .detach() methods in jQuery?

      All these methods are used to remove elements from DOM. But there are some differences between them.

      .empty(): This method removes all the child elements of the matched elements.

      .remove(): This method removes the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are also removed.

      .detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.


    2. What is difference between prop and attr?

      attr() get the value of an attribute for the first matched element from the set of matched elements. prop()which was introduced in jQuery 1.6 gets the value of a property for the first matched element from the set of matched elements.

      Attributes carry additional information about an HTML element and come in name="value" pairs. Where Property is a representation of an attribute in the HTML DOM tree. Once the browser parse your HTML code, corresponding DOM node will be created which is an object thus having properties.

      attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state.


    3. What is the use jQuery.data method?

      jQuery.data() methods is used to associate the data with the DOM nodes and the objects. It store arbitrary data associated with the specified element and/or return the value that was set.
      jQuery.data( document.body, "foo", 52 );


    4. Is it possible to fetch value of multiple CSS properties in single statement?

      Yes, it is possible by .css which was provided in version 1.9:
      var testVar= $("#divTest").css([ "width", "height", "backgroundColor" ]);
      //now testVar variable will be and array like this:
      { 
         width: "100px", 
         height: "200px", 
         backgroundColor: "#FF00FF" 
      }


    5. How to check if number is numeric while using jQuery 1.7+?

      Using "isNumeric()" function which was introduced with jQuery 1.7.


    6. How to check data type of any variable in jQuery?

      We can check data type of any variable by using $.type(Object) which returns the built-in JavaScript type for the object.

Event Handling





    1. Explain .bind() vs .live() vs .delegate() vs .on()

      All these methods are used for attaching events to selectors or elements. But there are some differences between them.

      .bind(): This is the easiest and quick method to bind events. bind() method only attach events to the current elements not future element. It will not bind events to elements added dynamically. It also has performance issues when dealing with a large selection.

      .live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. But it also has performance issue on large pages. Chaining is also not properly supported using this method. Because of its poor performance, this method is deprecated as of jQuery 1.7 and you should stop using it.

      .delegate(): The .delegate() method is same as .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored. It also supports chaining.

      .on(): Since live was deprecated with 1.7, so new method was introduced named ".on()". This method has all features provided by .bind(), .live() and .delegate().


    2. How to create clone of any object using jQuery?

      We can use clone() method of jQuery to create clone of any object.
      $(document).ready(function(){
         $('#btnClone').click(function(){
            $('#ddlCountry').clone().appendTo('body');
               return false;
         });
      });


    3. Does events are also copied when you clone any element in jQuery?

      Default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
      $(document).ready(function(){
         $('#btnClone').click(function(){
            $('#ddlCountry').clone(true).appendTo('body');
            return false;
         });
      });


    4. What is event.PreventDefault() function?

      The event.preventDefault() method prevents the browser from executing the default action. For example, prevents a link from following the URL or prevents a submit button to submit the parent form.


    5. What is event.stopPropagation() function?

      The event.stopPropagation() method stops the bubbling of an event to parent elements. For example, if there is a link with a click event attached inside of a DIV or FORM that also has a click attached, it will prevent the DIV or FORM click event from firing.


    6. What is the difference between event.PreventDefault and event.stopPropagation?

      event.preventDefault(): Prevents the browser from executing the default action.

      event.stopPropagation(): Stops the bubbling of an event to parent elements


    7. What is the difference among event.PreventDefault, event.stopPropagation and "return false"?

      event.preventDefault() will prevent the default event from occurring, event.stopPropagation() will prevent the event from bubbling up and return false will do both.


    8. What is the difference between event.stopPropagation and event.stopImmediatePropagation?

      event.stopPropagation() allows other handlers on the same element to be executed, whileevent.stopImmediatePropagation() prevents every event from running.

      For example
      $("div").click(function(e){
         e.stopImmediatePropagation();
      });
      $("div").click(function(e){
         // This function won't be executed
         $(this).css("background-color", "#f00");
      });

      If event.stopPropagation was used in previous example, then the next click event on div element which changes the css will fire, but in case event.stopImmediatePropagation(), the next div click event will not fire.


    9. How do you attach a event to element which should be executed only once?

      one() method of jQuery is used to attach a event to element which should be executed only once. The handler attached by method one() executes only once.

      For Example:
      $(document).ready(function() {
         $("#btnTest").one("click", function() {
            alert("This will be displayed only once.");
         });
      });​

      In this example message will be shown only once by clicking on btnTest button

Ajax





    1. Can we use jQuery to make ajax request?

      Yes, jQuery can be used to make ajax request.


    2. What are various methods to make ajax request in jQuery?

      There are multiple ways to make ajax request in jQuery:

      • load() : Load a piece of html into a container DOM

      • $.getJSON(): Load JSON with GET method.

      • $.getScript(): Load a JavaScript file.

      • $.get(): Use to make a GET call and play extensively with the response.

      • $.post(): Use to make a POST call and don't want to load the response to some container DOM.

      • $.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.


    3. What are the four parameters used for jQuery Ajax method?

      These are the four parameters for jQuery ajax method:

      • url: Specifies Url to send request

      • type: Specifies type of request (get or post)

      • data: Specifies data to be sent to server

      • cache: Whether the browser should cache the requested page or not


    4. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?

      There is an advantage of using $ajax() for ajax call against $.get() or $.post(). $ajax() provide you more functionalities like error callback for handling error in response but $.get() and $.post() do not provide this functionality. You will have to always trust the response from server and believe that it is going to be successful all time in case of $.get() and $.post().


    5. What are deferred and promise object in jQuery?

      These objects help in handling asynchronous functions like Ajax.


    6. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?

      Yes, We can execute/run multiple ajax request simultaneously in jQuery using .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events


    7. Can you call C# code-behind method using jQuery? If yes,then how?

      Yes, We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.


    8. How to handle Ajax error globally?

      ajaxError() function is used to handle ajax error globally in jQuery.
      $( document ).ajaxError(function() {
         $( "span#log" ).text( "Triggered ajaxError handler." );
      });

      In the code above, if there will be any error in any ajax request then #log span will show error message

jQuery Versioning





    1. Can we include multiple version of jQuery?

      Yes we can include multiple versions of jQuery in same page.


    2. In what situation you would use multiple version of jQuery and how would you include them?

      There may be a situation when we have a jQuery plugin in application which is dependent on older version of jQuery but for our own jQuery code, we want to use latest version of jQuery. So due to this dependency we will have to use multiple version of jQuery.

      Here is an example to use multiple version of jQuery:
      http://js/jquery_1.9.1.min.js
       
      
         var $jq = jQuery.noConflict();
      
       
      http://js/jquery_1.7.2.min.js

      By this way, for your own jQuery code use "$jq", instead of "$" as "$jq" refers to jQuery 1.9.1, where "$"refers to 1.7.2.


    3. Which is the latest version of jQuery library?

      The latest version of jQuery library (at the time of writing this article) is 1.11.3 or 2.1.4.


    4. Does jQuery 2.0 supports IE?

      No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.


    5. What are source maps in jQuery?

      Source Map is mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9.


    6. How to use migrate jQuery plugin?

      With release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it's not easy to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

      So to use old/deprecated features, you need to provide reference of jQuery Migrate Plugin.


    7. How to write browser specific code using jQuery?

      jQuery.browser property is used to write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.


    8. How can we check jQuery UI version?

      The command $.ui.version returns jQuery UI version.

Plug-in





    1. What is jQuery plugin and what is the advantage of using plugin?

      A plug-in is piece of code written in a standard JavaScript file . These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.


    2. What is jQuery UI?

      jQuery UI provides a prebuilt set of functionality that gives your pages a polished, professional look and feel. It is an official plug-in with commonly used interface widgets, like slider controls, progress bars, accordions, etc.


    3. What is the difference between jQuery and jQuery UI?

      jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.


    4. What is jQuery Connect?

      jQuery Connect is a jquery plugin which enables us to connect a function to another function. It is like assigning a handler for another function. This situation happens when you are using any javascript plugins and you want to execute some function when ever some function is executed from the plugin. This we can solve using jquery connect function.


    5. What is the use of $.disconnect() function?

      $.disconnect() function is used to disconnect a function to another function. It is opposite of $.connect().

Others




  1. What is statement chaining in jQuery?

    Chaining is one of the most powerful feature of jQuery. Chaining provides the ability to chain multiple functions together to perform several operations in one line of code. It makes your code short and easy to manage. The chain starts from left to right. So left most will be called first and so on.

    Syntax
    $(selector).fn1().fn2().fn3();

    ​$(document).ready(function(){
       $('#divTest').addClass('test');
       $('#divTest').css('color', 'blue');
       $('#divTest').fadeIn('slow');
    });​

    Using chaining, you can write above jQuery code like this:
    ​$(document).ready(function(){
       $('#divTest').addClass('test').css('color', 'blue').fadeIn('slow');
    });​


  2. How does caching helps and how to use caching in jQuery?

    Caching helps to increase performance and it can also be used in jQuery. If you are using an element in jQuery more than one time then you should cache that element.

    For example:
    $("#divTest").css("color", "red");
    $("#divTest").html("Some Text Here!");
    //Some more code for #divTest

    ​In jQuery code given above, we are using #divTest multiple time. Whenever it will be used like this, jQuery will have to traverse through DOM to get that element. We can avoid this extra traversing by saving this div in a variable:
    var $divTest = $("#divTest");
    $divTest.css("color", "red");
    $divTest.html("Some Text Here!");
    //Some more code for #divTest

    Now jQuery will not traverse again to find #divTest. We can user variable #divTest. In jQuery caching means saving jQuery selector in a variable and use that variable reference whenever required.


  3. You get "jquery is not defined" or "$ is not defined" error. What could be the reason?

    There may be many reasons for this:

    • You have forgot to include the reference of jQuery library and trying to access jQuery.

    • You have include the reference of the jQuery file, but name or path of referenced jQuery file is not correct.

    • You have include the reference of the jQuery file, but it is after your jQuery code.

    • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.


  4. How can we encode or decode url in jQuery?

    You need to use follwing methods for encoding and decoding of url in jQuery:

    Encode: encodeURIComponent(url)
    Decode: decodeURIComponent(url)
    You need to pass the complete url with parameterized value in the function. These functions will return you encoded/decoded url as a result.


  5. How to disable browser back button through jQuery?

    You can use following code to disable browser back button:
    window.history.forword(1);
       //or
    window.history.forword(-1);


  6. How to disable mouse right click using jQuery?

    $(document).ready(function()
    {
       $(this).bind("contextmenu"),function(e)
       {
          e.preventDefault();
       });
    });


  7. How to disable cut, copy paste in jQuery?

    $(document).ready(function()
    {
       $("#txtTest").bind("copy paste cut"),function(e)
       {
          e.preventDefault();
       });
    });

    By using code given above cut, copy and paste will be disabled on #txtTest textbox.

Saturday, 16 January 2016

Calling Cross Domain WCF Service using Jquery

From last couple of days, I was trying to call a wcf service using jquery that is hosted in different domain. But every time I was failed to call wcf service from different domain. After spending much time on R&D, I found the solution and the reason why I was unable to call cross domain wcf service.

Whenever you try to call a cross domain WCF Service by javascript or jquery, it behaves differently with different browsers. When you want to perform "POST" or "GET" request on cross domain wcf service or normal service using jquery/javascript or ajax, the browser actually sends an "OPTIONS" verb call to your wcf service that is not mention in your wcf method attribute. We mention there "POST" or "GET" to call a wcf service method. Hence we get error to call cross domain wcf service. We find the following request and response headers in firefox when we try to call wcf service.

Request Headers



  1. OPTIONS http://myserver/MyService.svc/GetStates HTTP/1.1

  2. Host: 192.168.4.156 User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0

  3. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

  4. Accept-Language: en-us,en;q=0.5

  5. Accept-Encoding: gzip, deflate

  6. Proxy-Connection: keep-alive

  7. Origin: http://192.168.4.156:90

  8. Access-Control-Request-Method: OPTION

  9. Access-Control-Request-Headers: content-type

  10. Pragma: no-cache

  11. Cache-Control: no-cache

Response Headers



  1. HTTP/1.0 405 Method Not Allowed

  2. Cache-Control: private

  3. Allow: POST

  4. Content-Length: 1565

  5. Content-Type: text/html; charset=UTF-8

  6. Server: Microsoft-IIS/7.0

  7. X-AspNet-Version: 4.0.30319

  8. X-Powered-By: ASP.NET

  9. Access-Control-Allow-Origin: *

  10. Access-Control-Allow-Headers: Content-Type

  11. Date: Fri, 04 May 2012 12:05:17 GMT

  12. X-Cache: MISS from c1india.noida.in

  13. X-Cache-Lookup: MISS from c1india.noida.in:3128

  14. Via: 1.0 c1india.noida.in:3128 (squid/2.6.STABLE21)

  15. Proxy-Connection: close

In above request headers the method is "OPTION" not "POST" and the response headers has content-type "text/html; charset=UTF-8" instead of "json;charset=UTF-8". To change these options we need to do some changes in web.config of hosted wcf service.

Configure WCF Cross Domain service



  1. namespace CrossDomainWcfService

  2. {

  3. [DataContract]

  4. public class Supplier

  5. {

  6. [DataMember] public string Name;

  7. [DataMember] public string Email;

  8. }

  9. [ServiceContract(Namespace = "")]

  10. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

  11. public class MyService

  12. {

  13. [OperationContract]

  14. [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

  15. List GetSuppliers (int OrgID)

  16. {

  17. // Fetch data from database var q= (from tbl in mobjentity.Customer

  18. where tbl.OrgID=OrgID).ToList();

  19. Listlst= new List();

  20. foreach(var supp in q)

  21. {

  22. Supplier msupp=new Supplier();

  23. msupp.Name=supp.Name;

  24. msupp.Email=supp.Email

  25. //Make Supplier List to retun

  26. lst.Add(msupp);

  27. }

  28. return lst;

  29. }

  30. }

  31. }

WCF Service Web.config



  1. <system.webServer>

  2. <modules runAllManagedModulesForAllRequests="true" />

  3. <httpProtocol>

  4. <customHeaders>

  5. <add name="Access-Control-Allow-Origin" value="*" />

  6. <add name="Access-Control-Allow-Headers" value="Content-Type" />

  7. </customHeaders>

  8. </httpProtocol>

  9. </system.webServer>

  10. <system.serviceModel>

  11. <behaviors>

  12. .

  13. .

  14. .

  15. </behaviors>

  16. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

  17. <standardEndpoints>

  18. <webScriptEndpoint>

  19. <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />

  20. </webScriptEndpoint>

  21. </standardEndpoints>

  22. <services>

  23. .

  24. .

  25. </service>

  26. </services>

  27. <bindings>

  28. .

  29. .

  30. </bindings>

  31. <client>

  32. .

  33. .

  34. </client>

  35. </system.serviceModel>

Global.asax Code


You can also define your hosted service web.config setting in Global.asax file. If you have defined setting in web.config then there is no need to do here.

  1. protected void Application_BeginRequest(object sender, EventArgs e)

  2. {

  3. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , ”*”);

  4. if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )

  5. {

  6. //These headers are handling the "pre-flight" OPTIONS call sent by the browser

  7. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );

  8. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );

  9. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" );

  10. HttpContext.Current.Response.End();

  11. }

  12. }

Wcf calling using Jquery



  1. $.ajax({

  2. type: "Post"

  3. url: "http://www.yourdomain.com/MyService.svc/GetSuppliers", // Location of the service

  4. data: '{"OrgID"="1"}', //Data sent to server

  5. contentType: "application/json;charset-uf8", // content type sent to server

  6. dataType: "json", //Expected data format from server

  7. success: function (msg) {

  8. //Implement get data from service as you wish

  9. },

  10. error: function (err) {

  11. // When Service call fails

  12. }

  13. });

Note



  1. You can define cross domain setting either in web.config or in global.asax file of your wcf service.

  2. For running the code, make a virtual directory/web application on IIS and map the code folder to it.

Summary

In this article I try to explain cross domain wcf service calling with example. I hope after reading this article you will be able to call cross domain wcf service. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article. You can download demo project from below link.