php mail form on magento product page - javascript

I am trying to make a simple price match contact form on my product page in Magento. I have a separate php file but it doesn't seem to receive the commands from the view.phtml file.
this is the form code which is located inside /app/design/frontend/default/my_design/template/catalog/product/view.phtml
<div class="pricematcher">
<body class="body">
<div id="pricematch" style="display:none;">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="send_contact.php" id="form" method="post" name="form">
<img id="close" src="<?php echo $this->getSkinUrl(); ?>images/close.png" onclick="div_hide()"</img>
<h2 class="h2price">Price Match</h2>
<hr id="hrprice">
<input id="name" name="name" placeholder="Name" type="text">
<input id="email" name="email" placeholder="Email" type="text">
<input id="productname" name="productname" placeholder="<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->__(' PART #: ');?><?php echo $_helper->productAttribute($_product, nl2br($_product->getSku()), 'sku') ?>" type="text" readonly>
<input id="competitor" name="competitor" placeholder="Competitor Product Link" type="text">
<textarea id="msg" name="msg" placeholder="Message"></textarea>
Submit
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<!-- Display Popup Button -->
</body>
</div>
<img id="popup" src="<?php echo $this->getSkinUrl(); ?>images/price-match.png" onclick="div_show()"</img>
this is the javascript which makes the form pop up and display
// Validating Empty Field
function check_empty() {
if (document.getElementById('name').value == "" || document.getElementById('email').value == "" || document.getElementById('msg').value == "") {
alert("Fill All Fields !");
} else {
document.getElementById('form').submit();
alert("Thank You for submitting a Price Match inquiry");
}
}
//Function to Hide Price Match
function div_hide(){
document.getElementById('pricematch').style.display = "none";
}
//Function To Display Price Match
function div_show() {
document.getElementById('pricematch').style.display = "block";
}
this is the php file that the form action should send to send_contact.php file located in the same directory as view.phtml
<?php
$subject = "Price Match";
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
// Enter Your email Adress
$to = "myemail#email.com";
$body = "$message, $competitor, $product";
$send_contact = mail($to,$subject,$body, "From: " . $mail_from);
//Check if message sent
if ($send_contact){
echo "we recieved";
}
else {
echo "error";
}
?>
Every thing works when I make this in a seperate folder on my server and execute outside of magento.

You should put send_contact.php at magento's root directory.

I think you can create an action in ProductController.php,for example,postEmailAction, then in the postEmailAction,you can get the data from the form:
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
, flow the code:
`
$mail = Mage::getModel('core/email');
$mail->setToName('YourStore Admin');
$mail->setToEmail($toEmail);
$mail->setBody($body);
$mail->setSubject('YourStore: New Product Review');
$mail->setFromEmail('donotreply#yourstore.com');
$mail->setFromName("YourStore");
$mail->setType('html');
try {
$mail->send();
}
catch (Exception $e) {
Mage::logException($e);
}
`
the action url will be the product controller + the action name;
Hope this will help you.

Related

Run PHP after JS validation

I am doing email validation for admin registration using JavaScript and save the data to database using PHP. Supposedly, the registration is done only if the email is valid. But when the email evaluates to invalid, the PHP code still run. How do I do it so that when the email is invalid, the PHP won't run.
Below is the PHP code to save data to database:
<?php
include('connection.php');
if(isset($_POST['saveBtn']))
{
$name = $_POST['name'];
$ic = $_POST['ic'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$gender = $_POST['gender'];
$des = $_POST['des'];
$address = $_POST['address'];
// Check if data exist
$check = "SELECT * FROM admin WHERE admEmail = '".$email."' AND admPassword = '".$pass."'";
if(mysqli_num_rows(mysqli_query($connect,$check)) > 0)
{
?>
<script>
alert('This email and password already registered!');
</script>
<?php
}
else
{
$insert = "INSERT INTO admin (admName, admIC, admEmail, admPassword, admDOB, admContact, admGender, admDesignation, admAddress, admDateJoin) VALUES ('".$name."', '".$ic."', '".$email."', '".$pass."', '".$dob."', '".$contact."', '".$gender."', '".$des."', '".$address."', NOW())";
if(mysqli_query($connect, $insert))
{
?>
<script>
alert('Insertion Successful!');
window.close();
window.opener.location.reload();
</script>
<?php
}
else
{
?>
<script>
alert('Insertion Failed. Try Again!');
</script>
<?php
}
}
}
?>
Below is the JS:
function validateEmail() {
var email = document.addAdminForm.email.value;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (email.match(validRegex))
{
alert("Valid email address!");
return true;
}
else
{
document.getElementById("email_error").innerHTML = "Invalid email";
document.addAdminForm.email.focus();
return false;
}
}
Below is the partial HTML form:
<form class="w-100" name="addAdminForm" method="POST" onsubmit="validateEmail(this)" action="add_admin.php">
<div class="row">
<div class="col form-group">
<!-- <label for="email">Email</label> -->
<input type="text" class="form-control" name="email" placeholder="Email" required>
<span class="error email_error" id="email_error"></span>
</div>
<div class="float-right">
<input type="submit" class="btn button_primary" value="Save" name="saveBtn">
</div>
</form>
I expect PHP run when validation is true
add this:
onsubmit="return validateEmail(this)"
change your JS code to:
var validRegex = /^([a-zA-Z0-9_-])+#([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;

Need help on css display state using localStorage and jQuery

I am building a multi-page form and it has a lot of conditional statements. Some of which deal with the display of particular DIVs based upon the selection of some other DIVs. To make my question simple I have created another form that works similarly, but is very short.
The first input field asks the "First Name." After it is filled with characters, two fields for "Middle Name," and "Last Name" appear. Originally, these two fields have "inline-style" of "display:none;" and hence are not displayed until the jQuery function displays them. Once the user fills out the form and hits submit, PHP validations run on the server.
For our purpose, let's fill the first input field then followed by two new fields displayed by jQUery, leave other fields blank and hit "submit." Of course, the PHP validations fail and we are shown the refreshed version of the form with all the form data gone and most importantly for my usage, the CSS display state for the two input fields gone. Now, I know I could add php to keep the values on the input fields, but that still does not solve my problem of keeping the CSS display state of the "display:none;" DIVs.
I need help with restoring the form data on the first field followed by the display of the other two fields with their data. I sort of know how the localStorage works, but I could not make it work here.
I very much appreciate anyone giving this their time.
Once again, thank you very much.
Here goes the code:
<?php
$firstName = $middleName = $lastName = $email = $phone = $comment = $from = $name = $subject = $subject2 = $message2 = $headers = $headers2 = $result = $result2 = '';
$errors = array('firstName'=>'','middleName'=>'','lastName'=>'','email'=>'','phone'=>'','comment'=>' ');
if(isset($_POST['submit'])) { /**checks if the submit button is pressed or not. only executes below steps if the form is submitted.**/
//check first name input
if(empty($_POST['firstName'])){
$errors ['firstName'] = 'Please enter your First Name <br />';
} else {
$firstName = $_POST['firstName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $firstName)){
$errors ['firstName'] = 'Only letters are accepted <br />';
}
}
//check middle name input
if(empty($_POST['middleName'])){
$errors ['middleName'] = 'Please enter your Middle Name <br />';
} else {
$middleName = $_POST['middleName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $middleName)){
$errors ['middleName'] = 'Only letters are accepted <br />';
}
}
//check last name input
if(empty($_POST['lastName'])){
$errors ['lastName'] = 'Please enter your Last Name<br />';
} else {
$lastName = $_POST['lastName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $lastName)){
$errors ['lastName'] = 'Only letters are accepted <br />';
}
}
//check email input
if(empty($_POST['email'])){
$errors ['email'] = 'Please enter your E-mail Address <br />';
} else {
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors ['email'] = 'Email must be a valid email address <br />';
}
}
//check phone number input
if(empty($_POST['phone'])){
$errors ['phone'] ='Please enter your Phone Number<br />';
} else {
$phone = $_POST['phone'];
if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}+$/', $phone)){
$errors ['phone'] = 'Only numbers separated by dashes are allowed <br />';
}
}
//check comment input
if(empty($_POST['comment'])){
$errors ['comment'] = 'Please provide your feedback <br />';
} else {
$comment = $_POST['comment'];
if(!preg_match('/^[\w,.!?\s]+$/',$comment)){
$errors ['comment'] = 'Only letters, commas, and periods are allowed <br />';
}
}
if(array_filter($errors)){
//let the user fill out form again
echo '<script type = "text/javascript">alert("Submission failed due to error in the input field. Please fill all the input fields and submit the form again. Thank you!") </script>';
} else {
header('location:thank-you');
}
//php to send message to both client and the owner
$mailto = "a#b.com"; //web owners email addresss
$from = $_POST['email']; //senders email address
$name = $_POST['firstName']; //user's name
$subject = "You received a message";
$subject2 = "Your message has been submitted successfully"; //message title for client email
$comment = "Client Name: ". $firstName. "wrote the following message". "\n\n". $_POST ['comment'];
$message = "Contact Form". "\n\n".
"From - ". $firstName. " ". $middleName. " ". $lastName. "\n\n".
"Email Id - ". $from. "\n\n". "Phone Number - ". $phone. "\n\n".
"FeedBack :". "\n\n". $_POST ['comment'];
$message2 = "Dear ". $firstName. ",". "\n\n". "Thank you for contacting us!";
$headers = "From: ". $from; //user entered email address
$headers2 = "From: ". $mailto; // this will receive to client
$result = mail($mailto, $subject, $message, $headers); //send email to the website owner
$result2 = mail($from, $subject2, $message2, $headers2); //send email to the user or form submitter
} // end of POST check
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1 /jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1 /jquery.validate.min.js"></script>
<link rel="stylesheet"href="https://fonts.googleapis.com/css?family=Muli">
<title>Contact Form</title>
<style>
label{display:block;}
.container{display:flex; flex-direction: row; flex-wrap: wrap;
margin-top:10rem; justify-content: left; margin-left:3rem;}
.flexItems{
margin-right:1rem; margin-bottom:2rem;
}
#submit{
margin-left:3rem;
width:20em;
}
.comment{
margin-left:3rem;
}
.red-text{
color:red;
}
</style>
<script>
$(document).ready(function() {
$("#fName").change(function(){
if($(this).val() != "" ){
$("#mName1").css("display","block");
$("#lName1").css("display","block");
} else {
$("#mName1").css("display","none");
$("#lName1").css("display","none");
}
})
})
</script>
</head>
<body>
<form action="" method="POST" auto_complete = "off" id = "form">
<div class = "container">
<div class= "flexItems">
<label>First Name</label>
<input id = "fName" type = "text" name = "firstName" >
<div class = "red-text"><?php echo $errors['firstName']; ?></div>
</div>
<div class= "flexItems" id = "mName1" style = "display:none;">
<label>Middle Name</label>
<input id = "mName" type = "text" name = "middleName" >
<div class = "red-text"><?php echo $errors ['middleName']; ?></div>
</div>
<div class= "flexItems" id = "lName1"style = "display:none;" >
<label>Last Name</label>
<input id = "lName" type = "text" name = "lastName" >
<div class = "red-text"><?php echo $errors ['lastName']; ?></div>
</div>
<div class= "flexItems">
<label>Email Address</label>
<input id = "eAddress" type = "email" name = "email" >
<div class = "red-text"><?php echo $errors ['email']; ?></div>
</div>
<div class= "flexItems">
<label>Phone Number</label>
<input id = "pNumber" type = "tel" name = "phone" >
<div class = "red-text"><?php echo $errors ['phone']; ?></div>
</div>
<div class= "comment">
<label>Comment</label>
<textarea rows = "6" cols ="60" name = "comment" placeholder = "Please leave a comment. Thank you!" ></textarea>
<div class = "red-text"><?php echo $errors ['comment']; ?></div>
</div>
<div id = "submit">
<button type= "submit" id = "submit" value = "Send my message ASAP" name = "submit">Submit</button>
</div>
</div>
</form>
</body>
</html>
I know I could add php to keep the values on the input fields, but that still does not solve my problem of keeping the CSS display state of the "display:none;" DIVs.
I would recommend using PHP to fill in the form values after submission and solve showing/hiding elements with JavaScript.
For example PHP would look like this: (using htmlspecialchars to escape quotes and other special characters and reading data directly from POST request)
<input
id="fName"
type="text"
name="firstName"
value="<?php echo htmlspecialchars($_POST['firstName']); ?>"
>
There is also possibility to keep values in localStorage if you prefer. I was able to find this jQuery plugin which does that - Persist.js.
Second task is to show/hide corresponding fields.
First of all, try to think about user experience when new fields appear or disappear. Maybe it's better to keep all the fields on the screen, disable/enable them etc. I can think of one case when fields can be hidden and it is when several options are presented for selection and the last option is 'other (please specify)' which allows to input custom response. I'll be adding this use case to the prototype bellow.
I'd recommend to create a single updateVisibility function that will show/hide needed blocks. It should be called when page loads (with data filled in with PHP) and when any form field is modified:
function updateVisibility() {
// fname - show/hide mName/lName
if ($("#fName").val() !== "") { // always use === or !== in JS for comparison
$("#mName1").css("display", "block");
$("#lName1").css("display", "block");
} else {
// hide inputs and clear values
$("#mName1").val('').css("display", "none");
$("#lName1").val('').css("display", "none");
}
}
$(document).ready(function () {
// call when page is loaded
updateVisibility()
// and every time any field changes in the form
$("#form").change(updateVisibility)
});
P.S. I've noticed and fixed several errors in HTML:
tag attributes should not contain spaces - id="fName" (not id = "fName")
label tag requires for attribute - <label for="fName"> (where fName is an ID of some other element to which label will point)
Please find prototype code bellow (only HTML part, StackOverflow does not run PHP). Programming language field is an example of how I think user experience should be, I've kept Middle name/Last name fields functionality like in your question.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli">
<title>Contact Form</title>
<style>
label {
display: block;
}
label.radio-label {
display: inline;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-top: 10rem;
justify-content: left;
margin-left: 3rem;
}
.flexItems {
margin-right: 1rem;
margin-bottom: 2rem;
}
#submit {
margin-left: 3rem;
width: 20em;
}
.comment {
margin-left: 3rem;
}
.red-text {
color: red;
}
</style>
<script>
function updateVisibility() {
// fname - show/hide mName/lName
if ($("#fName").val() !== "") {
$("#mName1").css("display", "block");
$("#lName1").css("display", "block");
} else {
$("#mName1").val('').css("display", "none");
$("#lName1").val('').css("display", "none");
}
// language other - show/hide language-other-block
if ($('input[name="language"][type="radio"]:checked').val() === 'other') {
$('#language-other-block').css('display', 'block');
} else {
$('#language-other-block').css('display', 'none');
$('#language-other-input').val('');
}
}
$(document).ready(function () {
// call when page is loaded
updateVisibility()
// and every time any field changes in the form
$("#form").change(updateVisibility)
})
</script>
</head>
<body>
<form action="" method="POST" auto_complete="off" id="form">
<div class="container">
<div class="flexItems">
<label for="fName">First Name</label>
<input id="fName" type="text" name="firstName">
<div class="red-text">
<?php echo $errors['firstName']; ?>
</div>
</div>
<div class="flexItems" id="mName1" style="display:none;">
<label for="mName">Middle Name</label>
<input id="mName" type="text" name="middleName">
<div class="red-text">
<?php echo $errors ['middleName']; ?>
</div>
</div>
<div class="flexItems" id="lName1" style="display:none;">
<label for="lName">Last Name</label>
<input id="lName" type="text" name="lastName">
<div class="red-text">
<?php echo $errors ['lastName']; ?>
</div>
</div>
<div class="flexItems">
<label for="eAddress">Email Address</label>
<input id="eAddress" type="email" name="email">
<div class="red-text">
<?php echo $errors ['email']; ?>
</div>
</div>
<div class="flexItems">
<label for="pNumber">Phone Number</label>
<input id="pNumber" type="tel" name="phone">
<div class="red-text">
<?php echo $errors ['phone']; ?>
</div>
</div>
<div class="flexItems">
<div>Programming language</div>
<div><input type="radio" name="language" value="js" id="language-js"><label class="radio-label"
for="language-js">JavaScript</label></div>
<div><input type="radio" name="language" value="php" id="language-php"><label class="radio-label"
for="language-php">PHP</label></div>
<div><input type="radio" name="language" value="other" id="language-other"><label class="radio-label"
for="language-other">other</label></div>
<div id="language-other-block" style="display: none;">
<label class="radio-label" for="">Please specify: </label>
<input type="text" name="language-other" id="language-other-input">
</div>
<div class="red-text">
<?php echo $errors ['language']; ?>
</div>
</div>
<div class="comment">
<label for="comment">Comment</label>
<textarea rows="6" cols="60" id="comment" name="comment"
placeholder="Please leave a comment. Thank you!"></textarea>
<div class="red-text">
<?php echo $errors ['comment']; ?>
</div>
</div>
<div id="submit">
<button type="submit" id="submit" value="Send my message ASAP" name="submit">Submit</button>
</div>
</div>
</form>
</body>
</html>

My page does not stay the same page when I click the option submit

I'm a little new here. I tried to make my website on my own and although it is almost finished, I can not solve the problem of sending information in my contact form.
The page is this: ramproducciones.pe (it's in Spanish)
If they go towards the end they find the contact form, even if they fill the data correctly, the email is sent but the next thing is that a blank page is given. What I want is that you get a message that says Thank you! Your message has been sent but I do not know how to do it. I have tried to copy many codes and I currently have this:
<!-- contacto-->
<section class="contact" id="contact">
<h1>Contacto</h1>
<hr/>
<div class="content">
<div class="form">
<form method="post" action="mail.php" name="contact">
<div class="column">NOMBRE<br/><br/>
<input name="name" id="name" value="" />
</div>
<div class="column-2">E-MAIL<br/><br/>
<input name="email" id="email" value="" />
</div>
<div class="column-3">MENSAJE<br/><br/>
<textarea id="message" name="message" ></textarea>
</div>
<div class="button">
<span><input class="submit" id="submit" name="submit" type="submit" value="ENVIAR"></span>
</div>
<div id="dialog-message" title="Thank You">
<p>¡Gracias! Tu mensaje ha sido enviado, te responderemos lo antes posible.</p>
</div>
</form>
</div>
<div class="contact-text">
No dudes en solicitarnos información.<br/><br/>
<strong>RAM Producciones</strong><br/><br/>
e-mail: <strong>info#ramproducciones.com</strong>
<br/><br/>
<img src=img/social/Facebook.png />
<img src=img/social/Vimeo.png />
<img src=img/social/Behance.png />
<img src=img/social/Instagram.png />
<img src=img/social/Youtube.png />
</div>
</div>
</section>
AND THE PHP is
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Solo ingresa letras y espacios.";
}
}
if (empty($_POST["email"])) {
$email_error = "Tu E-mail es necesario";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Formato de E-mail inválido";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'info#ramproducciones.pe';
$subject = 'Mail vía RAMPRODUCCIONES.PE';
if (mail($to, $subject, $message)){
$success = "¡Gracias! Tu mensaje ha sido enviado, te responderemos lo antes posible.";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
However I still can not solve the problem.
It's your action. You're sending your page to another page called mail.php. Set the action to reload your current page when the form is submitted.
Try using
<form id='form' method='post' action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>'>
as an attribute in your form
In the top of your page where you run your code for successful form submission, hide the form then display your message.
echo "<style>#form{display:none}</style>";
echo "<p>Thank you for submitting</p>";
There are a lot of possibilities in your case. Clearshot66 has introduced one.
Another possibility would be to keep your mail.php page and after the sending of the e-mail, you could create a logic to send the user back to your main page and show him a message. This could be done as I show you below:
mail.php
header("Location: your_main_page.php?showMessage=1");
exit;
your_main_page.php
<?php
if ($_GET["showMessage"] == 1) {
echo "Thanks for your contact.";
}
?>
The above code should be put in the beggining of your main_page.php
This is another IDEA.
The best good practice is to send the form using some ajax request and handle the return of this request, but this is a little bit more sofisticated than the options that we pointed to you.
As #clearshot66 said, you are redirecting to mail.php. I understand, that the php page you mean is this file.
What Fredi -ii- saw, you forgot to echo $success.
Blank page happens, because there is no output.
Hope I helped.

I can't create a sign up form properly

I have the following box that contains a sign upform:
<!-- sign up form -->
<div id="cd-signup">
<form class="cd-form" action = "signup.php" > <?php echo "$error" ?>
<p class="fieldset">
<label class="image-replace cd-username" for="signup-username">Username</label>
<input class="full-width has-padding has-border" id="signup-username" type="text" placeholder="Username" name = "user" <?php echo "value='$user'"?>>
</p>
<p class="fieldset">
<label class="image-replace cd-password" for="signup-password">Password</label>
<input name = "pass" class="full-width has-padding has-border" <?php echo "value='$pass'" ?> id="signup-password" type="text" placeholder="Password">
<!-- <span class="cd-error-message">Password must be at least 6 characters long</span> -->
</p>
<p class="fieldset">
<input class="full-width has-padding" type="submit" value="Create account">
</p>
</form>
<!-- more text here -->
<span class="section-nav">
<ul>
<li><a id="signup" class="cd-signup" href="#0">Get Started</a></li>
<li><a id="learnmore" class="cd-learnmore" href="#section2">Learn More</a></li>
</ul>
</span>
<span class="section-nav">
<ul>
<li><a id="signup" class="cd-signup" href="#0">Get Started</a></li>
</ul>
These were implemented as a button shape.
I included at the head of my html file (index.php) the following php code:
<?php
require_once 'functions.php';
require_once 'signup.php';
$userstr = '';
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
$loggedin = TRUE;
$userstr = " ($user)";
}
else $loggedin = FALSE;
if ($loggedin) {
header(home.php);
}
else {
?>
signup.php:
session_start();
<?php
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = "Not all fields were entered<br><br>";
else
{
$result = queryMysql("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
$error = "That username already exists<br><br>";
else
{
queryMysql("INSERT INTO members VALUES('$user', '$pass')");
die("<h4>Account created</h4>Please Log in.<br><br>");
}
}
}
?>
functions.php:
<?php
$dbhost = 'localhost'; // Unlikely to require changing
$dbname = 'socialmedia'; // Modify these...
$dbuser = 'root'; // ...variables according
$dbpass = 'mysql'; // ...to your installation
$appname = "Social Media"; // ...and preference
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
function queryMysql($query)
{
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}
function destroySession()
{
$_SESSION=array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time()-2592000, '/');
session_destroy();
}
function sanitizeString($var)
{
global $connection;
$var = strip_tags($var);
$var = htmlentities($var);
$var = stripslashes($var);
return $connection->real_escape_string($var);
}
function showProfile($user)
{
if (file_exists("$user.jpg"))
echo "<img src='$user.jpg' style='float:left;'>";
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if ($result->num_rows)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo stripslashes($row['text']) . "<br style='clear:left;'><br>";
}
}
?>
The code works perfectly from where I got it (source: Learn Php, MySql, & Javascript), so I decided to apply it to me own website.
However, When I click on the create account button, nothing happens. The database is correctly set along with the appropriate tables (tested on original code) along with the proper Ajax Requests.
I think the problem is somewhere in index.php, maybe something I missed ?
Thank you for your help ! :)
EDIT:
here is the javascript of the button implementation
jQuery(document).ready(function ($) {
var formModal = $('.cd-user-modal'),
formSignup = formModal.find('#cd-signup'),
tabSignup = formModalTab.children('li').eq(1).children('a'),
,
backToLoginLink = formForgotPassword.find('.cd-form-bottom-message a'),
mainNav = $('.main-nav'),
sectionNav = $(".section-nav");
//open modal
mainNav.on('click', function (event) {
$(event.target).is(mainNav) && mainNav.children('ul').toggleClass('is-visible');
});
//open sign-up form
sectionNav.on('click', '.cd-signup', signup_selected);
//open login-form form
mainNav.on('click', '.cd-signin', login_selected);
//close modal
formModal.on('click', function (event) {
if ($(event.target).is(formModal) || $(event.target).is('.cd-close-form')) {
formModal.removeClass('is-visible');
}
});
//close modal when clicking the esc keyboard button
$(document).keyup(function (event) {
if (event.which == '27') {
formModal.removeClass('is-visible');
}
});
//switch from a tab to another
formModalTab.on('click', function (event) {
event.preventDefault();
($(event.target).is(tabLogin)) ? login_selected() : signup_selected();
});
function signup_selected() {
mainNav.children('ul').removeClass('is-visible');
formModal.addClass('is-visible');
formLogin.removeClass('is-selected');
formSignup.addClass('is-selected');
formForgotPassword.removeClass('is-selected');
tabLogin.removeClass('selected');
tabSignup.addClass('selected');
}
Take a look at this line:
<p class="fieldset">
<input class="full-width has-padding" type="submit" value="Create account">
</p>
Your submit button should have a name of user.
<p class="fieldset">
<input class="full-width has-padding" name="user" type="submit" value="Create account">
</p>

How to get a msgbox?

I am creating a simple enquiry form with upload option.
If I click submit button it goes to another page and displays success message but it should come in the same page as a message box. What should I do?
Here is my Html code:
<ul>
<li><span>Name</span>
<input name="name" type="text" size="25" class="text1" />
</li>
<li><span>Contact</span>
<input name="contact" type="text" size="25" class="text2" />
</li>
<li><span>E-mail</span>
<input name="email" type="text" size="25" class="text3" />
</li>
<li><span>Subject</span>
<input name="subject" type="text" size="25" class="text4" />
</li>
<li><span>Message</span>
<textarea name="message" size="250" class="text5"></textarea>
</li>
</ul>
<label for="upload"></label>
<div class="x">
<input type="file" name="upload" id="file" class="button">
</div>
<div class="x1">
<input type="submit" name="submit" value="Submit" class="button" />
</div>
And this is my PHP code for uploading and inserting:
<?php
$target = "upload/";
$target = $target . basename($_FILES['upload']['name']);
$ok = 1;
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
echo "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
<?php
include ("conn.php");
if (isset($_POST['submit']))
{
$sql="insert into cform (name,contact,email,subject,message,upload)values('".$_POST['name']."','".$_POST['contact']."','".$_ POST['email']."','".$_POST['subject']."','".$_POST['message']."','$target')";
$result=mysql_query($sql);
if (!$result)
{
echo "could not enter data";
}
else
{
echo "successfuly entered";
}
}
?>
This PHP page has to run in background and when I click the submit button a message box should display success.
Edit the echo portion of the page as
second page
$rspnse = "";
if(!$result){
$rspnse = "Error";
}
else{
$rspnse = "Success";
}
header('Location: previous_page.php?response='.$rspnse);
Replace the previous_page.php with your original url of the first page
first page
<?php
if(isset($_GET['response'])){
?>
<script>
alert('<?php echo $_GET['response'] ?>');
</script>
<?php
}
?>
Hope this helps...
if(! $result) {
$msg = "could not enter data";
}else{
$msg = "successfuly entered";
}
header('Location: http://www.example.com/form.php?message=$msg');
//Redirect to form page with set message.
add script in form page to display message
if(isset($_GET['message'])){
print $_GET['message'];
}
This solution for as per your code
And another option is using ajax.

Categories

Resources