How to send a text from an input using twilio and svelte? - api

I see a lot of docs for this but nothing javascript. My lack of knowledge is coming into play here, so forgive me. I want to send a simple text to a phone number that is typed into an input. I have a serverless function set up but i don't know how to pass in the phone number to it, beyond that I have tried to write a post request to it but I must be way off. Is what I am doing possible?
let phoneNumber;
const handleSendText = () => {
fetch("https://svelte-service-xxxx.twil.io/sms", {
method: "post",
body: "This is a test",
headers: {
"Content-Type": "application/json",
},
to: JSON.stringify(phoneNumber),
from: "+xxxxxxxxxxx",
})
.then((response) => {
if (!response.ok) {
throw new Error("failed");
}
})
.catch((err) => {
console.log(err);
});
};
<input type="text" placeholder="phone number" />
<button on:click={handleSendText}>Send</button>

You'll need to bind the value of the <input> to a variable in your script.
<script>
let phoneNumber = "";
const handleSendText = () => { // we'll come back to this };
</script>
<input type="text" placeholder="phone number" bind:value={phoneNumber} />
<button on:click={handleSendText}>Send</button>
That makes it so that when you change the value in the input it updates the phoneNumber variable.
Now, in your handleSendText function you need to send all the parameters within the body of the request. Note, in the following code how the body contains all the parameters you want to send in one JSON stringified object.
const handleSendText = () => {
fetch("https://svelte-service-9106.twil.io/sms", {
method: "POST",
body: JSON.stringify({
to: phoneNumber,
from: "+18035298025"
}),
headers: {
"Content-Type": "application/json",
}
})
.then((response) => {
if (!response.ok) {
throw new Error("failed");
} else {
console.log("Success!");
}
})
.catch((err) => {
console.log(err);
});
};
Then, in your Twilio function you will be able to access the parameters you send in the event object. In this case, you will have event.to and event.from.

Related

NextJS - How to pass select box value to the API call using getInitialProps

I want to send the selected value (Month) to the API from the DropdownButton as a post request.
I am fairly new to the NextJS and I will really appreciate it if someone can help me pass the drop-down selected value
Please see the code below.
Code:
class Reports extends React.Component {
static async getInitialProps() {
const res = await fetch("https:testendpoint",{
method: 'POST',
headers:{
'Content-Type': 'application/json',
Accept: 'application/json',
'Authorization': 'ApiKey testapikey'
},
body: JSON.stringify({"from":"2022-{Month}-07T20:00:00.000Z","to":"2022-{Month}-07T21:00:00.000Z"})
})
const json = await res.json()
return {
data: json.data.value
}
}
render() {
return (
<DropdownButton>
<Dropdown.Item eventKey="01">January</Dropdown.Item>
<Dropdown.Item eventKey="2">February</Dropdown.Item>
<Dropdown.Item eventKey="3">March</Dropdown.Item>
</DropdownButton>
)
}
}
In the above API call, I am sending date (from) and (to) and I want the selected month to override the post-request.
You can do send selected months by this way :
const Reports = () => {
const [selectedMonth, setSelectedMonth] = useState(null);
useEffect(() => {
async function postSelectedMonth() {
let fromSelectedMonth = `2022-${selectedMonth}-07T20:00:00.000Z`;
let toSelectedMonth = `2022-${selectedMonth}-07T21:00:00.000Z`;
let response = await fetch("https:testendpoint", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "ApiKey testapikey",
},
body: JSON.stringify({
from: fromSelectedMonth,
to: toSelectedMonth,
}),
});
response = await response.json();
dataSet(response);
}
selectedMonth && postSelectedMonth();
}, [selectedMonth]);
const monthChangeHandler = (e) => {
let month = e.target.value;
setSelectedMonth(month)
};
return (
<div>
<select name="months" id="month" onChange={(e) => monthChangeHandler(e)}>
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="Mar">Mar</option>
<option value="Apr">Apr</option>
</select>
</div>
);
}
export default Reports;

data sent with vuex action return undefined

i'm using axios with vuex, i need to send data with json form to execute post request and add new row with axios, i'm using vuex, when action is trigered it doesn't keep the data and sent it on action, the data json is created on vue componment but don't send it to action to execute axios post :
Action.js:
export const addClassification = ({data}) => {
console.log('data actio:', {data})
axios
.post("/vendor/classification/save", data, {
headers: {
"Content-Type": "application/json",
// withCredentials: true //sent with cookie
Authorization: "Bearer " + Vue.$cookies.get("jwt"),
}
})
.then((res) => {
console.log('res', res)
// commit("ADD_TO_CLASSIFICATION", data);
})
.catch((err) => {
console.log(err);
});
state.js:
export default {
vendorClassificationList: [],
}
page.vue:
<BaseButton
label="Modifier"
classValue="btn-outline-primary"
#click.native="addClassificationData"
/>
data() {
return {
submitStatus: "",
name: this.$route.params.name,
id: this.$route.params.id,
code: this.$route.params.code,
jsonData:[]
};
},
methods: {
...mapActions(["addClassification"]),
addClassificationData() {
this.jsonData = JSON.stringify({
id: null,
name: this.name,
code:this.code,
active:true
})
console.log('json is', this.jsonData)
this.addClassification({
data : this.jsonData
})
},
Actions is Vuex receive the vuex context as the first param, as you can see in the docs.
In other words if you change in Action.js:
addClassification = ( {data}) => {
to
addClassification = (vuexContext, {data}) => {
it should do the trick. You can call the param vuexContext, context, destructure it if needed or call it _ if unused (as in your case), doesn't really matter, as long as it's there.
Your vuex action is wrong. You are missing the context which can use argument restructuring. Also, you probably need to send res.data within the commit instead of res, depending on what are you doing in your mutation.
actions: {
addClassification ({ commit }, payload) {
axios
.post("/vendor/classification/save", payload, {
headers: {
"Content-Type": "application/json",
// withCredentials: true //sent with cookie
Authorization: "Bearer " + Vue.$cookies.get("jwt"),
}
})
.then((res) => {
console.log('res', res)
commit("ADD_TO_CLASSIFICATION", res.data);
})
.catch((err) => {
console.log(err);
})
}
}

How do I use Vuelidate with a custom validator?

I’m trying to validate a 6 digit code with vuelidate. If this.validationcode equals false I want to show a validation error. I'm pretty new to vue so I'm not entirely sure where I'm going wrong. How do I get this to work?
The error I get is:
TypeError: Cannot read property '__isVuelidateAsyncVm' of undefined
JS
data() {
return {
validationcode: false,
validationRules: [
{ vcode: {
required,
numeric,
minLength: minLength(6),
maxLength: maxLength(6),
validCode () { return this.validationcode }
} },
],
};
},
I also tried it as an arrow function but it doesn't get the value properly from the looks of it.
validCode: () => {
console.log("the val code is " + this.validationcode)
return this.validationcode
}
HTML - v.formData.vcode.validCode - In the current front end view, this rule is triggered every time.
<div class=“form-group”>
<input
type=“text”
class=“form-control”
:class=“hasError(‘vcode’) ? ‘is-invalid’ : ‘’”
placeholder=“Enter your 6 digit code”
v-model=“formData.vcode”
/>
<div v-if=“hasError(‘vcode’)” class=“invalid-feedback”>
<div class=“error” v-if=“!$v.formData.vcode.required || !$v.formData.vcode.minLength || !$v.formData.vcode.maxLength”>
Enter your 6 digit code
</div>
<div class=“error” v-if=“!$v.formData.vcode.numeric”>
Should be a valid value.
</div>
<div class=“error” v-if=“!$v.formData.vcode.validCode”>
Code incorrect, please try again.
</div>
</div>
</div>
This is the method that I am assigning true/false to this.validationcode.
verifyNumber() {
var numbers = /^[0-9]+$/;
if (code.match(numbers)) {
// Twilio functions do not accept multipart/form-data
const data = new URLSearchParams();
data.append("phone_number", m.mobileNumber);
data.append("verification_code", code);
fetch("https://saffron-cheetah-1234.twil.io/check", {
method: "POST",
body: data,
})
.then((response) => response.json())
.then((json) => {
if (json.success) {
console.log("Successfully verified the token.");
this.validationcode = true;
} else {
this.validationcode = false;
console.log(this.validationcode);
console.log("Incorrect token.");
}
})
.catch((err) => {
console.log(err);
});
} else {
}
},

How To Attach File On Axios Post Request In Vue

Hello I am trying to attach file for axios.post however when I do a console.log() the formData is empty so here is what I am working with.
On my vue form
<form #submit.prevent="uploadTodos">
<div>
<input type="file" v-on:change="selectedFile($event)">
<label>Choose file</label>
</div>
<button type="submit">Submit</button>
</form>
Here is the data object
data() {
return {
file: null,
}
}
and method I have for the selectedFile on change event
selectedFile(event) {
this.file = event.target.files[0]
},
and here is the submit event method
uploadTodos() {
let formData = new FormData
formData.append('file', this.file)
this.$store.dispatch('uploadTodos', formData)
}
and here is the store method being dispatch
uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}
and when I console.log(file) I get the formData I created in the uploadTodos() method however it is empty, So I am trying to figure out why it is empty?
any help would be greatly appreciated

Quasar Framework Uploader with axios

A question about the quasar framework uploader component.
I need to post the images to a URL that will rename the uploaded file and return the full path.
I'm using the upload-factory and axios
But I'm having problems understanding exactly how to pass the file to axios as if it was just an input type file.
Basically I need to make it as If I'm sending a form with a single input file like this:
<input type="file" name="banner">
This is the component:
<q-uploader
url=""
extensions=".gif,.jpg,.jpeg,.png"
:filter="filterFiles"
:upload-factory="uploadFile" />
This is the upload method, but I keep getting an error response from the server.
uploadFile (file, updateProgress) {
const formData = new FormData()
formData .set('banner', file)
var headers = {
'Content-Type': 'multipart/form-data'
}
axios.post('http://someurl/uploadFile', formData , headers)
.then(function (response) {
console.log(response)
})
.catch(function (response) {
console.log(response)
})
}
If I post a plain html form with method="post" enctype="multipart/form-data" and a
<input type="file" name="banner">
I get my OK response from the server with the processed/uploaded image URL
I have successfully done uploading of the file to python API.
V1 Update
Use #added -> function(files) method.
Also extensions property is removed now use accept
This is the component:
<q-uploader
url=""
extensions=".gif,.jpg,.jpeg,.png"
#add="file_selected"
/>
<q-btn #click="uploadFile()">Upload</q-btn>
Data:
data() {
return {
selected_file:'',
check_if_document_upload:false,
}
}
Methods
file_selected(file) {
this.selected_file = file[0];
this.check_if_document_upload=true;
},
uploadFile() {
let fd = new FormData();
fd.append("file", this.selected_file);
axios.post('/uploadFile', fd, {
headers: { 'Content-Type': undefined },
}).then(function(response) {
if(response.data.ok) {
}
}.bind(this));
}
This is working fine for me.
I have successfully done direct uploading of the file on a button click to python API. But in vue3 and Quasar 2 with some additional formData. Thought might be helpful
This is component:
<q-btn
label="Upload"
#click="openFilePicker"
/>
<q-uploader
ref="uploadFile"
class="hidden"
accept=".jpg, .jpeg, .png"
#added="uploadFileFn"
/>
Setup:
setup() {
return {
uploadFile: ref(null),
}
},
Methods:
openFilePicker() {
this.$refs.uploadFile.pickFiles();
},
uploadFileFn(file) {
this.uploadFile = file[0];
let fd = new FormData();
fd.append("file", this.uploadFile);
fd.append("id", "1");
fd.append("name", "test_user");
this.$axios.post('/upload_file_with_additional_form_data', fd, {
headers: {'Content-Type': undefined},
}).then(
function (response) {
if (response.data.success) {
console.log(response)
}
}.bind(this))
}
This is working fine for me.