comment from comment box is overriding, not posting [duplicate] - javascript

This question already has answers here:
Create or write/append in text file
(7 answers)
Closed 5 years ago.
when I hit the post button, comment is posting on the page. If I hit it again, it overriding the previous comment. can someone please clarify this? And I'm running java script to display the date. It is showing all the time without any comments also. How can I modify that too?
Thanks in advance!
<h3 id="reply-title" class="comment-reply-title">Leave a Reply </h3>
<form action="" method="post">
<p class="comment-notes"><span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span></p>
<p class="comment-form-comment"><label for="comment">Comment</label> <textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" aria-required="true" required="required"></textarea></p>
<p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input id="author" name="author" type="text" value="" size="30" maxlength="245" aria-required="true" required="required"></p>
<p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input id="email" name="email" type="email" value="" size="30" maxlength="100" aria-describedby="email-notes" aria-required="true" required="required"></p>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"></p>
<div>
<?php
if($_POST) {
$name = $_POST['author'];
$comment = $_POST['comment'];
$email = $_POST['email'];
#echo $name . $comment . $email;
$handle = fopen("comments/get-more-twitter-followers.html", "a");
fwrite($handle, "\n".$name."\n".$comment."\n". $email. "\n");
fclose($handle);
}
?>
<?php
if($_POST) {
$email = $_POST['email'];
$useremail = fopen("useremail.html", "a");
fwrite($useremail, "\n".$email. "\n");
fclose($useremail);
}
?>
</div>
<div>
<div>
<p><strong><h4><u>Comments:</u></h4></strong></p>
</div>
<div>
<div>
<strong><?php
$name = $_POST['author'];
echo $name; ?> </strong> <small><script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write("/")
document.write(d.getMonth() + 1)
document.write("/")
document.write(d.getFullYear())
</script>
</small>
</div>
<div>
<p>
<?php
$comment = $_POST['comment'];
echo "\n".$comment."\n"."<hr>";
?>
</p>
</div>
</div>
</div>

Whay do you mean with; 'Your email address will not be published.' You write all 'mail addresses' to a plaintext file for crying out loud. DONT PUT THIS ONLINE.

You're not reading the file back to paint the comments, you are just using the POST data that came in:
<div>
<strong><?php
$name = $_POST['author'];
echo $name; ?> </strong> <small><script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write("/")
document.write(d.getMonth() + 1)
document.write("/")
document.write(d.getFullYear())
</script>
</small>
</div>
<div>
<p><?php
$comment = $_POST['comment'];
echo "\n".$comment."\n"."<hr>";
?></p></div>
</div></div>
</div>
$_POST in PHP refers to the body of the POST request that the script is responding to.
You need to replace that with functionality that does three things:
Reads from the file.
Splits the records into different entries with an author and comment.
Iterates over those entries and paints a separate div for each record.
Another gotcha: Your code is printing the current date as the date of the comment. If you are not storing the date of the comments, you probably shouldn't show the date.

<?php
$comment = $_POST['comment'];
$name = $_POST['author'];
$data_post->name = $name;
$data_post->comment = $comment;
if(isset($name, $comment)){
header('Content-type: application/json');
echo(json_encode($data_post));
return;
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$("document").ready(function(){
$("#comment").on("submit", function(e){
var comment = $('#comment');
e.preventDefault();
$.ajax({
method: "POST",
url: "index.php", // your php file name
data: comment.serialize(),
success: function (data) {
var d = new Date();
var data_comment = "<div><small>"+d.getDate()+"/"+(d.getMonth() + 1)+"/"+d.getFullYear()+"</small></div><strong>"+data.name+"</strong><p>"+data.comment+"</p>"
$("#list_comment").append(data_comment);
comment[0].reset();
console.log(data.name);
},
error: function (data) {
},
})
});
});
</script>
</head>
<body>
<h3 id="reply-title" class="comment-reply-title">Leave a Reply </h3>
<form action="" method="post" id="comment">
<p class="comment-notes"><span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span></p>
<p class="comment-form-comment"><label for="comment">Comment</label> <textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" aria-required="true" required="required"></textarea></p>
<p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input id="author" name="author" type="text" value="" size="30" maxlength="245" aria-required="true" required="required"></p>
<p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input id="email" name="email" type="email" value="" size="30" maxlength="100" aria-describedby="email-notes" aria-required="true" required="required"></p>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"></p>
</form>
<div>
<div>
<p><strong><h4><u>Comments:</u></h4></strong></p>
</div>
<div id="list_comment">
<div>
</div>
</body>
</html>
don't forget to change url in ajax post with your php filename (line 26)

Related

Display custom error message in login

I want to implement a simple login with PHP. But, also I want to customize the error message when the login is incorrect, for example display a error message in red color.
Login.php
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result = mysql_query($sql, $con);
if ($fila = mysql_fetch_array($result)) {
header('Location: menuclient.php');
} else {
/* How customize my message error */
}
?>
In the Login.php file, when the username or password are not correct, i want to display, for example, in id=error : "Login Incorrect" in red.
I dont know if I can do it with php.
Thanks for your help.
You can use session. Try following way.
Login.php
<?php
session_start();
if($_SESSON['error']): ?>
<span>Error : <?php echo $_SESSION['errorMsg']; ?></span>
<?php endif; ?>
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
session_start();
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result=mysql_query($sql,$con);
if( $fila=mysql_fetch_array($result) )
{
header('Location: menuclient.php');
}
else {
$_SESSION['errorMsg'] = "Wrong username or Password";
$_SESSION['error'] = true;
header('Location: Login.php');
}
?>

How to Save the optins in a text file without disturbing the email notif

I am using a custom optin page with a form , I want to tweak it a little bit,
I want to save all the optins on a txt file on the server without
disturbing the other functions of the form.
2nd thing I want is to show a custom Page after the optin form is
submitted.
Currently the form works like this
USER SUBMITS > PAGE REFRESHES FOR HIM > I GET AN EMAIL WITH THE SUBMITTED DATA.
Here is the form code
<div class="form fix ">
<p class="form-text">Fill This Out and See Your <br>Timeshare Report</p>
<form name="contactform" action="mail-script.php" method="POST">
<label for="fname">First Name:
<input type="text" name="fname" id="fname" />
</label><br>
<label for="lname">Last Name:
<input type="text" name="lname" id="lname" />
</label><br>
<label for="email">Email Address:
<input type="text" name="email" id="email" />
</label><br>
<label for="phone">Phone Number:
<input type="text" name="phone" id="phone" />
</label><br>
<label for="phone">Alternate Phone:
<input type="text" name="phone" id="aphone" />
</label><br>
<label for="resort">Resort Name:
<input type="text" name="resort" id="resort" />
</label><br>
<label for="amount">Amount Owed? $:
<input type="number" name="amount" id="amount" />
<p style="font-size: 12px !important;margin-top: -14px;padding-right: 30px;text-align:right;">
If Paid Off Leave Zero, Else Put Amount</p>
</label><br>
<div class="checkbox">
<div class="check-text fix">
<p>I'm Considering To</p>
</div>
<div class="check-one fix">
<input type="checkbox" name="call" id="" value="sell"/> Sell It <br>
<input type="checkbox" name="call" id="" value="buy"/> Buy It <br>
<input type="checkbox" name="call" id="" value="rent "/> Rent It
</div>
<div class="check-two fix">
<input type="checkbox" name="call" id="" value="cancel"/> Cancel Mortgage <br>
<input type="checkbox" name="call" id="" value="ownership"/> End Ownership <br>
<input type="checkbox" name="call" id="" value="give"/> Give It Back
</div>
</div>
<p class="captcha">
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input id="submit" type="submit" value="" />
<p class="submit-text">Ensure all fields are completed and correct, allowing you more benefits, while preventing abuse of our data.</p>
</form>
</div>
</div>
This is the mail script which sends me the email
<?php
/* Set e-mail recipient */
$myemail = "**MYEMAIL**";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$lname = check_input($_POST['lname'], "Enter your last name");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$resort = check_input($_POST['resort']);
$amount = check_input($_POST['amount']);
$call = check_input($_POST['call']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
First Name : $fname
Last Name : $lname
E-mail: $email
Phone : $phone
Resort: $resort
Amount: $amount
Call : $call
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: index.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
if (strtolower($_POST['code']) != 'mycode') {die('Wrong access code');}
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
Here is the online url of the page http://timesharesgroup.com/sell/index.html
you can add this code to your script after all the validation is done:
$text = "$fname\n$lname\n$email\n$phone\n$resort\n$amount\n$call\n\n";
file_put_contents('file.txt', $text, FILE_APPEND);
OR even better csv file:
$fields = array($fname,$lname,$email,$phone,$resort,$amount,$call);
$fp = fopen('file.csv', 'a');
fputcsv($fp, $fields);
fclose($fp);

can't post the data from form on a pop-up?

i would like to made a pop-up window for my login and signup sites. but there's a problem with this code, can't post the data from the form and the submit button didn't work when clicked. someone help me please. thanks.
here it is the index.html with the pop-up:
<div class="popup">
<h2>Welcome Guest!</h2>
<form id="formlogin" name="formlogin" method="POST" action="login_proses.php" enctype="multipart/form-data" autocomplete="on">
<p>Please enter your login and password here</p>
<p>
<label for="username">Login</label>
<input type="text" id="username" name="username" value="" required />
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password" value="" required/>
</p>
<p>
<input type="submit" value="Log In" onclick="popupUploadForm()">
</p>
</form>
<a class="close" href="#close"></a>
</div>
<script>
function popupUploadForm(){
var newWindow = window.location.href='login_proses.php';
}
</script>
and here it is login_proses.php that pick the data form, but it's always failed, and always go into index.html as else condition.
<?php
session_start();
include "connect.php";
if (isset($_POST["username"])){
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql=mysql_query("select * from member where username='$username'");
if ($sql && mysql_num_rows($sql)>0){
$result=mysql_fetch_array($sql);
if($password == $result['password']){
$_SESSION['username']=$username;
echo "<script type='text/javascript'>alert('Selamat Datang $username');
window.location.href='member.php';</script>";
}
else{
echo "<script type='text/javascript'>alert('Password salah, silahkan coba lagi');history.go(-1)</script>" ;
}
}
else{
echo "<script type='text/javascript'>alert('Username tidak ada dalam database');history.go(-1)</script>" ;
}
} else {
header("location:index.html");
} ?>

php ajax one page contact form

i am working on one page ajax contactform . I want to send an email with PHP without leaving my page and now i'm completely lost. I have no idea why its not working
i'll show you my contact form. thank you for help in advance. Here is the form ..
html code
<article class="panel" style="background:url(img/cover/bg_panel_3.jpg); background-size:cover;" full-screen>
<div style="padding-top:80px;">
<div class="row text-center centered">
<div id="contact-form">
<form id="contact-us" action="contact.php" method="post">
<ul>
<li class="field" id="check-1">
<input class="input txt requiredField wide alpha-only" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" placeholder="Name" onBlur="check(this.value)" />
</li>
<li class="field" id="check-2">
<input class="input wide mail-only txt requiredField email" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" placeholder="Email" />
</li>
<li class="field" id="check-3">
<input class="input wide hack-check sub-check requiredField" name="subj" type="text" placeholder="Subject" value="<?php if(isset($_POST['subj'])) echo $_POST['subj'];?>" />
</li>
<li class="field" id="check-4">
<input class="input wide num-only requiredField" name="num" type="text" placeholder="Number" value="<?php if(isset($_POST['num'])) echo $_POST['num'];?>" />
</li>
<li class="field" id="check-5">
<textarea class="input textarea wide hack-check msg-check txtarea requiredField" name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:">
<?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?>
</textarea>
</li>
</ul>
<div class="medium primary btn pretty-btn">
<input name="submit" class="subbutton" type="submit" value="Send" />
</div>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
<!-- End #contact -->
</div>
</div>
</div>
</article>
**js code **
$(document).ready(function() {
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
});
if(!hasError) {
var formInput = $(this).serialize();
alert(formInput);
$.post("contact-us.php",formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p class="tick fg-white sans"><strong>Thanks!</strong> Your email has been delivered. !</p>' );
});
});
}
return false;
});
});
PHP Code
//If the form is submitted
if(isset($_POST['submitted'])) {
$name = trim($_POST['contactName']);
$email = trim($_POST['email']);
$num = trim($_POST['num']);
$subject = trim($_POST['subj']);
$comments = trim($_POST['comments']);
$formcontent=" From : $name \n Email : $email \n Subject : $subj \n Phone number : $number \n \n Message : $message";
$recipient = "example#mail.com";
$subject = "Contact Form Query Received";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error encountered! Please try again or write directly to the mentioned email address.");
// set our boolean completion value to TRUE
$emailSent = true;
}
I suspect your problem is this extra }); in your code which is stopping the $.post(...) call from even being called. A quick lint of your JS shows this up, as does careful reading.
var hasError = false;
======> }); <====== remove this extra stuff.
if(!hasError) {

How to return to the previous page after a submit form with php?

I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>

Categories

Resources