Click here to Skip to main content
15,886,806 members
Articles / Programming Languages / Javascript
Tip/Trick

JSONP a way to AJAX request across domains

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Aug 2014CPOL2 min read 8.7K   1  
example to request a JSON data

Introduction

If you try to request to other domain different from that comes the request, exist a Policy for browsers that not allow you to do this. There are two main techniques to do this: JSONP or CORS. This example that I want to share is about how to use JSONP AJAX request.

Background

We were trying to integrate with a service provider (SP) that perfectly complements ours to show it to our customers as an extra and to obtain an extra benefit, extending the final package. These SPs have their own public webservice to make the requests and get the necessary information, GREAT!!, half work done :).

Let's do AJAX asynchronous requests and so we do not overload the page that allready takes enough. And so it began headache :(. Buildin the JSON for the request, done! Do AJAX request with JQuery, done! There is no JSON in return, but open the Fiddler and surprise exist response!!, If I can see the response, why is not in my succes function?

I learn about Same-origin policy.

Google this, google that and finally build my JS to finish my task, and now I share a simple example.

Using the code

With the following code you will be able to obtain a JSON response from other domain that allow callback parameter.

If you need to request with another JSON just add to the data parameter as I show commented in the sample file.

jQuery.ajax({
        url: URL,
        type: "GET",
        jsonpCallback: "callback",
        contentType: "application/javascript",
        dataType: "JSONP",
        beforeSend: function () {
            //Do your stuff before send, ussually a loading image.
        },
        error: function () {
            //Control the error.
        },
        success: function (data) {
            //Parse the data or do whatever you need.
                }
            }
        }

Callbacks

For JSONP applications to work, they need to be able to specify a callback parameter. You can specify a callback parameter by appending ?callback=[function_name], where [function_name] represents the Javascript function name to send the JSON object to. In AJAX request you must set it in JsonCallback.

Example calling:

http://echo.jsontest.com/Habana/Gropius?callback=callback

The response:

callback({"Habana": "Gropius"});

Thanks

http://json-p.org/

http://www.jsontest.com/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Spain Spain
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
-- There are no messages in this forum --