Receive text typed in input text, put in variable and apply in link
I want to receive the text in a field typed by the user and, when clicking on submit, the same will be generated a link with the text and sent to whatsapp as in the code below:
<form action="https://api.whatsapp.com/send?phone='.$telefone.'&text='.$texto.'" method="POST" target="_blank">
<input type="text" name="text" placeholder="Digite sua mensagem..." autocomplete="off">
<button class="trwpwhatsappsendbutton" name="enviar" type="submit">
<i class="fa fa-paper-plane-o"></i>
</button>
</form>
How can I do this?
2 answers
In this your code nothing will occur, since this action
is totally wrong. action
should call a post API, but without passing PHP-named parameters into it.
What you want to do would be more or less:
<?php
if(isset($_POST['telefone'])){
$telefone = $_POST['telefone'];
$texto = $_POST['texto'];
$resposta = file_get_contents("https://api.whatsapp.com/send?phone=" . $telefone . "&text=" . $texto);
echo $resposta;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $resposta; ?>
<input type="text" name="telefone"/>
<input type="text" name="texto"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Even so, it is not recommended. The recommended is to make use of jQuery, with each code in separate files, in the form of:
HTML ---> FORM ---> jQuery ---> PHP ---> WhatsApp API
You can even call the WhatsApp API directly from the form, assuming:
<form action="https://api.whatsapp.com/send/" method="POST" target="_blank">
<input type="text" name="text" placeholder="Digite sua mensagem..." autocomplete="off">
<input type="text" name="phone" placeholder="Insira o telefone (com o +55)..." autocomplete="off">
<button class="trwpwhatsappsendbutton" name="enviar" type="submit">
<i class="fa fa-paper-plane-o"></i>
</button>
</form>
In this way, text
and phone
would be sent to the API.
Just handle the submit
event of the form and make the necessary changes.
$(function() {
$('#send-message-whatsapp').on('click', 'button', function(e) {
e.preventDefault();
const $form = $("#send-message-whatsapp");
const phone = '5512999999999';
const text = $form.children('input[name="text"]').val();
const action = "https://api.whatsapp.com/send?phone=" + phone + "&text=" + text;
$form.attr('action', action);
$form.attr('target', '_blank');
$form.submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="send-message-whatsapp">
<input type="text" name="text" placeholder="Digite sua mensagem..." autocomplete="off">
<button class="trwpwhatsappsendbutton" name="enviar" type="submit">Enviar</button>
</form>