Thursday 25 September 2014

Jquery Ajax call example

function GetXrmElement() {
function CreateDebitTransaction() {                
                var Params = {
                    Leader : “Col. Hannibal Smith”,
                    Driver: “Cor. BA Baracus”,
                    Logistics: “Sgt Pedelton”,
                    pilot: “Lef Mardoc”
                };
                $.ajax({
                    type: "GET",
                    url: // ,
                    data: JSON.stringify(Params),                
                    data: Params,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {                        
                 // success method call back
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error Occured while executing the requese.");
                        return;
                    }
                });
            }




above is an asynchronous, non cross browser supported method. synchronous calls does not support jsonp. we can use async attribute but it has some limitations.

according to JQuery API documentation,


async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

to make it look like sync call i normally put the continuation of the code in the success or error method. not the best work around but work around none the less.

for cross domain purposes some websites say using headers like below resolves the issue. although i have not tested it.

function GetXrmElement() {
headers: { 'Access-Control-Allow-Origin': '*' }
/* may work ??
beforeSend: function (request) {
       //request.setRequestHeader("Access-Control-Allow-Origin: ", "*")
},*/


No comments: