PHP script echo isn't executed - javascript

I am printing a very simple JavaScript using PHP, which doesn't get executed. If I print the data, I see the following script (exactly as needed) at the end of the HTML file:
<script type="text/javascript">
document.getElementById("message").innerText="Email already exists";
</script>
I have also tried using innerHTML="Email already exists";.
This is printed in PHP as such:
echo "<script type=\"text/javascript\">
document.getElementById(\"message\").innerText=\"Email already exists\";
</script> ";
In my HTML I have an element which has the ID: message. It looks like this:
<h3 id="message"> </h3>
What I am expecting is to get "Email already exists" in the h3, however this doesn't happen. The JavaScript is not executed. If I use the exact same JavaScript code but place it ahead or on an "onclick" request, the code works.
One thing which could be relevant: I noticed that the JavaScript is printed after the closing HTML tag.
How do i get the JavaScript code to execute after being echo'ed into the HTML? I've read several threads which said its supposed to simply run, however mine doesn't. I have tried about 50 different fixes, none of which worked.
The code: http://ideone.com/dmR42O

You mentioned this:
One thing which could be relevant. I noticed that the javascript is
printed AFTER the closing html tag (the ).
That is very relevant. Any Javascript must be contained within the <html> element (before </html>). But, be sure that the Javascript appears after the <h3>. Javascript will run when it's encountered, as Marc said in a comment above.
If the Javascript must be before the , then do this:
window.onload=function(){
document.getElementById("message").innerText="Email already exists";
};

Try it like this:
echo '<h3 id="message"> Email already exists!</h3>';
<!DOCTYPE html>
<html>
<body>
<form id="submitform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="logIn_email_input" name="email" type="text" placeholder="Enter e-mail address" autocomplete="off">
<input id="logIn_password_input" name="password" type="password" placeholder="Enter password" autocomplete="off">
<input id="logIn_submit" type="submit" name="logIn_submit">SIGN UP</button>
</form>
<?php
$query = mysql_query("SELECT userid FROM users WHERE email = '". $email ."'");
if (mysql_num_rows($query) > 0) {
echo '<h3 id="message"> Email already exists!</h3>';
}
?>
<body>
</html>
You had a lot of issue here (maybe typos ?)
action="<?php echo $PHP_SELF;?>" should be action="<?php echo $_SERVER['PHP_SELF']; ?>"
<button id="logIn_submit" should be <input id="logIn_submit" type="submit" name="logIn_submit">
<? php had extra space should be <?php
If statement was missing closing brace }
No <body> tags

Related

How can I display something from another page by using HTML/Javascript?

I have looked around for answers to this question but either do not understand the logic of the other answer, or have done something wrong trying to incorporate those answers.
I have 2 pages of HTML, where the first page has this form
<form class='registerbutton' action='registration.php' method = "POST">
<input type='email' name='email' placeholder='Email'>
<input type='submit' value='Register'>
<script> localStorage.setItem("useremail",email);</script>
</form>
When I do not use the method="POST" I can see in the URL that the email value is added onto the URL and therefore that this form works. However, in my next page I have this:
<body>
<script>
var test = LocalStorage.getItem("useremail");
document.write(test);
</script>
</body>
However, this does not work. I have also tried <?php echo email;?> but that also does not work. I am sorry if this is a trivial question. I am more used to other programming languages and am new to web development.
This solution will work client side only. Try it should work fine, it should work fine. If any thing else then let me know.
Page 1
<form class='registerbutton' action='registration.php' method="POST">
<input type='email' name='email' placeholder='Email' id="emailId">
<input type='submit' value='Register'>
</form>
<script type="text/javascript">
var email = document.getElementById('emailId');
email.addEventListener("keyup", function(event) {
localStorage.setItem('useremail', event.target.value);
});
</script>
Page 2
<body>
<script type="text/javascript">
var test = localStorage.getItem("useremail");
document.write(test);
</script>
</body>
SERVER SIDE
<?php
echo $_POST['email']; // In case of post and $_REQUEST['email'] will work for both.
?>
Since your method is POST, so you can access your email with PHP by the following:
<?php echo $_POST['email']; ?>

PHP/JavaScript form validation, invalid email check

So i'm working on form validation for a website.
What i have accomplished so far is when the form is submitted, validate.php checks if the email is in the correct format.
If it is, it proceeds in calling the sendMail() function included in the validate.php which proceeds in sending the email and then redirects the user back to the home page after 5 seconds. (This part works <-)
If it isn't, that's where i'm stuck.
What i'm trying to accomplish at this stage, is somehow get PHP to send a script tag, <script> emailError(); </script>, to the current page (contact.html) and execute the script which simply appends a paragraph saying that the email is incorrect. What i am getting, however is the validate.php has its own error in the else statement simply saying Error in a blank page (which is what i don't want, i put it there to see if the validation was working correctly).
I tried to add this (the script mentioned above) in the else statement in validate.php:
validate.php
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
echo("<script> emailError(); </script>");
}
?>
So what i was hoping it would do, is echo it into the page executing the JavaScript function but it didn't work and i think i know why.
PHP, to my knowledge, executes on request of user interaction (press button, click something, etc...) or upon page loading (Correct me if i'm wrong, still learning).
To make sure that the echo did not work, i inspected the page in real-time while using the form and didn't see any sign of the script tag being inserted into the HTML.
At this point, i have tried many alternative solutions, i don't even know where to begin. I could really use some help and any tips for improving my form.
This is the contact page that i'm working on. Feel free to try it out and see the results for yourself but Please don't spam!
Click Here
emailError.js
This is what i wanted to echo into the page with PHP.
function emailError(){
var targetElement = document.getElementById("emailform");
var errorElement = document.createElement("P");
var errorMessage = document.createTextNode("Invalid Email");
errorElement.appendChild(errorMessage);
errorElement.setAttribute("id","error");
document.body.appendChild(errorElement);
}
contact.html
This is just a segment of contact.html showing my form.
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
I'm not asking for something to copy n' paste, simply something to push me in the right direction.
Well, first of all, You are submitting your form to validate.php, and then never redirect back to contact.html, that's why you dont see the script tag appended. And from whay i see, that string 'Error' does not appear to be in your code, so I'm guessing that you did not paste the entire code. My suggestion, is to redirect to the contact form back again if the condition fails, and change contact.html to contact.php in order to be able to do a validation. Here is some rough code:
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
header('Location: contact.php?error=1');
}
?>
and then, in your contact.php file:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
if ($_GET['error']) {
echo "<script> emailError(); </script>";
}
This is just a rough example, it can be more robust, with this solution, if somebody enters your contact form with the query param "error" he will get the javascript executed. But as I said, this is a concept and a rough solution to explain how you could solve your problem.
You can't execute java function like you are trying to.
If you use ajax, than in the success response function, set the respone to a div.
For example, if you have a success function that gets the data in an argument called data, than set an empty div with an ID like "emailResponse" in your page, and use this in the function:
var responseDiv = document.getElementById("emailResponse");
responseDiv.innerHtml = data;
Add this to your html:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
<div id="emailResponse"></div>
</form>
And in your PHP, change to this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
echo "Your message was sent!";
}else {
echo "You email was invalid!";
}
UPDATE:
If you are not using ajax - you need to redirect to the contact page with some parameter in GET, or set some SESSION variable.

data insertion works but not showing alertbox message

i have tried below code to execute validation function and the data insertion operation the followed code runs correctly on chrome but firefox not showing the message of succesfully insertion..
<input type="submit" onclick="chk()";/>//chk() contains validations
<?
php
if(isset($_POST["submit"]))
{
data insertion code
if(true)
{
<script language="javascript">alert " Adverties added";window.location="adverties.php";</script>
}
}
?>
Put JS in echo:
echo '.. script ... JS code';
I don't know if it's stackoverflow mistake, but " Adv.. " text is not in ( )
So it should be:
if(true)
{
echo '<script language="javascript">alert(" Adverties added");window.location="adverties.php";</script>';
}
I think I got it working.
<form action="[name of the page]" method="post">
<input name="submit" type="submit" onclick="chk()"/>
</form>
<?php
if(isset($_POST["submit"])){
if(true){
echo'<script> alert("Adverties added");window.location = "adverties.php";</script >';
}
}
?>
so I put the <input> inside a <form> that redirects you to the current page and used the POST method.
You also have to use the name property inside of the input tag inorder for $_POST["submit"] to work, I also added the echo to print the JavaScript correctly.
I hope this solves your problems.
p.s. sorry for my bad enlish :)

PHP echo out javascript

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>
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>
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.
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.

Javascript redirect based on form input

I need to redirect one page to another page using the form value.
I have this code, which i think is fine for first page and what should i put in the other page where i want to show the data ??
<meta http-equiv='refresh' content='0;url=http://site.com/page.php'>
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php echo $url; ?>">
<script language="JavaScript">document.myform.submit();</script>
</form>
Regards
You can't mix a meta-refresh redirect with a form submission per se.
Also, meta-refreshes are terrible anyway. Since you are already in control of the receiving page, and it's using PHP, use that to accomplish the redirect. Try this:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="submit" value="Go!" />
</form>
Then, in page.php:
<?php
// Act on the input, store it in the database or whatever. Then do the redirect using an HTTP 302.
header('Location: http://example.com');
?>
If you need the form to pass the destination along to page.php, you'll want to sanitize it to prevent a LOT of security problems. Here's a rough outline.
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="destination" value="http://example.com" />
<input type="submit" value="Go!" />
</form>
Then, in page.php (copied re-encoding from answer https://stackoverflow.com/a/5085981/198299):
<?php
$destination = $_POST['destination'];
$url_parsed = parse_url($destination);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
// Check that $destination isn't completely open - read https://www.owasp.org/index.php/Open_redirect
$query = parse_url($destination);
$destination = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?" . http_build_query($query);
header('Location: ' . $destination);
?>
I haven't double-checked that code (just wrote it here in the browser), but it should suffice as a rough sketch.
in site.com/page.php
<script>window.location.href = 'newPage.php';</script>
You will have to write this outside the php tags though.
To redirect a page in PHP, use:
<?php
header('Location: url/file.php');
?>
To refresh to a different page in HTML, use:
<meta http-equiv='refresh' content='0;url=http://url/file.php'>
In the content attribute, 0 is the amount of seconds to wait.
To refresh to a different page in JavaScript, use:
window.location.href = 'url/file.php';
When none of these work, follow an anchor link, using HTML:
Click here to go now!
To answer your question, it can be done several ways:
1) Very bad, requires two files, super redundant
HTML file:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Submit the form
document.forms['myform'].submit();
</script>
Page.php:
<?php
// Catch url's value, and send a header to redirect
header('Location: '.$_POST['url']);
?>
2) Slightly better, still not recommended
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Set form's action to that of the input's value
document.forms['myform'].action = document.forms['myform'].elements['url'].value;
// Submit the form
document.forms['myform'].submit();
</script>
3) Still very redundant, but we're getting better
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Simply refresh the page to that of input's value using JS
window.location.href = document.forms['myform'].elements['url'].value;
</script>
4) Much better, save yourself a lot of trouble and just use JS in the first place
<?php
// Start with a PHP refresh
$url = 'url/file.php'; // Variable for our URL
header('Location: '.$url); // Must be done before ANY echo or content output
?>
<!-- fallback to JS refresh -->
<script type="text/javascript">
// Directly tell JS what url to refresh to, instead of going through the trouble to get it from an input
window.location.href = "<?php=$url?>";
</script>
<!-- meta refresh fallback, incase of no JS -->
<meta http-equiv="refresh" content="0;url=<?php=$url?>">
<!-- fallback if both fail (very rare), just have the user click an anchor link -->
<div>You will be redirected in a moment, or you may redirect right away.</div>
Save that with a .php extension, and you should be good to go.

Categories

Resources