Ajax POST request to new Google Analytics V4 API - javascript

Google Analytics v4 API was just released and GET requests were changed to POST requests. And there are no good examples out there yet...
So I've successfully received accessToken, but when I try the following POST request - I'm always getting empty object Object { }, but I'm sure that data is there and ViewID is correct!
Any advice helps! Thank you!
requestAnalyticsData1 = function (accessToken) {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
url += "access_token="+accessToken;
var params = {
"reportRequests":[{
"viewId":"121238102",
"dateRanges":[{
"startDate":"yesterday",
"endDate":"today"
}],
"metrics":[{
"expression":"ga:users"
}],
"dimensions": [{
"name":"ga:pagePath"
}]
}]
}
$.ajax({
url: url,
type: "POST",
data: params,
dataType: "json",
success: function(results) {
console.log(results)
parseAnalyticsReportsData(results);
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});
};

Solution was to replace this part:
data: params,
dataType: "json",
With this:
data: JSON.stringify(params),
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},

Related

Jquery / JSON handle XHR Response

I am posting some JSON info using the code below. Currently, if it is successful (200 response) the alert pops up, but if it is unsuccessful nothing happens.
What I would like to do is basically say if successful do X, else do Y.
I have try using an if / else statement within the function, but it doesn't seem to work.
Apologies if this is a silly question, I am new to working with JSON, XHR etc. Any assistance would be greatly appreciated.
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
EDIT: Working Code:
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
add this line to your return jQuery.ajax({}) function:
error: function(xhr, ajaxOptions, thrownError){
window.alert(thrownError);
}
hope this helps~

Firebase Dynamic Link Creation With JavaScript

var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});

Post AJAX API Javascript SAPUI5 failed

I want to use POST method with AJAX in SAPUI5 javascript but I found an error.
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
nomorDosir: "01001961288",
kodeCabang: "A02"
}),
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: " + data + " " + JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
error:
I already did change code with dataType=text, or data: {nomorDosir: "01001961288", kodeCabang: "A02"} (without stringify), but I not yet find the solution. How to fix this problem?
Thanks.
Bobby
Not sure what your use case is but if you are trying to post to an oData service, it might be much easier to use SAPs createEntry method where the URL is the path to the model you want to post to and your JSON are the properties:
var oModel = new sap.ui.model.odata.v2.ODataModel("https://services.odata.org/V2/OData/OData.svc/");
//oModel should use your service uri
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
oModel.createEntry(url, {
properties: {
nomorDosir: "01001961288",
kodeCabang: "A02"
}
}, {
method: "POST",
success: function(response) {
alert(JSON.stringify(response));
//do something
},
error: function(error) {
alert(JSON.stringify(error));
}
});
oModel.submitChanges();
What you have is wrong json format, you have:
data: JSON.stringify({nomorDosir: "01001961288", kodeCabang: "A02"}),
Which actually should be:
data: {"nomorDosir": "01001961288", "kodeCabang": "A02"},
Which then you don't need to do a json.stringify on, because it already IS a json format. Hope this will help you out.
Which you could also try is setting a variable outside like this:
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
var json = {"nomorDosir": "01001961288", "kodeCabang": "A02"};
$.ajax({
type: "POST",
url: url,
data: json,
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: "+data+" "+JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});

Convert a cURL API call to Ajax

curl --basic --user {username}:{password} https://www.blueworkslive.com/api/Auth
I have tried to write something like this but it won't work! I keep getting error 400
$.ajax({
url: "https://www.blueworkslive.com/api/Auth",
type: "GET", //This is what you should chage
dataType: "jsonp",
username: "admin", // Most SAP web services require credentials
password: "admin",
processData: false,
contentType: "application/json; charset=utf-8",
success: function () {
alert("success");
console.log("success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
console.log(xhr.responseText);
alert(xhr.status);
alert(xhr.responseText);
},
});
And this as well:
{$(document).ready(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.blueworkslive.com/api/Auth?version=20091212", false);
xhr.setRequestHeader("Authorization", "Basic " + btoa("username.com:password"));
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin: *");
xhr.send("");
alert(xhr.status);
alert(xhr.responseText);
});}
Error: Origin is not allowed by Access-Control-Allow-Origin. I assumed the error was caused due to me running the script from a local server (since the origin was set to null by default) so I deployed it on a app development server so that I had a public origin.The same error occurred for the new origin - even though the origin now was not null anymore but the server provided origin!
$(document).ready(function(){
$(function (){
$.ajax({
url: 'https://www.blueworkslive.com/api/Auth', // url checked ...// error 400 not found url
data: {
//data
username:username,
email:email
},
dataType: 'json',
success: function(data)
{
//result success
}
});
});
});

Using ajax posting not getting any responce

<script>
function login() {
var postData = {
"UserName": "user#gmail.com",
"Password": "123",
"RememberMe": true
};
$.ajax({
url: "url",
type: "POST",
data: postData,
success: function (Data) {
alert("success");
},
error: function () {
alert("Failure");
}
});
}
</script>
here i am not getting any responce either success message r failure message. please help me
You can try updating these attributes more:
data: JSON.stringify(postData),
dataType: "json",
Try using by the following its works fine.if it not works let me know.
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function login() {
var postData = {
"UserName": "user#gmail.com",
"Password": "123",
"RememberMe": true
};
$.ajax({
url: "ChangePasswordSuccess.aspx",
type: "POST",
data: postData,
success: function (Data) {
alert("success");
},
error: function () {
alert("Failure");
}
});
}
</script>
Try This, you might get benefit from xhr.status
$.ajax({
cache: !1,
type: "POST",
data: $.toJSON(c),
contentType: "application/json; charset=utf-8",
url: e,
success: function (a) {
doStuff(a)
},
error: function (xhr, ajaxOptions, thrownError) {
alert(ajaxOptions);
alert(thrownError);
alert(xhr.status);
}
});
Note a is json response of request made to url e While c is data to be posted to the url.
Your URL is not valid !
compelete url property of ajax request and test again.

Categories

Resources