POST data to google contact api - javascript

I want to create new contact in google contact with google api with javascript and jquery, i can retrieve contacts with this sample :
jQuery.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
"max-results=100&" +
"v=3.0",
headers: {
'Authorization': "Bearer xs55.CjDOA8lRTs8567657567vXXXX",
'Content-Type': 'application/json'
},
method: "GET",
dataType: 'jsonp',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('error: ');
console.log(data);
console.log(data.status);
}
})
Now i want to POST data and create or update items in google document there is always error ! :(
For example in this code "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XXX' is therefore not allowed access. The response had HTTP status code 405." error happened :
jQuery.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
"max-results=100&" +
"v=3.0",
headers: {
'Authorization': "Bearer xs55.CjDOA8lRTs8567657567vXXXX",
'Content-Type': 'application/json'
},
method: "POST",
data: {title: "vvvv", phonenumber: "3333"},
//dataType: 'jsonp',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('error: ');
console.log(data);
console.log(data.status);
}
})
whitout jsonp option there is no way to work that this option used when want to GET something not POST it .

Can you try this:
data= {title: "vvvv", phonenumber: "3333"};
$.ajax({
type: "POST",
data :JSON.stringify(data),
url: "https://www.google.com/m8/feeds/contacts/default/full?alt=json&" +
"access_token=xs55.CjDOA8lRTs8567657567vXXXX&" +
//"max-results=100&" +
"v=3.0",
contentType: "application/json"
});

Related

How to convert a Raw body data request for an API to ajax request

I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.

Ajax data response by POST

Well, I send POST request to server-side to get data (xls). I use fiddler and see binary in response, but Chrome tells me there is a Network Error 0x800c0007.
Server side based on WCF. Here I take HttpResponse, copy Stream from Excel to response.OutputStream, and say response.flush(). It goes without errors.
I see response with 200 Code. But chrome does not react to data.
Probably I use wrong header or need to set up Ajax in different way.
$.ajax({
url: url,
method: 'POST',
type: 'POST',
data: JSON.stringify({ 'options': options }),
contentType: 'application/json;charset=utf-8',
accepts: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
dataType: 'json',
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": '*',
"X-HTTP-Method": "POST",
'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
},
error: function (data) {
console.log("error: ", data);
a.resolve(null);
},
success: function (data, status, headers, config) {
if (data != null) {
a.resolve(data);
}
}
});
return a.promise();
This is my last attempt.
Is it possible to send to server data by Post and have a response with binary?

How to fix "status":403,"error":"Forbidden","message":"Access Denied"? when I call API using Ajax

When I call API to POST Request I get error 403 and "has been blocked by CORS Policy.
This is my Ajax Code:
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: $('meta[name="server-config"]').attr('content') + "/file/upload/?user_id=" + response.user_id,
data: data,
headers: {
'Authorization': `Bearer ${$('meta[name=auth-key]').attr('content')}`
},
processData: false,
contentType: false,
cache: false,
timeout: 3000,
success: function (data) {
console.log(data)
// location.reload();
},
error: function (e) {
console.log("ERROR : ", e);
}
});
In your post method file add the following header and try
header('Access-Control-Allow-Origin: *');

Best method for getting JSON from REST API with Token

I have a rest API which has some nice JSON I want. I want to be able to call the API from a script within some HTML and pull out the JSON thats relevant to me.
What would be my best approach?
Something like the below using ajax? but i can't find a nice working example.
I have a token for my API so its vital I can use this. A curl command would be perfect, alas I cant do that. Eventually what I do will be used in a chrome extension.
jQuery.ajax( {
url: 'https://my-api.com/rest/v2/users/'
type: 'GET',
data: { content: 'testing test' },
beforeSend : function( xhr ) {
xhr.setRequestHeader( "Authorization", "BEARER " + xxxxxxxxx );
},
success: function( response ) {
// response
}
} );
Try this
var myJson;
$.ajax( {
url: 'https://my-api.com/rest/v2/users/'
type: 'GET',
data: { content: 'testing test' },
headers: { 'Authorization' = 'Bearer ' + token },
success: function( response ) {
myJson = response;
}
} );
Here there is the official explanation of the getJSON() method with some examples
https://api.jquery.com/jQuery.getJSON/
var authorizationToken = "xxxxxxx";
function xRequest(endpoint, method, options) {
$.ajax($.extend({}, {
type: method,
dataType: "json",
url: "https://api.xxxx.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.xxxxxx+json;version=2"
}
},
options));
}
This works

Youtube Upload JS with API -> get 405 Method not allowed

I can't upload videos to youTube with Javascript anymore. If I call the URL
$.ajax({
url: VIDEOS_UPLOAD_SERVICE_URL,
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + accessToken,
'x-upload-content-length': file.size,
'x-upload-content-type': file.type
},
data: JSON.stringify(metadata)
}).done(function (data, textStatus, jqXHR) {
...DO SOMETHING
}
})
I get an Error 405 Method not allowed, but a few days/weeks ago everything works fine :-(
The VIDEOS_UPLOAD_SERVICE_URL is https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet
But if I call the ajax Request to fetch the categories that works fine...

Categories

Resources