SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Wednesday, October 23, 2013

How to enable JSONP support in a Rails app

I have known about JSONP format's and the ways to display the data's via jQuery or Angularjs.
I was working on my real-time project tweeplus  with rails as Backend and Angularjs as MVC client framework.

When i tried to fetch the json api and render it on my views, i was unable to render it. Rather the json file gets loaded on the page and on chrome console it was showing the Content-Type as application/json .

Later on, i realized as per the jsonp angular docs, we must append JSON_CALLBACK to the URL.

So, How to enable JSONP support in a Rails app?

In a Rails controller where you want to return JSON to a callback function specified in an AJAX request or Angularjs js, simple add a callback key and value (via param[:callback]) to the call to render json:

render :json => your_data_hash, :callback => params[:callback]

When the JSONP AJAX request or Angularjs $http.jsonp request is made and a callback is specified (via  the ?callback= param OR the jsonpCallback option in jQuery’s $.ajax() function), Rails will now send back that JSON to the specified callback function in the DOM.


Good learn from my real-time project