Skip to Content

jQuery: write less, do more.

jQuery is an amazing framework and part of SAPUI5. I want to show you some features, which could be very useful for your SAPUI5-App. You can try out each code snippet on jsfiddle.net. The complete documentation of all jQuery-functions is available right here.

Simple cross-domain Ajax request

This code shows, how you can call a web service from a different domain, without getting security issues (same origin policy). This call will only work, if your service supports JSONP.

// service url
var url = 'http://ip.jsontest.com/?callback=processJSON';
$.ajax({
    url: url,
    jsonpCallback: 'processJSON',
    dataType: 'jsonp',
    success: function (result) {
        // process result
        $('#result').html(result.ip);
    },
    error: function (e) {
         // log error in browser
        console.log(e.message);
    }
});

If you don’t have to call a service from a different domain, you can remove the jsonpCallback property and change the dataType to json or something else (e.g. XML). You can try out this code snippet right here. Don’t forget to read the documentation of jQuery.ajax.

Iterate over a JSON structure

Sometimes it’s very important to handle a complex json response. For example, you want to show all objects of your result in a table or a row repeater. If you can’t use the built-in functions of SAPUI5 you can use this:

// Object
var person = {
    'firstName': 'John',
        'lastName': 'Smith',
        'age': 25,
        'address': {
        'streetAddress': '21 2nd Street',
            'city': 'New York',
            'state': 'NY',
            'postalCode': 10021
    },
        'phoneNumbers': [{
        'type': 'home',
            'number': '212 555-1234'
    }, {
        'type': 'fax',
            'number': '646 555-4567'
    }]
};
// Read single properties
$('#name').html(person.firstName + ' ' +person.lastName);
$('#age').html(person.age);
// Read Array of phone numbers
$.each(person.phoneNumbers, function () {
     // this represents one entry of the array
    $('#phoneNumbers').append($('<div class="number"></div>').html(this.type + ' : ' + this.number));
});

You can try out this code snippet right here. Don’t forget to read the documentation of jQuery.each.

Create a new jQuery function

If you want to enhance the functionality of jQuery, then check out the extend-function. In this way you can create a new function, which will be available over the jQuery or $ object. (By the way: ‘$’ is just a shortcut of jQuery). This is very useful, if you have to create util or helper functions.

// extend jQuery
$.extend($, {
  createText: function () {
       // create some text in container
       $('#container').append('<span>some text</span>');
  }
});
// click-handler
$('#create').click(function(){
    // call new function
    $.createText();
});

Test the complete snippet here. Documentation of jQuery.extend.

Create a new jQuery instance method

When you select a DOM-Element with jQuery, e.g. $(‘.row’), the framework will return a new jQuery object. You can access over this instance to all kinds of methods. But there is also a way to create new instance methods.

// create new instance method
$.fn.extend({
    colorize: function () {
       this.css('background-color','#f2aa00');
    }
});
// click-handler
$('button').click(function(){
    // call new instance method
    $('.target').colorize();
});

A very smart way to implement new stuff! Test the complete snippet here. Documentation of jQuery.fn.extend.

Simple data storage with jQuery

With HTML5 you can use persistent localStorage or temporarily sessionStorage API to save data in an appropriate scope. But jQuery offers an additional DOM-based method to store temporary arbitrary data.

// store data
$("body").data("data_one", 500);
$("body").data("data_two", 52);
$('button').click(function(){
    // read data
    var data_one = $("body").data("data_one");
    var data_two = $("body").data("data_two");
    // create result string
    $("div").html('Value: ' + data_one + ' and ' + data_two);
});

You can also store e.g. a serialized Javascript Object. But when you left the current site, the DOM-Element will be destroyed and your data will be lost. So it’s important to know, that you shouldn’t use this API to store session or persistent data. Code snippet is available here. Documentation of jQuery.data.

To report this post you need to login first.

4 Comments

You must be Logged on to comment or reply to a post.

  1. Madhumitha S

    Hi ,

    I appreciate the content of ur blog .Very useful.

    You have writtern about cross domain ajax request for Jquery.

    When i use eclipse plugin for Gateway ,the SAP UI 5 project code is generated by the plug -in

    How to apply the cross domain configurations  for a SAP UI 5 project ?

    How do i override the default properties and make the datatype as JSONP for a SAP UI 5 project?

    (0) 
    1. Michael Herzog Post author

      Hi Madhumitha,

      because web services of SAP Netweaver Gateway don’t support JSONP, you normally have to run app and service in the same domain. If you have problems to ensure this, you can use the URL-Rewriting/ Reverse Proxy functionality of your web server to manipulate the request of your SAPUI5 app an redirect it to a different destination (e.g. Application Server). In this way, your services run from your app point of view in the same domain. Maybe you should have a talk with your SAP or Web admins about this. Depending on your infrastructure, you have different kind of options. In my last project, I used an apache webserver as a reverse proxy (i have to say: my web-admin is godlike 🙂 ).

      Regards

      (0) 
  2. Noël Hendrikx

    Hi Michael,

    Nice blog! Does the “Simple cross-domain Ajax request” also work with different protocols / portnumbers? Or does it only solve the domain relaxing issues?

    Cheers!

    Noël

    (0) 
    1. Michael Herzog Post author

      Hi Noël,

      with JSONP, you can call a service with different protocol, domain and port number. I think it’s important to know, that a JSONP-call creates temporarily a new DOM element in your HTML. This DOM element is nothing more than a script-tag, whose src attribute contains the service url. In this way, the requested resource is downloaded just like a simple JavaScript file. Because you can load js-resources from any destination (e.g. CDN), you can call services via JSONP from similar URLs.

      Example script tag (by the way, second url parameter ‘_’ prevents caching):

      <script async src =”http://ip.jsontest.com/?callback=processJSON&_=1372200158436” /><script>

      JSONP is especially used in internet-applications. E.g: If you want to call a service from a social media API, you can often use JSONP as a pure client side solution. Sometimes however you have to authenticate e.g. with OAuth, which means, that you normally have to implement a server and client-side part (so you don’t use JSONP).

      But also in enterprise environments you can notice more and more service calls via JSONP to solve security issues (same origin policy). Sometimes it’s the easiest solution, when you can enhance your services to work with JSONP Paradigma. But for greater infrastructures with many application servers and standardized, non-JSONP services, i recommend to establish a reverse proxy to create a consistent service facade for you apps.

      Regards


      (0) 

Leave a Reply