Reputation: 12708
On form submit, I want to give the user a message.
Originally, I was doing
if(isset($_POST['submit'])) {
echo "submitted";
}
But this would appear randomly at the top of the page.
I want control where the message is output, so I wanted to append the message to a DOM element... to do that, I thought I could use JavaScript as so:
if(isset($_POST['submit'])) {
echo "<script type=\"text/javascript\">
document.getElementById(\"submitmsg\").innerHTML = \"submitted\";
</script>";
}
The HTML shows that the PHP seems to output the JS correctly, but submitmsg
is empty.
Any thoughts?
HTML form: calls itself so it can run the PHP code at the top of the page:
<form role="form" action="" method='post' accept-charset='UTF-8'>
<div class="row">
<div class="form-group col-xs-12 floating-label-form-group">
<input class="form-control" type="text" name="name" placeholder="Name">
</div>
</div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" name="submit" class="btn btn-lg btn-success">Send</button>
</div>
</div>
</form>
Upvotes: 0
Views: 301
Reputation: 31
the other answers are pretty much the right way.. if you wanna stick with the way you're doing things now, just switch your php output to:
window.onLoad = document.getElementById("submitmsg").innerHTML = "submitted";
if the Page is reloaded anyway you can echo submitted where you need it.
Upvotes: 0
Reputation: 11943
Not sure what you really do since you didn't post all the code, but I see 2 options.
First : On submit, you use an ajax query and don't refresh the page. If that's the case you should use the oncomplete()
callback to do the javascript stuff (php should not return javascript code).
Second : The page is reloaded, then you should use PHP to directly echo html wherever you want in your code :
<nav ... >...</nav>
<p id='submitted><?= isset($_POST['submit']) ? "Submitted" : "" ?></p>
Note that you can put php tags where you want really :
<html>
<head>
<title><?php echo "Today is " . date('Y-m-d');?></title>
</head>
<body>
<?= "My Cool Body" ?>
</body>
<html>
Upvotes: 3
Reputation: 24406
I want control where the message is output
Why don't you store the submit status in a PHP variable and output it where required:
<?php
$is_submitted = isset($_POST['submit']);
?>
<html>
<body>
<!-- your page -->
<nav></nav>
<?php if($is_submitted) : ?>
<p id="submitmsg">Submitted</p>
<? endif; ?>
Or even just put your isset()
check inline further down your page.
But this would appear randomly at the top of the page.
There is no point in echoing out a Javascript call to display this message, you can put PHP where ever you want to in a document.
Upvotes: 1