If you’re using the Javascript library anyhow, you might as well use it for everything…
This example should work for both functions as well as variables, give ti a shot:
<html>
<head>
<title>Particle Javascript Example</title>
<script type="text/javascript" src="http://cdn.jsdelivr.net/particle-api-js/5/particle.min.js"></script>
</head>
<body>
Check the console to see the output of the code.
<br>
<button type="button" onclick="functionPost('Mandatory_function_name', 'Optional_function_argument_here')">function POST</button>
<button type="button" onclick="variableGet('Mandatory_variable_name')">Variable GET</button>
<script>
var particle = new Particle();
var token;
var ActualDeviceID = "ENTER_DEVICE_ID_HERE";
function functionPost(functionName, functionArgument){
var fnPr = particle.callFunction({ deviceId: ActualDeviceID, name: functionName, argument: functionArgument, auth: token });
fnPr.then(
function(data) {
console.log('Function called succesfully:', data);
console.log(data.body.return_value);
}, function(err) {
console.log('An error occurred:', err);
}
);
}
function variableGet(variableName){
var vrGr = particle.getVariable({ deviceId: ActualDeviceID, name: variableName, auth: token })
vrGr.then(
function(data) {
console.log('Device variable retrieved successfully:', data);
console.log(data.body.result);
}, function(err) {
console.log('An error occurred while getting attrs:', err);
}
);
}
particle.login({username: 'EMAIL_ADDRESS_HERE', password: 'PASSWORD_HERE'}).then(
function(data){
console.log('API call completed on promise resolve: ', data.body.access_token);
token = data.body.access_token;
},
function(err) {
console.log('API call completed on promise fail: ', err);
}
);
</script>
</body>
</html>