Login change in to signup - forms

I have created a HTML5 registration form,is it possible for it to check the email address(inserted first) if it's already used to ask only for password(login) and if it's not to insert other fields needed for signup? using php,js or others.

<form id="signin_student" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
<input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
<input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
<label>Kelas</label>
<select name="class_id" class="input-block-level span5">
<option>Pilih Kelas</option>
<?php
$query = mysql_query("select * from class order by class_name ")or die(mysql_error());
while($row = mysql_fetch_array($query)){
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
?>
</select>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
<button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#signin_student").submit(function(e){
e.preventDefault();
var password = jQuery('#password').val();
var cpassword = jQuery('#cpassword').val();
if (password == cpassword){
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "student_signup.php",
data: formData,
success: function(html){
if(html=='true')
{
var delay = 2000;
setTimeout(function(){ window.location = 'siswa/index.php' }, delay);
}else if(html=='false'){
{ header: 'Data in DB is Not Found' });
}
}
});
}else
{
$.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
}
});
});
</script>
and file signup.php
<?php
mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$class_id = $_POST['class_id'];
$query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
$row = mysql_fetch_array($query);
$id = $row['student_id'];
$count = mysql_num_rows($query);
if ($count > 0){
mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
$_SESSION['id']=$id;
echo 'true';
}else{
echo 'false';
}
?>

Firstly, you could use this code to check when the user stops typing:
Run javascript function when user finishes typing instead of on key up?
Once that is finished, this SQL code may work to check if the email already exists:
SELECT EXISTS(SELECT email FROM email_table)
Then you can simply use a conditional statement to print whether the email exists.

Related

How to add a 'Send Message To' button on contact page?

I'm trying to add a "Send Message To" button on a contact form but I'm having trouble with the javascript/PHP. I'm using code I edited that came with the start bootstrap modern business theme, so far I have just added the $to = '$department', set the select tag ID as department and the value of option tags to the appropriate emails.
Not sure if any of that is correct.
HTML:
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Send Message To</label>
<select class="form-control" id="department">
<option value="sales#website.com">Sales</option>
<option value="support#website.com">Support</option>
</select>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-CMD" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
PHP:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$message = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = '$department';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Javascript
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
Im not quite sure about your questions, but if you're just trying to get the item from the department form, and send it to that email address, this is the code for that.
JS:
data: {
name: name,
email: email,
message: message,
department: document.getElementById('department').value
},
You must pass the value of the form to the PHP script. You originally had the $message var set to the message and then the next line would set that variable to the department. You need to keep them separate.
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$department = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = $department;
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Hope this works!

PDO prepaired statement UPDATE not working

I've been persistently trying to get this statement to update my db, but with no success. I have a form that is to allow user to update their username and email. What am I overlooking?
Here is my statement:
<?php require_once('config.php');
$id= $_SESSION['id'];//get user id you can use session also
if (isset($_POST['submit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$query = "UPDATE members SET username = :username ,email = :email WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':username',$username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
}
$query = "SELECT * FROM members WHERE id = $id"; //Get user info
$stmt = $db->prepare($query);
$stmt ->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
// output data of each row
foreach($result as $row){
$username = $row['username'];
$email = $row['email'];
}
}
?>
Here is my form:
<form role="form" class="cf-form floating-labels" method="post" action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>">
<fieldset>
<legend>My Account<br />
<img class="logo_contact" src="img/jobmiser_logo2.png" alt="jobmiser logo" />
</legend>
<div class="icon">
<label class="cf-label" for="username">Username</label>
<input class="user" type="text" name="username" id="username" value="<?php echo $username ?>" tabindex="2" required />
</div>
<div class="icon">
<label class="cf-label" for="email">Email</label>
<input class="email" type="email" name="email" id="email" value="<?php echo $email ?>" tabindex="3" required />
</div>
</fieldset>
<fieldset>
<div class="icon">
<input name="submit" type="submit" value="Update" />
</div>
</fieldset>
</form>
You need to bind the :id parameter in your update query:
// bind :id
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// You also need to execute it
$stmt ->execute();
In the second statement you should also bind the value id and not insert it directly into the string.
// BAD
$query = "SELECT * FROM members WHERE id = $id";
// GOOD
$query = "SELECT * FROM members WHERE id = :id"; //Get user info
$stmt = $db->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt ->execute();

PHPMailer and Ionic with Gmail

I'm attempting to create a contact form for my app using PHPMailer and Ionic with Gmail.
The page receives (Failed.) result message when it triggers the script but I never get the email from the form. Here is my code:
template.html
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
app.js
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed.';
$scope.result='bg-danger';
}
}
});
PHP
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('my#emailaddress.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mygmailusername#gmail.com";
$mail->Password = "passwordform";
$mail->setFrom('mygmailusername#gmail.com', 'Contact Form');
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
You need to initialize $scope.formData = {} so that it can hold the values you are expecting. Right now, its trying to bind values to a scope variable that is undefined.
Edit - It looks like you have no ng-click handler in your button to register the click to the submit. Please add this to your button. Additionally, $valid only works if your input values are enclosed in a .
template.html
<form name="myForm">
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default"
ng-disabled="myForm.$invalid || submitButtonDisabled == true"
ng-click=submit(formData)>Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
What this is doing is its registering the $scope.submit the button, and in the HTML you're passing in formData as a parameter. The now has a name and its required values are checked in ng-disabled of the button which refers to the same name and disables if the I've cleaned up your app.js so that you're getting the params correctly.
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage = '';
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(contactform), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
}
});

how to get the name of image in input , code igniter edit form

I am trying to edit a picture that I've already uploaded, so when Click on edit i cant not get the name of the image in the input. here is my code in controller:
It means I want to edit the details of an item but i don't want to edit the image of it.
controller
//method to edit category
public function edit_menu($id) {
if($this->isLogin()) {
//object/instance of menu
$menu_list = new Menu();
//calling method of , menu model
$menu_list->load($id);
//print_r($menu_list);
$menu_list_array = (array)$menu_list;
//object/instance of category
$category = new Category();
//calling method of category model
$category_list = $this->Category->get();
//creating an array to hold data
$category_form_options = array();
//iterate through loop
foreach ($category_list as $id => $category) {
$category_form_options[$id] = $category->category_name;
}
//creating an array to hold data for category and menu, to pass data to view
$data = array();
//category key of data array to hold category details
$data['category'] = $category_form_options[$menu_list_array['category_id']];;
//menu key of data array to hold menu details
$data['menu'] = $menu_list;
//CI built-in method to have three params, first is field id, second is human readable lable to show in case of error, rules include required, type.
$this->form_validation->set_rules(array(
array('field' => 'category_id','label' => 'Category', 'rules' => 'required',),
array('field' => 'type','label' => 'Type','rules' => 'required',),
array('field' => 'menu_name', 'label' => 'Menu Name', 'rules' => 'required',),
array('field' => 'description','label' => 'Description','rules' => 'required',),
));
if (empty($_FILES['avatar']['name'])){
$this->form_validation->set_rules('avatar', 'Avatar', 'required');
}
//CI method to error delimiters,
//https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#errordelimiters
$this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div>');
if (!$this->form_validation->run()) {
$datas['title'] = "";
$this->load->view('header', $datas);
//this will load data
$this->load->view('category_form_edit', array('category_form_options' => $category_form_options, 'data' =>$data, ));
$this->load->view('footer');
}
else {
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->do_upload('avatar');
$data_upload_files = $this->upload->data();
//record from global post variable to model fields.
$menu_data = array();
$menu_data['category_id'] = $menu_list->category_id = $this->input->post('category_id');
$menu_data['type'] = $menu_list->type = $this->input->post('type');
$menu_data['menu_name'] = $menu_list->menu_name = $this->input->post('menu_name');
$menu_data['description'] = $menu_list->description = $this->input->post('description');
$menu_data['per_gram'] = $menu_list->per_gram = $this->input->post('per_gram');
$menu_data['per_quantity'] = $menu_list->per_quantity = $this->input->post('per_quantity');
$menu_data['per_dozen'] = $menu_list->per_dozen = $this->input->post('per_dozen');
$menu_data['avatar'] = $menu_list->avatar = $data_upload_files['file_name'];
$menu_data['updated_by'] = $menu_list->updated_by = $_SESSION['user_id'];
$menu_data['updated_on'] = $menu_list->updated_on = date('Y-m-j H:i:s');
//update model
$id = $menu_list_array['menu_id'];
$where = array('menu_id' => $id);
$menu_list->update('menus', $menu_data, $where);
$this->load_menu();
}
}
}
view
<?php echo form_open_multipart('', 'fscontrol/edit_menu');?>
<!-- <form method="post"> -->
<div class="form-group">
<label for="category_id">Category Name</label>
<select name="category_id" class="form-control" >
<?php
foreach ($category_form_options as $category_id => $category_name) {
$selected = $data_array['category_id'] == $category_id ? 'selected' : '';
echo '<option ' . $selected. ' value="' . html_escape($category_id) . '">' . html_escape($category_name) . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="type">Type</label>
<input type="text" class="form-control" name="type" value="<?php echo $data_array['type']; ?>">
</div>
<div class="form-group">
<label for="menu_name">Menu Name</label>
<input type="text" class="form-control" name="menu_name" value="<?php echo $data_array['menu_name']; ?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" value="<?php echo $data_array['description']; ?>">
</div>
<div class="form-group">
<label for="per_gram">Per gram</label>
<input type="text" class="form-control" name="per_gram" value="<?php echo $data_array['per_gram']; ?>">
</div>
<div class="form-group">
<label for="per_quantity">Per quantity</label>
<input type="text" class="form-control" name="per_quantity" value="<?php echo $data_array['per_quantity']; ?>">
</div>
<div class="form-group">
<label for="per_dozen">Per dozen</label>
<input type="text" class="form-control" name="per_dozen" value="<?php echo $data_array['per_dozen']; ?>">
</div>
<div class="form-group">
<label for="avatar">Photo</label>
<input type="file" class="form-control" name="avatar" size="20" value="<?php echo $data_array['avatar']; ?>">
</div>
<div class="form-group">
<input type="hidden" name="menu_id" value="<?php echo $data_array['menu_id']; ?>">
<input type="submit" class="btn btn-default" value="Edit"/>
</div>
</form>
If you are using bootstrap template you will not get the image name. You'll see only:
no file chosen
So it is better to use:
<img src="">
, and display image as a thump nail.

registration script keeps showing errors when all fields are filled

Im having a little issue with my registration script.
I am trying to add rows into my mysql database.
This is my form verifier to make sure all fields are filled:
//Variables from the table
$user = $_POST['un'];
$pass = $_POST['pw'];
$rpass = $_POST['rpw'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($user);
$pass = mysqli_real_escape_string($pass);
$rpass = mysqli_real_escape_string($rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
and this is the form
<form action="register_proc.php" method="post">
<label for="un">Username</label>
<input type="text" name="un" id="un" placeholder="username"/>
<br/>
<label for="pw">Password</label>
<input type="password" name="pw" id="pw" placeholder="password"/>
<br/>
<label for="rpw">Repeat Password</label>
<input type="password" name="rpw" id="rpw" placeholder="repeat password"/>
<br/>
<input type="submit" name="submit" value="Complete Registration"><br>
<div style="float: left;">
Home
</div>
<div style="float: right;">
Login
</div>
</form>
I have no idea why it keeps outputting the else statment "Please fill in all the information!"
All of the $post variables have the correct names
thank you for the upcoming support.