I have been trying to get the Object id of the parse user, so that i can send it to the users phone number. The cloud code is done in javascript which i am not familiar with. I believe the problem is with my code. Here is what i have done so far:
var twilio = require("twilio");
twilio.initialize("myAccountSid","myAuthToken");
// Create the Cloud Function
Parse.Cloud.define("inviteWithTwilio", function(request, response) {
// getting objectId from Parse
var query = new Parse.Query("objectId");
query.equalTo("username", request.params.number);
query.find({
success: function(httpResponse){
response.success("Code found");
},
error: function(httpResponse){
response.error("Code not found");
}
});
// Use the Twilio Cloud Module to send an SMS
twilio.sendSMS({
From: "myTwilioPhoneNumber",
To: request.params.number,
Body: "Start using Parse and Twilio!" + query
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
I need help making this code work. And advice on books i can read to improve my understanding of JavaScript would be useful.
Was finally able to solve my problem. All i actually needed was Parse.User.current().id. Here is the working code:
var twilio = require("twilio");
twilio.initialize("myAccountSid","myAuthToken");
// Create the Cloud Function
Parse.Cloud.define("inviteWithTwilio", function(request, response) {
// Use the Twilio Cloud Module to send an SMS
var objectId = Parse.User.current().id ;
twilio.sendSMS({
From: "myTwilioPhoneNumber",
To: request.params.number,
Body: "Your Apps verification code is " + objectId
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
Related
I've been developing a simple RESTful API with NodeJS and Express. When the backend was done and operative, my next step was to make HTML forms to fill the database and consume the API. I decided that using jQuery to submit the data would be a nice idea to get some practice .
So basically I want to get from a $.post the body and status that my app's backend generates whenever it recieves a POST request. Here's the form's script:
$('#addcube').submit(function(event){
//Stop the default behaviour of the submit button
event.preventDefault();
//Get the input values
var $form = $(this),
postData = {
nombre: $form.find('input[name="nombre"]').val(),
brand: $form.find('input[name="brand"]').val(),
capas: $form.find('input[name="capas"]').val(),
kind: $form.find('input[name="kind"]').val()
},
url = $form.attr('action');
$.ajax({
url: url,
type: 'post',
data: JSON.stringify(postData),
contentType: "application/json",
done: function(cube, textStatus, jqxhr){
console.log(JSON.parse(cube));
},
fail: function(jqxhr, textStatus, errorThrown){
console.log(errorThrown.msg);
}
});
});
And here's the backend route for that post:
app.post('/api/cube', cubeController.addCubo);
Which is controlled by this script:
module.exports.addCubo = function(req, res){
var Cube = require('../models/cube');
console.log('POST');
try{
console.log(req.body);
var cubo = new Cube({
nombre : req.body.nombre,
brand : req.body.brand,
capas : req.body.capas,
kind : req.body.kind
});
cubo.save(function(err){
if(!err){
console.log('Nuevo cubo guardado.');
res.send(JSON.stringify(cubo));
res.status(200);
}else{
console.log('Error al guardar: '+err);
res.send('{"status":"400","msg":"bad_request"}');
res.status(400);
}
});
}catch(err){
res.send('{"status":"500","msg":"internal_server_error"}');
}
};
No body property exists at response, use . Set $.post() type to json, or use JSON.parse() at .done(). Also, if sending error, use .fail() to log messages
var send = $.post(url, {
nombre : name,
brand : marca,
capas : layers,
kind : tipo
}, "json"); // set expected response type to `"json"`
// Try to get the result
send.done(function(cube, textStatus) {
console.log(cube, textStatus)
});
// handle errors
send.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown, errorThrown.msg)
});
I am using twilio api code in jquery,its working fine.
but i want to implement it in pure javascript,how can i do that with only javascript?
My code is here.
$(document).ready(function() {
$("#btnSubmit").click(function(){
var SID = "AC654656****************"
var Key = "df5456**************"
$.ajax({
type: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/' + SID +'/Messages.json',
data: {
"To" : "+919580834781",
"From" : "+12018647238",
"Body" : "Test"
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(SID + ':' + Key));
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
can anyone please suggest me the solution?
Twilio developer evangelist here.
We do not recommend you use front end JavaScript to make calls to the Twilio API. It requires you to embed your Account Sid and Auth Token in your front end (or make it accessible from your front end) which means that an attacker could steal your credentials and use them to abuse your account.
We recommend you perform any actions with the Twilio API on the server. We do have a Node.js module on npm to make that easy to work with. Here's an example of sending an SMS message with the Node.js module:
var client = require("twilio")(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
client.messages.create({
body: "Hello",
to: TO_NUMBER,
from: FROM_NUMBER
}).
then(function(result) {
console.log("Message sent!");
}).
catch(function(err) {
console.log("Error sending message: ", err);
})
Check out this blog post introducing the Twilio Node.js module for more information.
Let me know if that helps at all.
What I am trying to do: I am using parse server with javaScript SDK to change a field value for an already existing user.
The code that i am using
var query = new Parse.Query(Parse.User);
query.equalTo("username", "someUserName");
query.find({
success: function(users){
console.log("user found", users);
users.set("name", "new name");
users.save(null,{
success: function(updated){
//worked
},
error: function(error, updated){
//didn't work
}
});
},
error: function(error, users){
console.error("error at querying: ", error);
}
});
The issue : this does not update the name field value.
What i have discovered from researching this issue
: seems like i have to utilize the sessioToken or/and masterKey like this(show below) but that also did not work.
users.save(null,{useMasterKey:true}{
success: function(updated){
//worked
}
I am quite confused at the moment, any help would be appreciated.
Your master key or session token should be the first parameter.Have a look at the Parse.Object.save API
https://www.parse.com/docs/js/api/classes/Parse.Object.html
Try something like this
users.save({useMasterKey:true}, {
success: function(updated){
//worked
}
error: function(err){
}
});
So I am trying to get the cloud code to do an aftersave event that pings another location to do some data saving.
It has some data that needs to be sent as well.
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var pieceName = "Robert Rauschenberg Quote";
var url = 'http://www.gilmancontemporary.com/wp-content/uploads/2015/06/Delicate_Garden.The_Bear.48x42.jpeg';
Parse.Cloud.httpRequest({
url: artistURL,
dataType : "text",
crossDomain: true,
type:"GET",
data : {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response(httpResponse.text);
},
error: function(httpResponse) {
response('Request failed with response code ' + httpResponse.status)
}
});
});
The code does not give an error, or any warnings. Me saving/creating entries works fine.
Cors is already handled, as I can successfully make this call with an ajax script.
Any clue why this is not sending?
Can I not have data in a parse httpRequest?
Can it not be crossdomain?
Alternatively
Is there a way to test this code outside of the Parse Cloud???
The way you call httpRequest function is not correct in cloud. You also do not need to worry about CORS as you are not working in a browser environment. Try this instead:
Parse.Cloud.httpRequest({
url: artistURL,
params: {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response(httpResponse.text);
},
error: function(httpResponse) {
response('Request failed with response code ' + httpResponse.status)
}
});
To test this outside cloud environment you can use the curl command. It will be something like:
curl -G -v "http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php" --data-urlencode "pieceName=Robert Rauschenberg Quote,url=http://www.gilmancontemporary.com/wp-content/uploads/2015/06/Delicate_Garden.The_Bear.48x42.jpeg"
I am not a JSON specialist and therefore I need help to solve a little problem.
When submitting a form, before the form closes, it returns 'Unexpected end of input'.
I have searched the Internet and this forum, I found nothing solving the problem. I hope you'll be able to help me sort it out.
So, to make it easier for you, what's going on?
The user requests a listing. He fills the form with a message and a price. The item_id is transmitted directly (and working as I get it working so far).
The form data are sent via JSON to a remote server (VPS) which un-json the data. However, in addition to the 'unexpected end of input', I got on my remote server 'Server response: 400 (Bad Request)'
I am almost sure it is due to this code and not the remote server one.
I have identified thanks to debug that the error is at the line :
JSON.parse(data);
$('#requestListingSubmit').click(function (evt) {
evt.preventDefault();
rL_form.hide();
rL_load.show();
rL_controls.hide();
rL_alert.empty();
var item_id = $(this).data('item-id');
var route = '/request';
$.ajax(
{
type: 'POST',
url: coreURL + route,
data:
{
'item_id': item_id,
'message': $('#message').val(),
'price': $('#price').val(),
},
success: function (data)
{
try
{
JSON.parse(data);
window.location = coreURL+'/account/listings?new';
}
catch(e)
{
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert(
{
type: 'danger',
message: 'Error: '+e.message
});
}
},
error: function (jqXHR, status, httperror) {
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert({
type: 'danger',
message: (jqXHR.responseJSON.message || httperror)
});
}
});
});
Thank you very much guys!