How do I display a person’s name in the onclick message="Alert()"?

Asked

Viewed 141 times

1

I made a customer registration file I wanted to enter the client’s name in onclick="alert()" every time the registration operation was made showing his name with the message Cliente fulano cadastrado com sucesso. How do I do that?

<form method="POST">
<p> Nome: <input type="text" name="nome" size=30 maxlength="30" required=""> </p>
<p> <input type="submit" name="Inserir" onclick="alert('Cliente $nome cadastrado com sucesso')" value="Cadastrar cliente"> </p>
</form>
// No PHP
$nome = $_POST['nome'];
  • I don’t know if I understand you very well, but you’d like to concatenate the Nome with what? If you can rephrase your question better.

  • I would like to display the customer name in the message that is displayed on onclick="alert()".

1 answer

3


Brothão, I think that to do this with Javascript is better and easier than to do with PHP.

By clicking the button we call the function displayName().

When the function displayName() is called, it only displays Alert() if the variable "name" is not empty.

Document.querySelector() passes the value that is in the field with id "name" to the variable "name".

function exibirNome() {
  let nome = document.querySelector("#nome").value;
  //Esse IF serve para só chamar o alert se o nome for preenchido (a variável nome tiver valor
  if (nome) {
    alert("Cliente " + nome + " cadastrado com sucesso");
  }
}
<form method="POST">
  <p> Nome: <input type="text" name="nome" id="nome" size=30 maxlength="30" required> </p>
  <p> <input type="submit" name="Inserir" onclick="exibirNome()" value="Cadastrar cliente"> </p>
</form>

The ideal would be for you to display the "Success" message, only after verifying that the operation was actually performed successfully in PHP. Because, the way you’re doing, the message is displayed before the data goes into PHP and the data is actually entered into the database.

You run the risk of an error and the data will not be entered in the database, and even then the "Success" message would have already been displayed.

If you want me to write the answer for this case, leave a comment, then I edit the answer and put this option too.

See if it suits you. Any questions, just ask. See you later!

  • You’re right, that way it got better, thank you.

  • You’re welcome, my friend.

  • In this case it would be better to put message like this: xxxxx client we are processing your registration :)

  • That’s right, little Leo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.