How to Bypass Cross Orginin (CORS) by JSONP [duplicate] - javascript

Please could someone help me work out how to get started with JSONP?
Code:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
var photos = function (data) {
alert(data);
};
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: false,
});
});
Fiddle: http://jsfiddle.net/R7EPt/6/
Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).
thanks.

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?
Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";
You will end up with a script segment that looks like this after it loads the data:
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";
Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});
See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.
NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.
RAW JavaScript demonstration (simple Twitter feed using JSONP):
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
</body>
</html>
Basic jQuery example (simple Twitter feed using JSONP):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

There is even easier way how to work with JSONP using jQuery
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.
For more detail refer to the jQuery.getJSON documentation.

In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Related

Trying to get csv data to javascript array and getting 404 error

I have a validation in my site that uses a large table (in csv format).
I've tried the following code:
let styleurl = document.getElementById("isthisthestore");
styleurl = styleurl.getAttribute("data-stylesheeturl")
console.log(styleurl);
let data;
$.ajax({
type: "GET",
url: styleurl + "/tambour.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
console.log(data);
}
});
I'm getting the url from an element i have on the page (I'm sure therre is a better way but that's not the problem...)
I'm getting an error that says:"GET https://correct-file-url/tambour.csv 404"
Any idea why that is?
I have created a file for you see an easy code that work, but an observation is to check the complete "url", for example, when the var will printed on console, copy this url and check it, very important are that dont have any spaces white, or doubles slashs (//), see the example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>An Example for correct csv.toArrays</title>
</head>
<body>
<div id="isthisthestore" style="display: none;" data-id="https://yousiteweb.test/"> </div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.11/jquery.csv.min.js" integrity="sha512-Y8iWYJDo6HiTo5xtml1g4QqHtl/PO1w+dmUpQfQSOTqKNsMhExfyPN2ncNAe9JuJUSKzwK/b6oaNPop4MXzkwg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
var styleurl = $('#isthisthestore').attr('data-id'); //use jquery to get an url
var styleurl = styleurl+"tambour.csv"; //dont put slashes in the file name if your var url have a slash in the end of string, like data-id="https://yoursiteweb.test/"
console.log('the complete url is: '+styleurl); // check if your url+file is available
let data;
$.ajax({
type: "GET",
url: styleurl, //the var with the csv file
dataType: "html", //type html for use jquery.csv
success: function(response)
{
data = $.csv.toArrays(response);
console.log(data);
}
});</script>
</body>
</html>
King Regards

Using javascript to access Google's URL shortener APIs in a Google Chrome extension

I am writing my first google chrome extension which will use Google's URL shortener api to shorten the URL of the currently active tab in Chrome.
I am a longtime sw developer (asm/C++) but totally new to this "webby" stuff. :)
I can't seem to figure out how to make (and then process) the http POST request using js or jquery. I think I just don't understand the POST mechanism outside of the curl example.
My javascript file currently looks like this:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
});
The easiest solution would be to use jquery's $.ajax function. This will allow you to asynchronously send the content to google. When the data comes back you can then continue to process the response.
The code will look something like this question
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response); // Evaluate the J-Son response object.
}
});
Here is the jquery ajax api
Update in Jan, 2016: This no longer works, as the link shortening API requires authentication now.
I wrote a blog post with a simple solution:
http://uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html
It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you'd be able to call this service again. For simplicity, I've only shortened one URL for the demo. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.
var shortenUrl = function() {
var request = gapi.client.urlshortener.url.insert({
resource: {
longUrl: 'http://your-long-url.com'
}
});
request.execute(function(response) {
var shortUrl = response.id;
console.log('short url:', shortUrl);
});
};
var googleApiLoaded = function() {
gapi.client.load("urlshortener", "v1", shortenUrl);
};
window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');
Here I will explain how to create a google url shortener automatically on every web page using javascript and html
Phase-stages are
1) Make sure you have a jquery script code, if there is already advanced to phase two.
2) Add the following script code, after or below the jquery script code:
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
3) How to use it:
If you want to use html tags hyperlink
<a id="apireadHref" href="blank">blank</a>
If you want to use html tag input
<input id="apireadValue" value="blank"/>
The end result
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
HTML
<a id="apireadHref" href="blank">blank</a>
or
<input id="apireadValue" value="blank"/>
DEMO
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHf3wIv4T',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "longUrl": "' + longURL +'"}',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
Worked out a quick and simple solution on this issue. Hope it will solve the problem.
<html>
<head>
<title>URL Shortener using Google API. http://goo.gl </title>
<script src="https://apis.google.com/js/client.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
function load() {
gapi.client.setApiKey('[GOOGLE API KEY]');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("result").innerHTML = "";
var Url = "http://onlineinvite.in";
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': Url
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + Url + "<br>";
str += "<b>Test Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("result").innerHTML = str;
}
else {
alert("Error: creating short url \n" + response.error);
}
});
});
}
window.onload = load;
</script>
<body>
<div id="result"></div>
</body>
</html>
Need to replace [GOOGLE API KEY] with the correct Key
Your LongUrl should replace Url value i.e. http://example.com

insert XML into DOM leads to not working class/id selectors

I'm trying to load an XML file with ajax and insert parts of this XML DOM document into the browsers HTML DOM.
This works so far, but when I try to get an inserted element with a class or id selector with jquery it returns the empty list.
I tried it only in firefox 10 so far. does anyone have a clue why this might be? is it just not safe to do so?
test.html:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>dom test</title>
<script type="text/javascript">
$(function() {
var xml = null;
$.ajax({
type : "GET",
async : false,
url : 'test.xml',
dataType : "xml",
success : function(data) {
xml = data;
}
});
$('body').html($(xml).children().clone());
console.log($('h1')); // prints the h1 element
console.log($('.title')); // prints empty list
console.log($('p')); // prints the p element
console.log($('#content')); // prints empty list
});
</script>
</head><body></body></html>
test.xml:
<div id="root">
<h1 class="title">Blabla</h1>
<p id="content">
Lorem ipsum
</p>
</div>
It seems like you are just trying to grab HTML via AJAX and then insert it into your page. To do that you should be using dataType: "html" in your ajax request.
$(function() {
var html = null;
$.ajax({
type : "GET",
async : false,
url : 'test.xml',
dataType : "html",
success : function(data) {
html = data;
}
});
$('body').html(html);
});
It is doing as expected. Can verify by alerting the $(xnl).find("h1").text(). however can you please try with changing double quotes to single quotes in your xml. and disabling HTML5 support in your ff (that might be the issue too)?

jQuery('#divElement').html(str) does not work inside onsuccess - $.ajax({ type: "POST",....,onsuccess , )

I'm dealing with an issue that make me crazy. I want to build the pages dynamically, but when the POST success (return from my web service, using $.ajax({ type: "POST",....,onsuccess , ) the onsuccess function called which should build a page.
If I call the onsuccess from the onready directly, it works fine the page appear. but when the onsuccess function called due to return from the web service I can't see the page (The onsuccess func called for sure, I also see that the page element their - using Chrome "Inspect element" ), any one can explain me Why I can't see the page!!!!?!
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>
</head>
<body>
<script type="text/javascript">
function DebugClient(data, fnSuccess, fnError) {
$.ajax({
type: "POST",
url: "Service/WcaService.asmx/Client_GetInfo",
data: '{"id": ' + data + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnSuccess,
error: fnError,
dataFilter: function (data) {
//remove the ‘d’ property inserted by all WCF services (if it exists)
return data.replace(/^\{"d":(.*)\}$/, "$1");
}
});
}
$(document).ready(function () {
//If I call the onSuccess directly from here it works.
DebugClient(currentID, onSuccess, DefaultErrorHandler);
return false;
}
function onSuccess(res) {
var html = '';
html += '<div data-role="page">';
html += '<div data-role="header">';
html += '<h1>My Title</h1>';
html += '</div>';
html += '<div data-role="content">';
html += '<p>Hello world</p> ';
html += '</div>';
html += '</div>';
jQuery('#divData').html(html);
return false;
});
</script>
<div id="divData">
</div>
</body>
</html>
Your ajax call specifies fnSuccess. Your function is onSuccess.
Further, it looks like the ajax call might be in the global scope, but the onSuccess() function is inside a $(document).ready() callback which means it isn't available in the global scope.
I solved the problem, it is simply using the $(page).appendTo($.mobile.pageContainer) instead of JQuery(XXX).html, I remark the changes in Red for simplicity and few comments in Green , hope this will be useful and helpful, I can't find complete solution for this scenario, so I add it for any one need it.
Thanks guys.
TAG: how to create page in run time according to return value from WEB Service / WCF
Here the complete solution:
http://bit.ly/vjuPSw

Parse complete html page with jquery

I load a html with ajax. I want to load the result in a jquery object. I tried that but it returns null. How can I do this? I got a complete page including doctype, head elements and body elements.
var test = $(result); //result contains html code
alert(test.html()); //returns null
I load the data with this function.
function ajaxLoadContent(element) {
$.ajax({
url: "url to the page",
type: "GET",
timeout: 5000,
datattype: "html",
success: function(result) {
//handler
},
});
return false;
It's a while ago, but maybe you're still interested in it..
The intern implementation of $(String) is not able to build an jQuery object that contains head or body tags. It will simply ignore them and move all elements inside on level up.
So if your string is for example
<html>
<head>
<meta ...>
</head>
<body>
<div id="a"/>
</body>
</html>
the resulting jQuery object will be an array of two elements
[<meta ...>, <div id="a" />]
to get a body-like jQuery object cut everything but the body content before passing it to jQuery:
body = '<div id="body-mock">' + html.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>';
var $body = $(body);
now things work as expected.. for example
$body.find('#a')
Hope that helps..
test is just an html string, so you could simply do this to show the contents
alert(result);
and if you want to bind that to an element
$("#myDiv").html(result);
function ajaxLoadContent(element) {
$.ajax({
url: "url to the page",
type: "GET",
timeout: 5000,
datattype: "html",
success: function(data) {
var result = $(data);
},
});
return false;
You should now be able to call the result like this (remember it's not added to the DOM yet):
alert(result.html());
Add to the DOM
result.appendTo("body");
Let me know if this works for you.
Try the load method of jQuery object: http://api.jquery.com/load/
Load data from the server and place
the returned HTML into the matched
element.

Categories

Resources