Posting to YouTube API with jQuery - javascript

I am trying to post a request to the google authSub for youtube. I use jQuery for AJAX posts etc. When I make the POST I get a 405 error: "405 Method Not Allowed".
Here is my js:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
},
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
});
The page I am using in the API for this is here.
Here is what the error looks like:

Your data parameters for the request are misplaced see below:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
data: {
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
}
});
Now it may be something youre doing wrong additionally, but this for sure needs to be corrected.

Ah, here is a solution to the problem. If I make the request with the url built out and assigned as an href to an anchor or call it in window.open(); it works.
window.open('https://www.google.com/accounts/AuthSubRequest?scope=http://gdata.youtube.com&next=http://' + globalBrand + '/sitecreator/view.do&session=1');
As for why jQuery's method with the ajax was being rejected I know not. It seems to be an issue elsewhere also.

Solution to error HTTP HEADER OPTIONS in JQuery, this request is ok for me:
var word = 'search+word';
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/api/videos?q="+word+"&max-results=10&alt=json-in-script&format=5,
cache: false,
dataType:'jsonp',
success: function(data){
//json 'data' var treatment
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert("Not able to fetch the data due to feed unavailability!!!");
}
});
Reference: http://www.mohammedarif.com/?p=180

Related

slim framework and ajax. '/' character as a parameter

I'm making an ajax call to a Slim framework web service. This is for sending notes to my database.
The problem is that the users can write for example "send 1/2 piece". So when I make the call, the URL throws 404 not found because of the '/' character.
Is there any way to avoid this problem?
notes = 'send 1/2 piece'
$.ajax({
type: 'GET',
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + notes,
dataType: "json", // data type of response
beforeSend: function(xhr, settings){
},
success: function(data){
},
error: function(xhr, status, errorThrown){
errorPopup(errorThrown);
},
complete: function(xhr, status){
}
});
You need to run EncodeURIComponent against notes, only.
Before your ajax call:
notes = 'We have funny characters in here like /es';
encNotes = EncodeURIComponent(notes);
Then, create your url string using the encoded string.
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + encNotes,

How to parse parameters from Ajax return string

I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Access JSON with JQuery which has authentication

I want to receive json from this API but it has authentication which username(nama pengguna) is "foo" and password(sandi) "foo". How I can receive it in my program? I use Jquery and eant build it with phonegap and build for Android
I am trying like this
$.ajax({
url: 'http://api.tabloidnova.com/1/subscribe/get?api_key=259225f04f4015746b03e1bad6238eaa&format=json&channel_id=110',
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization","Basic foo:foo");
},
dataType: 'json',
async: false,
success: function(data){
$.each(data,function(i,grab){
console.log(grab[i].article.node_id);
console.log("tes");
})
}
})
but in my ripple emulator it still give me unauthorized error. If I use without ripple emulator it can't work because I run it from localhost which has origin policy. Any suggestion?
SOLVED now. Finally I encode it my username and password first. Thanks
You will need to set the appropriate request header to pass the credentials. See for example here.
$.getJSON({
'url': 'http://host.com/action/',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
//May need to use "Authorization" instead
xhr.setRequestHeader("Authentication",
"Basic " + encodeBase64(username + ":" + password)
},
sucess: function(result) {
alert('Done');
}
});
In javascript, with ajax we can do this way:
$.ajax({
'url': 'http://host.com/action/',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password) //May need to use "Authorization" instead
},
sucess: function(result) {
alert('done');
}
});
Check the documentation for jQuery.ajax(). You will have more options to implement this.

Cross Domain AJAX POST / HTTPS / Header Authentication?

I have to issues:
1) I've tried using JsonP, but can't get POSTing to work. Essentially, I'm trying to authenticate with an API, passing a Base64-encoded namevaluepair in the header over HTTPS.
2) How do I pass this key/value in the header? Any help would be appreciated! Here is an example of what I want, though this obviously doesn't work:
// where does this go?
var headerString = 'user=' + encodeURIComponent(username + ':' + password);
$.ajax({
type: "POST",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
success: function(data) {
},
error: function(data){
}
});
add headers to ajax call:
var headerObj = {'user': encodeURIComponent(username + ':' + password)};
$.ajax({
type: "GET",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
headers: headerObj,
success: function(data) {
},
error: function(data){
}
});
The best way to do this is probably through a server side proxy on your own domain.
See this page for tips.
This way you will be able to get the response from the other server

Categories