How do I use the Deezer Api? - javascript

I'm trying to use the deezer api to look up artists and display their name and image using Jquery. Here's my code:
$.getJSON('http://api.deezer.com/search/artists?q='+q+'',
function(data) {
$("#artists").empty();
$.each(data, function(i,item){
var y=item.picture;
var z=x+y;
$("#artists").append("<div id='card_artist'><div id='cardimg' style='background-image: url("+ z +");'></div><div id='artistname' class='jtextfill'><span>" + item.name + "<span></div></div>");
});
});
but it just won't work. The code seems fine, but it keeps throwing up this error message, which I haven't a clue about or how to fix:
XMLHttpRequest cannot load http://api.deezer.com/search/artists?q=whatever. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
How do I get it to work?

The error is thrown because your browser is blocking the request. Because you execute this from javascript from your own site or maybe localhost, you do a cross-site request by calling a different url (the Deezer url). There are multiple ways to solve this problem.
Try the following 'hack' with jsonp:
// Using YQL and JSONP
$.ajax({
url: "http://api.deezer.com/search/artists?q="+q,
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
format: "json"
},
// work with the response
success: function( response ) {
$("#artists").empty();
$.each(data, function(i,item){
var y=item.picture;
var z=x+y;
$("#artists").append("<div id='card_artist'><div id='cardimg' style='background-image: url("+ z +");'></div><div id='artistname' class='jtextfill'><span>" + item.name + "<span></div></div>");
}
});
Source: https://learn.jquery.com/ajax/working-with-jsonp/
Or 2. You route the request through your own server.
With a server side language like php you do the request to the Deezer Api, and with jQuery you call that php page.

Related

Get cross domain data using ajax

I am using ajax to get cross domain data.
Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol (Details) .
So i am using YQL https://code.tutsplus.com/tutorials/quick-tip-cross-domain-ajax-request-with-yql-and-jquery--net-10225 to get html data.
My question is how to make call using external proxy server. For example https://www.pinterest.com/ , so i am using external proxy server with direct url access like https://www.filterbypass.me/s.php?k=https://www.pinterest.com/ .
But the problem is yql query return to null, no response data.
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="https://www.filterbypass.me/s.php?k=https://www.pinterest.com/"') + '&format=json&diagnostics=true&callback=',
dataType: 'json' ,
success: function(data) {
console.log(data);
}
});
If you are planning to use JSONP you can use getJSON which made for that. jQuery has helper methods for JSONP
$.getJSON( 'http://someotherdomain.com/service.php', function( result ) {
console.log(result);
});
Read the below links
http://api.jquery.com/jQuery.getJSON/
Basic example of using .ajax() with JSONP?

Ajax response with JSONP, can see result cannot use it

I have the following javascript:
jQuery(document).ready( function($) {
var id = "123";
var api = "example.com:8999/".concat(id)
$.ajax({
url : api,
type: 'GET',
dataType: 'jsonp',
// jsonpCallback: "localcallback",
success: function (data) { alert('success'); }
})
});
I can see the response in chrome dev tools, but the alert isn't getting called. Ultimately I need to work with this response to set the value of a div.
Image of chrome tools:
Thanks
EDIT: Put 'POST', was using 'GET', still not working. Also, I think I'd prefer "mom and pop" json, but due to CORS and the fact I'm not good with the web and am just trying to hack this together.
Your server is not returning JSONP. It's returning plain JSON. If you specify JSONP, then the server must explicitly create a JSONP formatted response or the ajax response will not be received and processed properly.
FYI, a JSONP request is sent via a script tag (that's how it gets around the same-origin limitation for cross domain requests) and the response has to be formatted as a script that calls a function and passed the requested data to that function. You can read about how JSONP works here.
Just make your ajax call without specifying the 'dataType' attribute, then control should come back to your success callback if your ajax call completes successfully.
FYI: jQuery will try to find the response data type based on the MIME type of that response.
Example:
$( function() {
$.ajax({
url :"http://example.com:8999/123",
type: 'GET',
success: function (data) {
console.log(data); // Prints the response on console
alert('success');
}
})
});
If you want to make this call only with JSONP then it would be better to share the reason with us, so that we can suggest a better solution if possible.

Strange $.post() AJAX error when parsing JSON

I am facing this strange error in using $.post.
works
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data);
$('#loader').hide();
});
});
The above piece of code, shows me the json array I am receiving using a php file, and also shows the title field here, and hides the loader image.
But when I alert(data.title), it shows me undefined. More over, when I add datatype 'json' to $.post,
doesn't work
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data);
$('#loader').hide();
}, "json"); //Added datatype here.
});
This neither alerts anything nor does it hide the loader image. I also tried,
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
jQuery.parseJSON(data);
alert(data.title);
$('#loader').hide();
});
});
The above one too neither alerts anything nor does it hide the loader. And then I tried this one too that did nothing.
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
jQuery.parseJSON(data); //tried without this too.
alert(data['title']);
$('#loader').hide();
});
});
The strangest thing is that I have previously used json as I have shown in the 2nd script(out of 4), and that works normally. My JS console too doesn't show any errors or warning. What am I doing wrong here? How do I access the title field of data?
If this helps, here is how I send the json array,
$json = array("title" => $title, "embed" => $embed, "desc" => $desc, "duration" => $duration, "date" => $date);
print_r(json_encode($json));
I would really appreciate if someone can point out the error and tell me why my scripts are failing, similar functions worked in other js file.
here is my data, that is returned by server,
{"title":"Sunn Raha Hai Na Tu Aashiqui 2 Full Song With Lyrics |
Aditya Roy Kapur, Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"Presenting
full song \"Sun Raha Hai Na Tu\" with lyrics from movie \"Aashiqui 2\"
produced by T-Series Films & Vishesh Films, starring Aditya Roy Kapur,
Shraddha Kapoor in voice of Ankit Tiwari. \n\nSong: SUNN RAHA
HAI\nSinger: ANKIT TIWARI\nMusic Director: ANKIT TIWARI\nAssistant Mix
Engineer - MICHAEL EDWIN PILLAI\nMixed and Mastered by ERIC PILLAI
(FUTURE SOUND OF BOMBAY)\nLyrics:SANDEEP NATH\nMovie: AASHIQUI
2\nProducer: BHUSHAN KUMAR KRISHAN KUAMR Producer: MUKESH BHATT
\nDirector: MOHIT SURI\nMusic Label: T-SERIES\n\nBuy from iTunes -
https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy
& stay connected with us!! \n\nSUBSCRIBE T-Series channel for
unlimited entertainment\nhttp://www.youtube.com/tseries\n\nCircle
us on G+ \nhttp://www.google.com/+tseriesmusic\n\nLike us on
Facebook\nhttp://www.facebook.com/tseriesmusic\n\nFollow
us\nhttp://www.twitter.com/_Tseries","duration":"391","date":"2013-04-03"}
Edit
This worked suddenly.. :o
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data.desc);
console.log(data.desc);
$("#loader").hide();
}, "json");
});
In comments, you mention that this AJAX corresponds to a YouTube API.
YouTube's blog announced in 2012 that they would support CORS, which uses server-side header flags that compatible browsers interpret as permitting requests that would otherwise be prohibited by browser security Same-Origin-Policy.
Assuming, as you say, the first example worked, the first issue was "Why did (a subsequent) alert(data.title) fail? (my edit) ". If you type alert(data.title) in the console, it will fail because the scope of data is the callback function where it is defined as a parameter, and in the global scope data is undefined. If you try to pass data back to the global scope somehow, it can still be undefined because $.post returns immediately, before the data has been fetched, and merely queues a request and sets the callback function you supply to handle the reply.
The second example, which explicitly sets the $.post dataType parameter to 'json', may fail with CORS based API because the mime types for json are not allowed to be sent up to the server as Content-Type: for a simple CORS request, and $.post will as far as I know only do simple requests without preflight. $.ajax can possibly do the more complex requests if correctly applied.
The work around to keep using $.post is not to use json as the expected data type, send requests up as form data, the server may send you back json anyway if that is what the API says will happen, which can be verified while testing the code.
From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Simple requests
A simple cross-site request is one that:
Only uses GET, HEAD or POST.
If POST is used to send data to the
server, the Content-Type of the data sent to the server with the HTTP
POST request is one of application/x-www-form-urlencoded,
multipart/form-data, or text/plain.
Notice that application/json did not make the list of what Content-Type is permissible in a simple CORS request.
See also A CORS POST request works from plain javascript, but why not with jQuery?
Use ajax as
$.ajax({
url:url,
type:'post',
dataType:'json',
success:callback
})
With this type you can set lots of parameter in low level.
With datatype attribute jQuery parses JSON and send data as callback function.
I think you have to replace all single \ with double '\' to feed it to JSON.parse.

Get prayer time JSON data using JQUERY and Ajax

I want to READ JSON data using Jquery ana Ajax from this link
http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?
and this is my code:
$(document).ready(function() {
var strUser ="http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?";
$.ajax({
url: strUser ,
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert("yes");
});
}
});
});
I tried this code with other links , and it's correct, but from the specified link I don't get any out put, can you help me??
The url you are trying to access with JSONP doesnot support it. The server will need to return the response as JSON, but also wrap the response in the requested call back. So a way to solve this problem is using a server side proxy, which fetches the response from the specified url and passes it on to your client side js, like:
$.ajax({
type: "GET",
url: url_to_yourserverside_proxy,
dataType: "json",
success: function( data ) {
console.log(data);
}
});
where
url_to_yourserverside_proxy is a server side file that fetches response from the url specified
URL is outputting json but for cross domain need jsonp.
Not all API's provide jsonp. If cross domain API doesn't provide jsonp and isn't CORS enabled you will need to use a proxy to retrieve data due to same origin policy

Can't load json data in jquery

I am trying to get json data from twitter . http://api.twitter.com/1/statuses/public_timeline.json
this is my code
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
it is from http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_getjson
but it is not working !
You are running in the same origin policy in JavaScript. This basically says, that you can't access resources from different domains (in your case the other domain would be twitter.com).
One solution is to use JSONP. The twitter API supports this. You can run a JSONP-request with jQuery in your case like this:
$.ajax({
url: "http://api.twitter.com/1/statuses/public_timeline.json",
cache: false,
dataType: 'jsonp',
success: function( result ){
$.each(result, function(i, field){
$("div").append(field + " ");
});
}
});
Besides, w3schools is no reliable source for information. Better use something like the Mozilla Developer Network.
Check out the json document you are trying to load. It returns the following error when I try to access it:
{"errors":[{"message":"Sorry, that page does not exist","code":34}]}
I would try replacing the url with a working api call to twitter before you worry about whether the code snippet is working. :)
Your trying to get a document from a different domain and the requested URL is blocking your request due to Cross-Origin Resource Sharing. You can read up on that here: http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing
You can use JSONP with jQuery which should allow you to complete the request but that page you are requesting gets a 404 error so there's probably not much you can do with the result anyway.
You can Access json data from other domain using $.ajax() jquery method .See the code example below
$.ajax({
url : " // twitter api url",
dataType : "JSON",
cache : false,
success : function(success)
{
$.each(success, function(index,value) {$("div").append(value + ""); })
}
error : function() { //Statements for handling ajax errors }
});
The url you are using in that ajax request is returning a json array which contains an error
{"errors": [{"message": "The Twitter REST API v1 is no longer active. Please
migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}
You need to migrate to API v1.1 before process the request , Replace the twitter api url with the new json url which is provided in API v1.1

Categories

Resources