Leonoliveira
Leonoliveira

Reputation: 25

How can I confirm something in JavaScript and then use

I have a form and when you submit it, a JavaScript message appears.

$message = "Want to insert?";
echo "<script type='text/javascript'>window.confirm('$message');</script>";

And what I want to do is, if the person clicks 'OK' it inserts values in the database, if not it cancels it.

$titulo = $_POST['titulo'];
$mensagem = $_POST['mensagem'];
$ano = $_POST['ano'];
$mes = $_POST['mes'];
$dia = $_POST['dia'];
$link = " ";

Upvotes: 0

Views: 79

Answers (3)

XeNo13GrIn
XeNo13GrIn

Reputation: 122

You need to pass data using a request to your server. You cannot use JavaScript to write in you database directly since you already use PHP

But to confirm the user before you send your request or you can use this in your JavaScript code before you send your request.

if (confirm('Your Message')) {
    // User click OK
    // Send your data to server using a Request
} else {
    // User click cancel
}

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

In simple words, PHP executes first, and then client side JavaScript executes. If you want it to be interactive, you must use AJAX, which will allow you to send PHP command controlled by JavaScript.

If I were you, I would do this way:

if (confirm("Are you sure?"))
  $.post("path/to/php.php", {data: you_need_to_send}, function (response) {
    if (response == "OK")
      alert("All Done!");
  });
else
  alert("You cancelled the insertion.");

Note: Here, $.post() is a jQuery implementation of AJAX POST method. Just for ease of explanation I gave this. Please don't shout at me for answering a jQuery way for a JavaScript question.


Update

You can use onsubmit of the form to make this possible. Make sure you give a return inside the event:

<form method="post" action="http://example.com/" onsubmit="return confirm('Are you sure?');">
  <input />
  <input type="submit" value="Send" />
</form>

Run the above snippet and check it out.

Upvotes: 2

Venkatesh K
Venkatesh K

Reputation: 4584

Use <form> tag, and handle the onsubmit event. once he clicked 'OK' on message box submit the form.

Once the form gets submitted, In server side (PHP) write a code to get the data ( either by GET/POST which ever way you are sending) and insert into the table.

Upvotes: 3

Related Questions