What is jsonp?
JSONP is complement to JSON base data format. It allows one to access different domain which is by default prevent by web browser due to security concern under same origin policy .
Under Same origin policy, if web pages served from one domain such as (example.com) can not access another domain(such as example2.com) except under// <![CDATA[
tag inside html element. This type of pattern is called JSONP.
// ]]>
JSONP does not mean response should be in json format, it mean any javascript in response can be easily executed.
AJAX request are made through javascript(or jquery) inside the//
Given below example of jquery-ajax request:
<html>
<head>
</head
<body>
// <![CDATA[
javascript" >
// ]]>
$(document).ready(function(){
$.ajax({
url: “
http://example.server1.com?callback=?”,
type: “POST”,
data: {“email”: username},
dataType: “JSONP”,
contentType: ‘application/json’,
success: function (data){
book_details = JSON.parse(data)
},
error: function () {
$(‘#loading’).hide()
alert(‘Invalid Username/Password’)
}
});
</script>
</body>
</html>
code inside// <![CDATA[
tag just send request to another domain to retreive data from other domain.
// ]]>
As you are seeing , format of url is like that appending callback query string at end of url. It is any regular parameter but passed with url when we are making JSONP request.
Callback query parameter can be anything (you can give like “http:://example.server1.com?callback=any_name”)
Response of server returning json data will
“any_name([book:{id:1 , author: asas}])”
in success function, you still get data [book:{id:1, author: asss}].
But Server should validates its access request before accessing that url .
In Rails 3:
You have apply before filter
Consider i have books_controller , there is cross domain request for returning json data from server.
Either header not set or you not set dataType: JSONP , you will get following error
”Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.”
The first request send by ajax is OPTIONS(instead of POST, GET what is you expected).
If you does not specify server how to handle OPTIONS method, you will get error “specified routes not found”.
If you have to mention that name of methods in config/routes.rb file :
match ‘some_url’ => ‘controller#action’, :via => ["options", "get", "post"]
then options request get handled in server side.
SETTING HEADER IN RAILS 3 CONTROLLER :
class ApplicationController < ActionController::Base
before_filter: set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = ‘*’
headers['Access-Control-Request-Method'] = ‘*’
headers['Access-Control-Allow-Headers'] = ‘*’
headers['Access-Control-Allow-Credentials'] = “true”
end
end
Then you have to send response in correct format:
If you does not specify correct format, then you will get error in sucess event of ajax as ” Parsed error “.
RESPONDING TO JSONP REQUEST IN RAILS 3
@book = Book.all
books= @book.to_json
respond_to do |format|
format.json{render :json => books, :callback => params[:callback]}
end
it will construct respond in javascript as “params[:callback](books)”
If you does not understand any part of above explanation , please free mail me to “narutosanjiv@gmail.com”