I am using a contact form on my website and I want it to use a javascript function to use a popup box to tell the user that they have not filled all fields. I have this code:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "Email sent!";
}
}
?>
</script>
However, the website displays this error:
Fatal error: Call to undefined function requiredfields() in /home/a8502709/public_html/test/contact.php on line 46
The line above is the line that it echoes the calling for the function. How can I properly call the function in echo?
You didn't quote your echo output:
echo requiredFields();;
It should be:
echo "requiredFields();";
Otherwise you're telling PHP to execute the requiredFields() function, which doesn't exist in PHP. Hence the error. Your intent here is to tell the JavaScript on the rendered page to execute the function. So as far as PHP is concerned you're just outputting a string to the page.
Note also that this is a syntax error:
echo "Email sent!";
What this will do is emit the following to the JavaScript in your <script> block:
Email sent!
Which, of course, isn't valid JavaScript. You probably meant to output that somewhere else in the page.
Edit: You also seem to have a significant logical error in your code. If you remove the unrelated lines, your structure is essentially this:
if ($action=="") /* display the contact form */
{
?>
<script type="text/javascript">
<?php
} else {
echo "requiredFields();";
}
?>
</script>
So... You only open the <script> tag in the if block, but you use that tag in the else block. By definition both can't execute. Only one or the other. So you're going to have to restructure this a bit.
Maybe close the <script> tag in the if block too, and then open another one in the else block? Or have multiple if/else blocks for the HTML and for the JavaScript? There are a couple of different ways to structure this. But you should see what I'm talking about when you view the page source in your browser. You'll see that, in the event of the else block, you're never creating a <script type="text/javascript"> line and therefore aren't actually executing any JavaScript.
Though, thinking about this some more, it doesn't make sense at all to have the JavaScript start in the if block. Since only the else block uses it. You can't define the function in the if and then try to use it in the else because, again, by definition only one or the other would execute. Maybe just move all of the JavaScript to the else:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<?php
}
else /* send the submitted data */
{
?>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "alert('Email sent!')";
}
?>
</script>
<?php
}
?>
Honestly, this mix of PHP/HTML/JavaScript you have here is a little confusing. Which isn't making this any easier for you. You'll probably want to re-structure this a bit once you get it at least working.
Related
Here's my code. Now here what happens is when I fill that specific form with just 1 input the data gets submitted and the alert is shown after that, but if I don't fill anything in the form and just click on submit button, the alert is shown even if the form is empty, and after the alert, it shows that please fill out this field.. so what went wrong? tried searching for this solution and tried so many things but nothing works... :(
<div class="newsletter">
<p>Sign Up for the <strong>NEWSLETTER</strong></p>
<form method="post">
<?php
if(isset($_POST['subscribe']))
{
$e_mail = $_POST['e_mail'];
$conn = new mysqli('localhost','root','','purrfect_whiskers');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
}
else
{
$stmt = $conn->prepare("insert into newsletter(e_mail) values(?)");
$stmt->bind_param("s", $e_mail);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
?>
<input class="input" type="email" name="e_mail" text-transform="lowercase" placeholder="Enter Your Email" autocomplete="off" required="required">
<button class="subscribe" onclick="submit_email()" type="submit" name="subscribe"><i class="fa fa-envelope"></i> Subscribe</button>
<script type="text/javascript">function submit_email(){alert("You've been subscribed to our newsletter!");}</script>
</form>
</div>
It looks like you should validate that the user did put in a value for email before allowing the submission. If they did not, present an error. If they did, allow the submission and on page refresh, present the success alert
There are a couple ways to prevent automatic form submission, one of them is to put an onsubmit handler in the form tag and have it return true (to allow the submission or false to prevent it. You can do all your validating in that handler:
<form method="POST" onsubmit="return submit_email()">
Then in your function, check that the value is there before allowing it to continue:
<script type="text/javascript">
function submit_email(){
let email_input = document.querySelector("input[name='e_mail']");
if (email_input.value=="") {
alert("Please type in your email first");
return false; // this prevents the form from submitting
}
return true; // this allows the submission
}
</script>
The form will submit, the page will refresh and your PHP code will do it's thing. At the end of which, just hardcode your alert, like this:
<?php
if(isset($_POST['subscribe'])){
// do all your code as you are, then end with:
?>
<script>
alert("You've been subscribed to our newsletter!");
</script>
<?php
}
?>
The alert code executes no matter what. You must therefore display it only if there is nothing in your form.
For that, I added an id in your input and I made a check to know if your form is empty or not.
The best would be to check with regex if it is indeed an email address but here is the code just to verify if it is just not empty
Here is the code:
<div class="newsletter">
<p>Sign Up for the <strong>NEWSLETTER</strong></p>
<form method="post">
<?php
if(isset($_POST['subscribe'])) {
$e_mail = $_POST['e_mail'];
$conn = new mysqli('localhost','root','','purrfect_whiskers');
if($conn->connect_error) {
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into newsletter(e_mail) values(?)");
$stmt->bind_param("s", $e_mail);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
?>
<input id="id_input" class="input" type="email" name="e_mail" text-transform="lowercase"
placeholder="Enter Your Email"
autocomplete="off" required="required">
<button class="subscribe" onclick="submit_email()" type="submit" name="subscribe"><i class="fa fa-envelope"></i>
Subscribe
</button>
<script type="text/javascript">function submit_email() {
if (document.getElementById("id_input").value !== "") {
alert("You've been subscribed to our newsletter!");
}
}</script>
</form>
</div>
I'm building a website, and I am incorporating PHP and Javascript into the website. What I am trying to do with this website is to use an interface that allows a user to "log in" in a sense, and then store the information entered through the use of cookies. I am trying to call an external js function using php, however for some reason, although the script tag is being added into the html document as desired, the function is not being called at all and can't figure out why or how to fix it. I have attached a portion of my code below. Thank you very much in advance.
My PHP code:
<?php
$fail="";
$success="";
if (isset($_POST['submit'])) {
echo "<script>console.log('Submitted');</script>";
$first=$_POST["first"];
$last=$_POST["last"];
$city=$_POST["city"];
if ($first!="test"||$last!="test"||$city!="test"){
$fail="This is an error message";
}
else{
echo "<script>console.log('This is working from html');</script>";
$success= "<script src='main.js'>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>
<script>
console.log("Hello World!");
</script>";
}
}
?>
Portion of my HTML:
<div id="container">
<?=$fail?>
<form action="" method="POST">
<p>Enter Family Name (as it appears on your invitation): </p>
<input class="entry" type="text" name="first" placeholder="FIRST NAME" required><br><br>
<input class="entry" type="text" name="last" placeholder="LAST NAME" required><br><br>
<input class="entry" type="text" name="city" placeholder="CITY (ONLY)" required><br><br>
<input name="submit" type="submit" style="margin:auto; display:block">
</form>
<?=$success?>
Javascript code:
function createCookie(name,value){
document.cookie=name+"="+value;
console.log("This is working");
console.log(document.cookie);
console.log("This is too");
}
function getCookie(name){
var split=document.cookie.split(";");
for (let i=0;i<split.length;i++){
if (split[i].indexOf(name)===0){
return split[i].substring(name.length+1);
}
}
}
This portion of code is creating a conflict in behavior in the web browser (you have both src and code in the same script tag):
$success= "<script src='main.js'>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>";
You should change this, by simply making a second script tag (splitting them up):
$success= "<script src='main.js'></script>
<script>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>";
That way the src does not negate any code content of the script tag.
Second, you should also quote the strings being added from php in those js function calls. Like so:
$success= "<script src='main.js'></script>
<script>
console.log('success variable is working');
createCookie('first',". json_encode($first) .");
createCookie('last',". json_encode($last) .");
createCookie('city',". json_encode($city) .");
</script>";
The use of json_encode here is to ensure the values are javascript safe to pass through and not break the script.
So far i have such code
<form action="register.php" target="login" type=post>
<label for="name">Account </label><br><br>
<input type=text id="name" name="account" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<label for="name">Password</label><br><br>
<input type=text id="name" name="password" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<button type=submit>Register</button>
</form>
I placed it inside an IFrame but when i try to use php with such code:
<?php
If (IsSet($_GET["account"]["password"])) { $Account = $_GET["account"]; $Password = $_GET["password"];
$AllRight = True;
For ($I=0; $I<StrLen(WrongChars); $I++) {
If (StrPos($Account, SubStr(WrongChars,$I,1))) {
Echo "<p>Your Name musn't contain the char \"".SubStr(WrongChars,$I,1)."\"</p>";
$AllRight = False;
}
}
If (file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
Echo "<p>This Account already exists!</p>";
$AllRight = False;
}
If ($AllRight) {
$Text .= "$Password ";
File_Put_Contents (AccountFilesPath.$Account.AccountFilesEnding, $Text);
if(!file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
echo "<p>Error during account cration!</p>";
}
Echo "<p>This Account is created succesfully!</p>";
}
}
?>
yet the responce im getting is a fresh registration page with no work done...
i want my iframe to individually register text files like (user1.txt) with ($Password) inside. Along with having a link to the login, and upon login have a User Control Panel.
I don't understand why you are using an iframe for this but I can see that you use $_GET in your php when your form submits $_POST (type="post")
Try changing that in your PHP code and see if it works
Edit*
As stated in the comments this is not a $_GET index $_GET["account"]["password"]
Let's say you stick with POST since your html form submits a POST,you must use something like this:
if(isset($_POST["account"]) && isset($_POST["password"]))
And to be sure what variables you get from your form, I recommend you to print your Post array before any manipulation.
print_r($_POST);
everybody.
I have the following situation:
I have:
http://example.com/ and http://example.com/new
In example.com, I have some forms that I load in example.com/new domain with fancybox iframe.
My form, basically shows some fields for the user to enter his pessoal data, like name, phone and etc... After he submit that, I show some user agreement terms that comes from database and a checkbox for the user to say that he agree with the terms.
After he check and submit, I want to alert some sucess message and the fancybox modal/iframe to close and thats it.
In the form page, i've loaded jquery, and bootstrap. So, when the user agree, I print:
<?php
echo "
<script>
alert('Some success message!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
?>
I have three forms, in one, works, in the other two, i get:
Error: Permission denied to access property '$'
The only difference between the form that works and the other two, is that in the form that works, i don't have the agreement terms coming from database, only the checkbox.
I could put my entire code here, but would be a giant question. But if you guys need, I can update.
Sorry for my english and forgive-me if I was not clear.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
/* Connect with DB */
require_once('require/conectar.php');
if(!empty($_POST))
foreach($_POST as $k => $v)
$$k = $v;
?>
<script type="text/javascript" src="http://example.com/new/assets/js/jquery.js"></script>
</head>
<body>
<?php if(!isset($agree) and !isset($next)): ?>
<h1>The form</h1>
<form method="post" action="">
<label>Your name:</label>
<input type="text" name="name">
<br>
<label>Your email:</label>
<input type="text" name="email">
<br>
<input type="submit" name="next">
</form>
<?php
else:
$error = (!isset($name)) ? true : false;
$error = (!isset($name)) ? true : false;
if($error)
{
echo '<script>You must fill all fields before submit.</script>';
exit;
}
$qrr = mysql_query("SELECT * FROM `terms`");
$terms = mysql_fetch_object($qrr);
?>
<h1>Terms:</h1>
<?php echo $terms->content; ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $name; ?>" name="name">
<input type="hidden" value="<?php echo $email; ?>" name="email">
<input type="checkbox" value="1" name="accept"> I agree.
<input type="submit" name="agree">
</form>
<?php
endif;
if(isset($agree))
{
/*
Here i mail me the user data.
*/
echo "
<script>
alert('Soliciação Realizada com sucesso!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
}else
{
echo "<script>alert('You need to agree with the terms to proceed.');</script>";
}
?>
</body>
</html>
This is a browser security thing. While there's a few ways around it, the best one is probably to use the postMessage API.
On your example.com parent page, add some code like this:
function handleMessageFromiFrame(event) {
alert('Some success message: ' + event.data);
//$.fancybox.close();
}
window.addEventListener("message", handleMessageFromiFrame, false);
And, then on your child example.com/new iframe, add code like this:
var parentOrigin = "*"; // set to http://example.com/ or whatever for added security.
function sendMessageToParent(){
parent.postMessage("button clicked", parentOrigin);
}
$('#submit-btn').click(sendMessageToParent);
Here's an example of it in action:
Parent example.com page: http://jsbin.com/hiqoyevici/1/edit?html,js,output
Child example.com/new iframe: http://jsbin.com/goferunudo/1/edit?html,js,output
When you click the button in the child page, it uses postMessage to notify the parent. Then the parent listens for the message and does whatever action you want.
I have a form built that works perfectly fine. However, when a message is successfully submitted, the user gets redirected to a new page with the 'success' message I have set up. Instead, I want the success message to be displayed in a div which is placed next to the form, and the form to reset in case the user would like to send another message. Likewise, I am also hoping to have my 'error' message show up in the same div upon failure. Was hoping someone can help with my if/else statement to make this possible.
Here's my HTML:
<div id="contact-area">
<form id="theform" name="theform" method="post" action="feedback.php">
<input type="hidden" name='sendflag' value="send">
<p>
<label for="Name">Name:</label>
<input type="text" name="name" id="name" value="" />
</p>
<p>
<label for="Email">Email:</label>
<input type="text" name="email" id="email" value="" />
</p>
<p>
<label for="Message">Message:</label><br />
<textarea name="message" rows="20" cols="20" id="message"></textarea>
</p>
<p>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</p>
</form>
</div>
<div class="message">
<p class="submitMessage"></p>
</div>
Here's my PHP:
<?php
$mail_to_send_to = "myemail#gmail.com";
$your_feedbackmail = "noreply#domain.com";
$sendflag = $_REQUEST['sendflag'];
if ( $sendflag == "send" )
{
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$headers = "From: $name" . "\r\n" . "Reply-To: $email" . "\r\n" ;
$a = mail( $mail_to_send_to, "Feedback form", $message, $headers );
if ($a)
{
print("Message was sent, you can send another one");
} else {
print("Message wasn't sent, please check that you have changed emails in the bottom");
}
}
?>
If I understand your question correctly, you're looking to never leave a page but rather have a div appear or disappear based off of a successful form submission. If so, it looks like you're going to have to use AJAX. Luckily, jQuery has this built right in! I'd suggest something like the following:
$.post("url.php", { option1: value1, option2: value2 }, function(data) {
if(data != '')
$('#theDiv').html("Success!");
});
For more information, read up on the documentation here.
Read and follow examples here: jQuery AJAX
You'll basically do something like this.
$.ajax({
url: /url/to/your/php,
data: dataObjectPosting
success: function(data){
//the data object will have your PHP response;
$('#divid').text('success message');
},
error: function(){
alert('failure');
}
});
Remember, success simply means HTTP 200, not necessarily that your PHP code ran successfully as you would see it.