Ajax autocomplete from youtube search, Cross-Origin Request Blocked - javascript

EDIT: I was able to solve this, thanks for you time
I am trying to make an autocomplete on a search form for youtube videos.
I got the url you can use from here: Youtube API search auto-complete
And I'm using this script (though I don't think it has much to do with the problem I'm having): https://goodies.pixabay.com/javascript/auto-complete/demo.html
code I'm using
var xhr;
new autoComplete({
selector: '.search-box',
source: function(term, response){
try { xhr.abort(); } catch(e){}
xhr = $.getJSON('https://suggestqueries.google.com/complete/search?client=firefox&ds=yt', {
q: term,
dataType: "jsonp"
}, function(data) {
console.log(data)
response(data);
});
}
});
gives me the response:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q=test&dataType=jsonp. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Am I just not allowed to do this?

install a chrome plugin "Allow-Control-Allow-Origin"

To prevent Cross Site Scripting (XSS) attacks, XHR's are limited in the domains that they can contact. But there are ways around this that also keep users secure.
Route the request through your own domain, but this depends on your server side architecture
If developing a browser extension, like in chrome it is possible to configure the manifest to allow the communication
Or, enable cross-origin requests by modifying headers sent by the server, like in
PHP
Node.js
I would not suggest asking users to install extensions that usurp this very important policy

Was able to figure it out thanks to this answer: https://stackoverflow.com/a/6120260/929321
Changed from .getJSON to .ajax and added dataType: 'jsonp'.
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});

Try the provided youtube search API by getting the credentials from the API console. Here is the link and you can try it out there as well : https://developers.google.com/youtube/v3/docs/search/list
$.get(
"https://www.googleapis.com/youtube/v3/search",{
part : 'snippet',
q : 'batman',
key: 'YOUR_API_KEY'},
function(data) {
console.log(data);
//do the manipulation here
}
);

Related

CORS issue while submitting data to google forms in angular

While submitting the data :
Error Message : XMLHttpRequest cannot load https://docs.google.com/forms/d/xxxxxxxxxxxxx/formResponse. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8090' is therefore not allowed access. The response had HTTP status code 405.
$scope.postDataToGoogle = function(){
$http({
method: 'POST',
crossDomain: true,
url: 'https://docs.google.com/forms/d/XXXXXXXXXXXXXXXXXXXXXXXX/formResponse',
// dataType: "xml",
data: tempData,
}).success(function(data,status){
//alert(data)
console.log("Success");
}).error(function(data,status) {
console.log('Error:' + status);
});
}
Its not about jquery or angular, CORS allows or disallow done by Back-end server.
Google might not support this.(to access https://docs.google.com)
CORS (Cross-Domain Resource Sharing) allows you to more cleanly separate your front-end from your back-end.
CORS is a group of special response headers sent from the server that tell a browser whether or not to allow the request to go through
Access-Control-Allow-Origin: http://example.com.
Why does jQuery throw an error when I request external resources using an Appcache Manifest?
I do have tried with angular still not able solve it, but with jQuery its works for me.
$.ajax({
url: 'https://docs.google.com/forms/d/xxxxxxxxx',
data: tempData,
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
alert('error');
},
200: function () {
alert('Thank you for your valuable feedback');
}
}
})

Calling External API with Javascript

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?
This is what I have so far using jQuery and ajax:
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'json',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
It is throwing a alerts that just says "Status:" and "Error:"
The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."
Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.
If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).
Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN
You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.
It would be something like that:
$("#ButtonForm").click(function(){
$.ajax({
url:(Your url),
dataType:'json',
type: 'post',
data: yourForm.serialize(),
success:function(response){
** If yout API returns something, you're going to proccess the data here.
}
});
});
Ajax:
http://api.jquery.com/jquery.ajax/
You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.
Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.
My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.
When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.
Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'jsonp',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If you use jquery, use .post, or .ajax, to submit
$.post(url, data, callbackSuccess, callbackError);
more about these methods here http://api.jquery.com/jquery.ajax/
example:
var url = 'http://example.com/path/endpoint';
$.post(url, {name: 'Darlan', lastname: 'Mendonça'}, function(response){
// callback success
}, function(response) {
// callback error
});

Reddit API /api/morechildren returns "No 'Access-Control-Allow-Origin' header" using mootools

I've tried the following basic Reddit API morechildren request using mootools:
var moreChildren = new Request({
async: true,
url: 'http://www.reddit.com/api/morechildren',
method: 'post',
data: {
api_type: "json",
children: "cl2vjlp",
link_id: "2ijczu",
sort: "top"
},
onSuccess: function(response){
commentData = JSON.parse(response);
console.log(commentData);
}
});
// tried above request with and without the following line
delete moreChildren.headers["X-Requested-With"];
moreChildren.send();
And I'm receiving a XMLHttpRequest cannot load http://www.reddit.com/api/morechildren.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403. in Google Chrome.
Observations:
Adding .json to reddit/api/morechildren(.json) does not resolve
deleting "X-Requested-With" header does not resolve
Any help is greatly appreciated. :)
This is because of same origin policy - CORS.
you do well to remove this:
// tried above request with and without the following line
delete moreChildren.headers["X-Requested-With"];
but if the reddit site does not support it, it won't work.
you have 2 options:
local proxy, ajax call to local, local server-side to reddit, back and output to browser
use JSONP where available.
can't test your case as it needs oauth but via info.json which is GET, you can:
http://jsfiddle.net/dimitar/zy3rwpjs/
new Request.JSONP({
url: 'http://www.reddit.com/api/info.json',
callbackKey: 'jsonp',
data: {
url: 'http://www.reddit.com/buttons'
},
onSuccess: function(response){
console.log(response.data, response.kind);
}
}).send();
obviously, when it expects POST, things get more complex... JSONP works as GET.
if all you care about is your own project and google chrome, you can start with with --disable-web-security flag, which will allow the call.

Creating an API in yii for cross domain communication

I am planning to create a Restful API in yii for cross domain communication. As what I have researched, cross domain communication can only be done via jsonp and my implementation is as follows:
UsersController:: actionCrossDomain
public function actionCrossDomain(){
$this->layout=false;
$data['data']['User']['name']= 'Johny';
$this->_sendResponse(200, CJSON::encode($data),'application/json');
}
UsersController::_sendResponse methdod it is the same as you can see in :Click here
On another server that i configured using virtual host, I am invoking the above method via ajax:
$( document ).ready(function() {
$.ajax({
type: "POST",
dataType: "jsonp",
url:'http:'http//uxaserver.local/alpha2/app/users/crossDomain' ,
data: null,
processData: false,
crossDomain: true,
contentType: "application/json",
success: function (data) {
console.log("done");
},
error: function (request, status, error) {
console.log(request);
}
});
});
The issue is my firebug is is complaining that : SyntaxError: invalid label
My requirement is such because I am helping my client's to do some customized analytic to his other websites and I need to put a script in his web pages of different domains so that the analytic data is recorded in the main server. I understand that I need to use the rest interface to communicate thus I am taking this approach. I am not sure if I have taken the right approach and please advice. I want to make it in a way where a client has an api key and can communicate with the api provided by me.
Is there any other approach to do this? Rather than jsonp?
As i see this string contents error
url:'http:'http//uxaserver.local/alpha2_uxarmy/app/users/crossDomain' ,
Should be
url:'http//uxaserver.local/alpha2_uxarmy/app/users/crossDomain' ,

Get OAuth request token through JSONP

I am trying to make a pure JavaScript Twitter application. I'm not concerned about the security involving the tokens since this is for internal use.
Currently, my code looks like this:
$.ajax({
url: 'https://api.twitter.com/oauth/request_token',
type: 'post',
data: {
oauth_callback: callbackurl
},
dataType: "jsonp",
headers: {
"oauth_nonce": nonce1,
"oauth_callback": callbackurl,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": Math.round(new Date().getTime()/1000),
"oauth_consumer_key": "IQKbtAYlXLripLGPWd0HUA",
"oauth_signature": "Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", //generate
"oauth_version": "1.0"
},
success: function(data)
{
console.info(data);
}
});
This code is rather incomplete, but the goal is to get what Twitter is returning (the request tokens). Obviously this code is not going to work because it violates cross origin policy. I have heard that this is possible with pure JavaScript, though. I need to send Twitter headers (at least, I think they have to be headers) then retrieve what they return.
Is there a workaround for this?

Categories

Resources