Reputation: 41
I'm trying to insert javascript into a div. All of this is within a php document.
I am trying to get a div to fade into view when it's child div is loaded. Parent div had id of 'subemail' (this is hidden) Child div with id 'error' is shown then it should fade in the above div.
Following is the script I'm trying to load but get error unexpected T_STRING, expecting ',' or ';'.
<script type="text/javascript">
$(function(){$('div#subemail').fadeIn('slow');});
</script>
The PHP document:
if (empty($_POST['sub_name'])) {
$errors[] = 'Please type in your name';
} else {
$sub_name = strip_tags($_POST['sub_name']);
}
if (filter_input(INPUT_POST, 'sub_email', FILTER_VALIDATE_EMAIL)) {
$sub_email = $_POST['sub_email'];
} else {
$errors[] = 'Please type in a valid email';
}
if ($errors) {
echo '<div class="errors">';
echo '<script type="text/javascript">';
echo '$(function(){$('div#subemail').fadeIn('slow');});';
echo '</script>';
foreach ($errors as $error) {
echo '<p class="error">- ' . $error . '</p>';
}
echo '</div>';
}
Upvotes: 1
Views: 17275
Reputation: 239240
You need to escape your quotes with backslashes:
echo '$(function(){$(\'div#subemail\').fadeIn(\'slow\');});';
The problem is you're opening a string with the first '
, and closing it at 'div#...
. rather than closing it at the end of the line. Most languages use a backslash to denote a quote which is part of the string, rather than terminating the string.
You could also switch contexts, which I think cleans things up drastically; just be sure to separate your view/controller logic by moving the below to a template file of some kind:
<? if ($errors) { ?>
<div class="errors">
<script type="text/javascript">
$(function() { $('div#subemail').fadeIn('slow'); });
</script>
<? foreach ($errors as $error) { ?>
<p class="error"><?= $error ?></p>
<? } ?>
</div>
<? } ?>
Upvotes: 10
Reputation: 4016
alternatively, you can write
echo "$(function(){$('div#subemail').fadeIn('slow');});";
Upvotes: 1