I’m currently messing with google’s apis using ajax trough jquery library.
In order to use a google service API i need to get an auth token sending a request to ClientLogin. Actually, i’ve no idea how to pass the token to the second request .
I’ve set a global variable token as var token = null;
I call two requests on $(document).ready event.
- The first one is an https POST
request to google clientLogin in
order to get user credential token.
Here’s the code of the first ajax request :
$.ajax({
type: "POST",
url: "https://" + host + clientLoginEntryPoint,
data: cLRequestData(accountType, user, pwd, service),
dataType: "html",
success: function (response) {
var tokenArray = response.split("="); // Split to response tokenArray[3] is the auth token
token = tokenArray[3];
$(".status").html(token);
}
}); // END OF CLIENT LOGIN REQUEST
-
The second one is supposed to call the contacts API with an http GET.
$.ajax({ type: "GET", url: "http://" + host + googleContactEntryPoint, beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'GoogleLogin auth=' + token); xhr.setRequestHeader('GData-Version', '3.0'); }, success: function(response, textStatus, xhr) { var names = $(response).find('entry>title').text(); $(".status").text(names); }, error: function(xhr, status, error) { $(".status").html(xhr.status+ " "+ xhr.statusText ); }}); // END OF GOOGLE CONTACT REQUEST
The problem i’m facing is that token is set to null when i try to set Google Authentification Header in the second request. I’ve already read link text but this is not working for me. I now that must be something to do with callback/events but i’m couldn’t figure how to do this.
Any help appreciated
Question was updated:
You are redeclaring a local variable in your first request namedtoken, so it doesn’t use the globaltokenthat you initiated withnull.Remove the
varkeyword in the first request.If the requests run sequentially, then the second will not wait for the first to receive its response before it executes.
If that’s the case, place the second request in a
function, and call that function from thesuccess:callback in the first.(In this code, you could actually get rid of the global
tokenvariable, and just pass thetokenfrom the first request to the second as a function parameter.)