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-9106.twil.io/sms", {
method: "post",
body: "This is a test",
headers: {
"Content-Type": "application/json",
},
to: JSON.stringify(phoneNumber),
from: " 18035298025",
})
.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>
CodePudding user response:
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
.