Im new to web development, I apologize in advance. I have a form where the user can write a simple message and then the browser will open whatsapp web containing the message previously written. I need to pass a function to the action="" of the form to make this work. I can't figure it out.
What I tried and worked so far:
<form id="user_form" action="https://api.whatsapp.com/send?phone=123456789&text=Hello" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
<input type="submit" value="connect us" >
</form>
It works just fine, but i want the text parameter (https://api.....text=VARIABLE) to be the message that the user writes.
I tried to do this, but doesn't seem to work:
<form id="user_form" onSubmit="return sendMsg()" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
<input type="submit" value="connect us" >
</form>
<script>
function sendMsg(){
var actualMsg = document.getElementById("msg").value;
document.user_form.action = "https://api.whatsapp.com/send?phone=123456789&text=Hello";
return false;
}
</script>
CodePudding user response:
What you need is an event listener that updates the value of your action
attribute.
const url = 'https://api.whatsapp.com/send?phone=123456789&text=';
document.getElementById('msg').addEventListener('keyup', (e) => {
document.getElementById('user_form').setAttribute('action', url e.target.value);
console.log(document.getElementById('user_form').getAttribute('action'));
})
<form id="user_form" action="" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
<input type="submit" value="connect us" >
</form>
CodePudding user response:
Call the function on submit and inside the function use javascript to send the request using the method the API requires. Using a similar code.
var url = "sample-url.php";
var params = "lorem=ipsum&name=alpha";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//use proper headers and method as specified in api
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);