Skip to content

Instantly share code, notes, and snippets.

@ryankirkman
Created May 30, 2012 10:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryankirkman/2835327 to your computer and use it in GitHub Desktop.
Save ryankirkman/2835327 to your computer and use it in GitHub Desktop.
Call an external JSON API via a local cross domain proxy
// See: http://api.jquery.com/jQuery.ajaxPrefilter/
$.ajaxPrefilter( function( options ) {
if ( options.crossDomain ) {
var newData = {};
// Copy the options.data object to the newData.data property.
// We need to do this because javascript doesn't deep-copy variables by default.
newData.data = $.extend({}, options.data);
newData.url = options.url;
// Reset the options object - we'll re-populate in the following lines.
options = {};
// Set the proxy URL
options.url = "http://mydomain.com/proxy";
options.data = $.param(newData);
options.crossDomain = false;
}
});
// How to use the cross domain proxy
$.ajax({
url: 'http://the-real-api-url.com/getdata',
data: {
username: 'myUsername',
password: 'myPassword'
},
crossDomain: true, // set this to ensure our $.ajaxPrefilter hook fires
processData: false // We want this to remain an object for $.ajaxPrefilter, and for performance reasons
}).success(function(data) { // Use the new jQuery promises interface and assume our API call returns a JSON object
var jsonData = JSON.parse(data); // Assume it return a JSON string
console.log(jsonData); // Do whatever you want with the data
});
@ynevet
Copy link

ynevet commented Jul 11, 2012

Syntax error at 28 line: open curly brace instead of close.
Should change it to: }).success(function(data) {

@ryankirkman
Copy link
Author

@ynevet Thanks mate

@ynevet
Copy link

ynevet commented Jul 12, 2012

Hi, you welcome.

Look, I need to post data to another domain and i'm using your code, but the ajax call does't reaching to my proxy action at the server and the browser alerts:
"XMLHttpRequest cannot load http://www.anotherdomain.com/. Origin http://localhost:5432 is not allowed by Access-Control-Allow-Origin."

Any Idea?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment