Category Archives: Http services

Jquery – Cross domain script call – No transport error

I have spent few hours figuring out that why my below code is not working. This piece of code is beeing called from a asp.net website. It is calling a WebApi http service using jquery ajax api.

$(document).ready(function () {
$.ajax({
    url: "http://localhost:65209/api/values/SayHello",
    type: "GET",
    success: function (result) { alert(result);  },
    error:   function () { alert('error'); }
});

The reason was that using ajax I was trying to make a cross domain script call whiich by default will throw an error saying “No Transport”.
the solution is to introduce one line which was introduced after jquery 1.4.1 version onwards. Just add this line after $(document).ready() itself.

jQuery.support.cors = true;

That’s it! the same code works fine for me.

Note: Even though it works fine for you if you create your own service layer and website is trying to consume it. But there are few public websites  like netflix which does not allow cross domain scripting.

I hope it helps!

Json data – Thinner and familiar data format

I have written a little about json in bits and pieces in my erlier posts but moving further i felt a strong urge to put it altogether about Json. Mainly from development perspective which should cover from basic syntax to serialization and desrialization of json data. It also consists of links to good articels wherever needed.

Json (Javascript object notation) is a data format which is a thinner and cleaner than xml/soap formats. I am putting main points here that can get you started right away. Please refer to W3Schools on Json for the detailed syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Json values can be integer,floating point,string(in double quotes),boolean (true/false),Array (square brackets), object(curly brackets) or NULL

Mostly we deal with object oriented way of representation so let me take an example.

Employee.cs it is a c# class.


public class Employee{

public string Name {get;set;}

public int      Age    {get;set;}

public bool   IsPermanent {get; set;}

Json representation of an Employee object:


// single object of an employee

{"Name" : "praveen" , "Age" : 30, "IsPermanent" : true }

// list or array of employees. please note the square brackets.

var employeesArray = [

{ "Name" : "praveen"   , "Age" : 30 ,"IsPermanent" : true} ,

{ "Name" : "amit"      , "Age" : 27 ,"IsPermanent" : false} ,

{ "Name" : "sudhakar"  , "Age" : 27 ,"IsPermanent" : true}

]

Now that you must be comfortable with the syntax of Json data. next step is to understand how to handle Json data effectively.In this post i will discuss how to consume a webapi http service which returns an object in Json data format.

Note: To create WebApi service please refer to My Post on How to create a WebApi

Let us see few jquery methods we can use to fetch Json data.

Using $.ajax(type,uri,onSuccessMethod,onErrorMethod): .ajax() is much familiar method as it is more generic in nature and can call “Get”, “Post” etc. type of requests. you can also specify content type (default is xml).


function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.ajax (
type   :  "GET",
url     :   httpApiUri ,
contentType : "json",

success  : function(data){
              $.each(data, function (index,item){
               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
              });
           },
error   :  function (jqXHR, textStatus, err) {
             alert('Error: ' + err);
           });
);
}

Using $.getJSON(uri,successmethod): Unlike $.ajax() method this one is specific to “Get” type of requests and fetch the data in Json format by default which is great if you are sure of your data format beforehand.

function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.getJSON ( httpApiUri , function(data){
                         $.each(data, function (index,item){
                               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
                               });
                         }
          )
          .fail( function (jqXHR, textStatus, err) {
              alert('Error: ' + err);
           });
}

How to send the json data as a parameter?
Now that you know how to represent Json data using javascript notation and jquery syntax.Next step is to serialize your normal data say a javascript variable and send it as a parameter to a webapi service for instance. I am considering Jquery as an example here as it is the most widely acceptable cross browser javascript library. There are various jquery apis available to achieve this.

Using JSON.stringify( jsonData ):  Let’s say i want to make a “post” request to add an employee using an http service. you can use JSON.stringify() method which is available on Json2.js on GitHub.You need to include this js file in your code. This method will serialize your javascript variable into json format and send it over the wire.

Note: One important thing about $.ajax() method is that the parameters contentType  is a format which is returned on success of the call. data  is the parameter which defines datatype of the parameter you are sending to the service. both in this example are json.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>JSON.stringify(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>


Using jQuery.ParseJSON(jsonData):
This method is added in jquery version -1.4.1 onwards so you dont need to include any other js file. It performs the similar operation.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>jQuery.parseJSON(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>

Deserializing JSON data: Now that you know 1) Json syntax 2) jquery apis to send json data as parameter, we need to know how to deserialize the json data at code side. We have several ways to do it.
I found Json.net library very easy to use and i have a detailed post dedicated to JSON.Net. Please refer to  My Post on Json.Net to serialize an deserialize Json data

Now if you are given your next task on jquery with services dealing with json data, i guess you are good to go 🙂 (or at least googled code will start making sense if you are not fully prepared)

Hope it helps!

Praveen