I am searching for an example on how to push metric to the pushgateway via ajax.
echo 'some_metric 42' | curl --user user:pass --data-binary #- https://example.com/metrics/job/author_monitoring/jobname/count_open
with curl it works perfect!
I don't know how to translate this in js/jquery.
Maybe someone has an example
Here is what I got so far.
(function ($, $document) {
"use strict";
function textToBin(text) {
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin)
.join(' ')
);
}
var username = "user";
var password = "pass";
var metric = 'some_metric 42';
var binaryData = textToBin(metric);
$.ajax({
url: "https://example.com/metrics/job/author_monitoring/jobname/count_open",
data: binaryData,
type: 'POST',
crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
success: function () {
console.log("Success");
},
error: function () {
console.log('Failed!');
}
});
})($, $(document));
here is the error:
text format parsing error in line 1: invalid metric name
okay I got it.
There is an easy solution, import is the \n at the end of the string.
(function ($, $document) {
"use strict";
var username = "user";
var password = "pass";
var metric = 'some_metric 42\n';
$.ajax({
url: "https://example.com/metrics/job/author_monitoring/jobname/count_open",
data: metric,
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
xhr.setRequestHeader("Content-Type", "text/plain");
},
success: function () {
console.log("Success");
},
error: function () {
console.log('Failed!');
}
});
})($, $(document));
Related
I have a problem, my code works correctly in all browsers except IE.
IE returns me SCRIPT1002 Syntax error.
This line:
if(data.responseText.match(/Произошла.*/)) {
On next code:
localRequest: function(period, adapter, adapterType, errText){
let _this = this;
let iRow = rowInfo.iRow;
let aboutRow = rowInfo.aboutRow;
queryState = $.ajax({
type: 'get',
url: 'api/ds/cs',
dataType: 'json',
data: {
period: period,
adapter: adapter,
adapterType: adapterType,
errText: errText,
subject: iRow.value,
body: aboutRow.value
},
}).done(function (data) {
}).fail(function(data){
**if(data.responseText.match(/Произошла.*/)) {**
let errText = data.responseText.split(')',)
let errNumb = errText[0].split('(',)
alert('Не удалось сформировать проишествие: ' + errText[1] + ' №' + errNumb[1])
} else {
alert(data.responseText);
}
})
},
How can I turn the results from Script 1, Name, Email, Teamsinto variables I can use in script 2?
I am making an API call to fetch some JSON I then want to use certain values as text in a message I then send to slack.
Example.
$('.Name').html(data.user.name); // Returns John
$('.Email').html(data.user.email); // Returns John#John.com
$('.Teams').html(data.user.teams[0].name); // Returns JohnsTeam
var text = 'Hello my name is $Name + my email is $Email + From $Teams'
Output = Hello my name is John my email is John#John.com From JohnsTeam
Script 1
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Script 2
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
One great solution is to set the variable you get from the response in the HTML5 localstorage as follows:
Inside ur success:
success: function(data) {
localStorage.setItem("urdata",JSON.stringify(data));
}
In the other script, u can retrieve the data like this:
var data = localStorage.getItem("urdata"); data = JSON.parse(data);
Can anyone help me put my three snippets below into one usable script.
1) Get active window URL
2) Strip URL for ID only
3) Concatenate API request to include ID from URL
The below returns my current window URL.
chrome.tabs.query({active: true, currentWindow: true},
function(tabs) {
var tabURL = tabs[0].url;
console.log(tabURL);
});
Example....https://myapi.com/users/PLLFFR6
function test() {
var urlID = tabURL.split("/");
urlID = urlID[urlID.length-1];
}
This splits down https://myapi.com/users/PLLFFR6 and returns only "PLLFFR6"
var authorizationToken = "xxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/' + urlID + '?include%5B%5D=contact_methods&include%5B%5D=teams');
Based on this example myapiRequest should =
**/users/PLLFFR6?include%5B%5D=contact_methods&include%5B%5D=teams**
Something like this should work:
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
function apiRequest(endpoint, options) {
return new Promise(function (resolve) {
$.ajax(
$.extend({}, {
type: 'GET',
dataType: 'json',
success: function(data) {
resolve(data)
},
url: 'https://api.website.com/' + endpoint,
headers: {
Authorization: 'Token token='+authToken,
Accept: 'application/vnd.myapi+json;version=2'
}
}, options)
)
})
}
/* example usage */
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return apiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Note that since you're using chrome.tabs, this will only work as a Chrome extension, not in a browser. You'll also need jQuery loaded (to use $.ajax and $.extend).
I have the following code:
var Faculty180API = {
token: '1a88be52b9e9dd649998c3c1979b6b5c79cc160e',
base_url: 'https://www.faculty180.com/api.php',
account: 'DemoLinks',
last_results: null,
fetch: function(path, params, callback) {
$.ajax((this.base_url + this.make_path(path)), {
data: this.make_params(params),
crossDomain: true,
xhrFields: { withCredentials: true },
success: callback,
dataType: 'json',
error: function(xhr) {
if(xhr.status == 200) {
$('#results').text(xhr.responseText);
}
else {
$('#URL').text(Faculty180API.base_url . HERE);
$('#results').text(xhr.status + ' - ' + xhr.statusText);
}
}
});
},
make_params: function(params){
params['token'] = this.token;
return $.param(params);
},
}
In the line that I have written HERE, I want to add what Function(params) returns to the output. How can I do this?
Haven't tested this, but I'm thinking you can just call it like this:
$('#URL').text(Faculty180API.base_url + Faculty180API.make_params( yourParams ) );
Also note that I changed your . (after base_url) to a +. Dot is string concatenation in PHP; in Javascript it's +
I'm faced with trying to add testing to a lot of code like the following. I know I can use mockjax to to intercept the ajax calls. But I don't how to test the $.ajax({...}) calls in isolation. I'd appreciate a good refactoring approach, but I'd also like to avoid rewriting the entire app.
I've gotten a start in other areas using qunit, and I like it. But I'm open to other suggestions too. How should I proceed?
function submitSync(repFrom, continuousRep, storedPassword) {
// var repTriggered = false;
if (repFrom !== '' && (storedPassword !== null || storedPassword !== "")) {
var secureHome = "http://" + homeUser + ":" + storedPassword + "#" + window.location.host + "/" + homeURL;
var theSource = repFrom.split("/");
var singleDocumentReplication = (theSource.length === 5);
/*
* DELETE existing replications. There will normally be no more than 1.
* Do not delete replications for application updates.
* Note that we don't allow the user to create continuous replications.
*/
$.getJSON(currentHost + '/_replicator/_all_docs', function (data) {
$.each(data.rows, function (i, theRow) {
$.ajax({
url: currentHost + '/_replicator/' + theRow.id,
type: "GET",
dataType: 'json',
async: false,
contentType: "application/json",
success: function (doc) {
if (doc._id !== "_design/_replicator" && (typeof doc.source !== 'undefined' && !doc.source.match(onlineBase + '/' + remoteDB))) {
$.ajax({
url: "/_replicator/" + doc._id + "?rev=" + doc._rev,
type: "DELETE",
contentType: "application/json",
success: function () {
console.log('Replication deleted: ' + doc._id + '?rev=' + doc._rev);
}
});
}
}
});
});
});
if (singleDocumentReplication) {
var theDoc = theSource[4];
var repFromBase = repFrom.substr(0, repFrom.indexOf(theDoc) - 1);
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFromBase, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3,
"doc_ids": [theDoc]
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
} else {
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFrom, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
}
}
}
Looks like you've got a ton of code duplication. My recommendation would be to put your ajax calls into modules and pass the $.ajax as a dependency.
So:
function myModule(ajaxDependency, anyOtherDependency) { }
This way in your unit test you simply check to make sure your dependecies behave a certain way. And it looks like it will eliminate all your DRY issues.