How could I replace a form with already inserted text after unsuccesfull finding in database? - javascript

I have the code in Participate.php file which has a form:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
After unsucessful submit (I check if inserted mail already exist in database) and if no exist I want to refill value for form. This is the input.php code:
<?php
$name = $_POST['txtName'];
$mail = $_POST['txtEmail'];
$description = $_POST['txtDescription'];
$connect = new PDO("mysql:host=4*****3;dbname=3*****b", "3***b", "****");
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$q=$connect->prepare("SELECT mail FROM konkurs WHERE mail LIKE (?)");
$q->bindValue(1, $mail);
$q->execute();
$row_cnt = $q->rowCount();
if($row_cnt == 0){
$query = $connect->prepare("insert into konkurs(name,mail,description)
values(?, ?, ?)");
$query->bindValue(1, $name);
$query->bindValue(2, $mail);
$query->bindValue(3, $description);
try {
$query->execute();
echo ("<script LANGUAGE='JavaScript'>
window.alert('Sent.');
window.location.href='index.html';
</script>");
exit;
} catch (PDOException $e) {
die($e->getMessage());
}
} else {
echo ("<script LANGUAGE='JavaScript'>
window.alert('This mail already exist.');
window.location.href='Participate.php';
document.getElementById('txtName').value = 'nothing';
</script>");
}
?>
The thing is it's redirecting to Participate.php after unsuccesfull sumbition. But it doesn't refill the form.

First of all, you must change your HTML to include the id attribute, for example:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" id="txtName" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" id="txtEmail" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
Then, you must move your logic to the same file as the form container (here Participate.php), and remove the redirection for failures. Otherwise, you'll get no visible results, as the redirection would prevent further JavaScript code from running.
// Updated to prevent syntax errors with multiline strings
echo "<script>"
. "window.alert('This mail already exist.');"
. "document.getElementById('txtName').value = 'nothing';"
. "</script>";

Related

Php javascript conflict in wordpress template file

I have built a contact form for my wordpress site. Four fields are there - name, email, subject, message. For logged in users I want their name and email to be auto-filled in their respective fields in the form and those name, email fields will be disabled for them to edit. And for non-logged in users they will put name, email fields manually. I have put this code in the page template file -
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
if ( 0 != $current_user->ID ) {
echo '<script type="text/javascript">
document.getElementById("curUserName").value = "'.$user_name.'";
document.getElementById("curUserName").disabled = "disabled";
document.getElementById("curUserEmail").value = "'.$user_email.'";
document.getElementById("curUserEmail").disabled = "disabled";
</script>';
}
?>
But this code is disabling name, email fields for both users (logged in and non-logged in). I have controlled the script through if condition. Still the javascript is applying for both users. Please advise where I have gone wrong.
Here is the form html -
<form action="/success.php" method="post">
<label>Name :</label><br>
<input type="text" id="curUserName" name="sender_name" required><br>
<label>Email :</label><br>
<input type="text" id="curUserEmail" name="sender_email" required><br>
<label>Subject :</label><br>
<input type="text" name="sender_sub"><br>
<label>Message</label><br>
<textarea name="sender_msg" rows="4" cols="60" required></textarea><br>
<input type="submit" name="submit" value="Send">
</form>
The source you are going to change has disabled option already.. so just remove it if the user is not logged in :)
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
echo '<script type="text/javascript">';
if ( 0 != $current_user->ID )
{
echo 'document.getElementById("curUserName").value = "'.$user_name.'"
document.getElementById("curUserName").disabled = "disabled"
document.getElementById("curUserEmail").value = "'.$user_email.'"
document.getElementById("curUserEmail").disabled = "disabled"';
}
else
{
echo 'document.getElementById("curUserName").disabled = false;
document.getElementById("curUserEmail").disabled = false;';
}
echo '</script>';
?>
Don't echo javascript with php. It's bad practice.
Try using value tags in your inputs, check if user logged in with a ternary operator, and if so, echo to value tag their credentials.
<?php (is_user_logged_in()) ? $current_user = wp_get_current_user() : $current_user = false; ?>
<label>Name</label>
<input type="text" id="curUserName" name="sender_name" value="<?php ($current_user) ? echo $current_user->user_name : '' ?>" required>
<label>Email</label>
<input type="text" id="curUserEmail" name="sender_email" value="<?php ($current_user) ? echo $current_user->user_email : '' ?>" required>

Entered Fields should not be cleared with alert box is displayed in php

I am trying to display a message if the amount entered greater than 5000 alert box or echo messsage "Enter a pan card no" as to be displayed when I click on submit button. In my code Message gets displayed but all the fields which data has been already entered gets cleared. I dont want the data which is entered to get cleared.
Here is the code.
<?php
include_once "db.php";
if(isset($_POST['submit'])) {
$amount = mysql_real_escape_string($_POST["amount"]);
$firstname=mysql_real_escape_string($_POST["firstname"]);
$phone=mysql_real_escape_string($_POST["phone"]);
$address=mysql_real_escape_string(stripslashes($_POST["address"]));
$pan=mysql_real_escape_string(stripslashes($_POST["pan"]));
$query= mysql_query("INSERT INTO payment (amount,selector1,firstname,lastname,email,phone,address,country,state,pan)VALUES('$amount','$selector1','$firstname','$lastname','$email','$phone','$address','$country','$state','$pan') ") or die(mysql_error());
if($amount>="5000")
{
echo "Enter Pan Card No";
}
else {
$id=mysql_insert_id();
$_SESSION['sess_user'] = $id;
$_SESSION['lastname'] = $lastname;
$_SESSION['address']=$address;
header("Location:successreg.php");
}
}
?>
<form action="" method="post" name="payment">
<div class="w3l-user">
<input type="text" name="amount" placeholder="₹ My Contribution" required="">
</div>
<input type="text" name="firstname" placeholder="Firstname" required="">
<input type="text" name="pan" placeholder="Pan Card No" >
</div>
<div class="btn">
<input type="submit" name="submit" value="REGISTER"/>
</div>
</div>
<div class="clear"></div>
</form>
</div>
</div>
In order to show values, after for submission you should get values from $_POST and use them in input values:
$firstname = '';
if(isset($_POST['submit'])) {
// write below line after `if`
$firstname = $_POST['firstname'];
Now, change your HTML to:
<input type="text" name="firstname" placeholder="Firstname" required="" value="<?php echo $firstname; ?>">
For Radio buttons:
$firstRadio = $secondRadio = '';
if(isset($_POST['submit'])) {
// if first radio is selected which you will know from $_POST['firstRadio']
$firstRadio = 'selected';
And in HTML:
<input type='radio' <?php echo $firstRadio;?> value=1 name='firstRadio' />

Php login work only when mysqli_num_rows equal to Zero, otherwise doesn't work.I am stuck

here's the code guys please help me
if mysqli_num_rows==false Than code works but why num rows doesn't work i can't get it i tried everything but same error appears
<?php
//Start session
session_start();
//Include database connection details
require_once('db.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($con,$query);
if($row=mysqli_num_rows($result)==1){
mysqli_fetch_array($con,$result);
echo 'Logged in';
header('location:profile.php');
}
else{
echo 'error occured';
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
session_start();
require_once('db.php');
if(!empty(trim($_POST['username'])) && !empty(trim($_POST['password']))){ // check with posetd value
$user_name = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$query = "SELECT * FROM users where username='$username' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)>0){ // if data comes
// here do some data assignment into session
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}else{
echo "please fill the form value";
}
?>
Note:-
Read and use prepared statements to prevent your code from SQL Injection. :-http://us.php.net/manual/en/mysqli-stmt.prepare.php
Above file extension must be .php

how can I put validation_errors() at the right side of textfield?

I have followed the learning tutorials in CodeIgniter and Im currently creating a program using the same procedure on my reference(link posted below) where there is a log-in form. I have no problem with the functions, I just want to put the validation_errors() at the right side of the textfield where if the username is empty or incorrect, the error message will display on the right side of the textfield. Is there a way to do this? or should I use javascript instead of using this validation_errors()? Hope someone will help me. Thanks!
Here's the code in VIEW:
<h3>Log-In with CodeIgniter</h3>
<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="password" name="password"/>
<br/>
<input type="submit" value="Log-In"/>
</form>
Here's the code in CONTROLLER:
function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run()==FALSE) {
$this->load->view('login_view');
}
else {
redirect('home', 'refresh');
}
}
function check_database($password) {
$username=$this->input->post('username');
$result=$this->user->login($username, $password);
if($result) {
$sess_array=array();
foreach($result as $row) {
$sess_array=array('id'=>$row->id, 'username'=>$row->username);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return FALSE;
}
}
Reference: http://www.codefactorycr.com/login-with-codeigniter-php.html
<h3>Log-In with CodeIgniter</h3>
<?php if (form_error('password')=="Invalid username or password")
{
echo form_error('password');
}
?>
<?php echo form_open('verifylogin'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username"/><?php echo form_error('username'); ?>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="password" name="password"/><?php echo form_error('password'); ?>
<br/>
<input type="submit" value="Log-In"/>
</form>
<?php echo form_open('verifylogin'); ?>
This will display all the errors of FORM at one time - they come in form of bulk errors (not splitted)
<?php echo form_error('username'); ?>
<?php echo form_error('password'); ?>
This is the right way of displaying the individual errors , where CodeIgniter provides you the way of displaying the error individually
showing individual errors in codeigniter
and search for Showing Errors Individually
You can display them in span tag at side of input fields - to get the kind of O/P which you want
Here's what I did..
$this->form_validation->set_message('check_database', '<br/><br/>Invalid username or password');
I added <br/> to Invalid username or password so that it will not place to password field.

Double form will not submit second form

Hi I have two HTML forms when the one is submit a JavaScript function submits the second the one form works but the second doesn't I'm not sure if it is the forms or the post pages can any one help.
The one form sends an email this is sending the email correctly sending the correct data to the correct email address.
The second form is meant to upload a file it doesn't seem to be doing anything at all there are now errors displayed to the screen I have done a try catch and nothing is displayed i have also looked into the logs and nothing is displayed I'm
HTML
<div id="loginborder">
<form id ="upload" enctype="multipart/form-data" action="upload_logo.php" method="POST">
<input name="userfile" type="file" />
<input type="submit" onsubmit="alert()" value="dont press" disabled>
</form>
<div id="login">
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<input type="hidden" name="subject" value="Can you create me a Contributors account">
<input type="text" name="first_name" id="first_name" placeholder="Name">
<input type="text" name="company" id="company" placeholder="Company Name">
<input type="checkbox" id="tc" onclick= "checkbox()">
<input type="submit" id="submit" onsubmit="alert()" name="submit" value="Register" disabled>
</form>
</div>
</div>
<?php
}
else
// the user has submitted the form
{
// Check if the "subject" input field is filled out
if (isset($_POST["subject"]))
{
sleep(5);
$subject = $_POST["subject"];
$first = $_POST["first_name"];
$company = $_POST["company"];
$therest = "First name= $first" . "\r\n" . "Company= $company" . "\r\n";
}
echo "$therest <br>";
$first = wordwrap($first, 70);
mail("careersintheclassroom01#gmail.com",$subject,$name,$therest,"subject: $subject\n");
echo "Thank you for sending us feedback";
header( "refresh:5;url=index.php" );
}
?>
</body>
</html>
javascript
<script type="text/javascript">
function alert()
{
document.getElementById("upload").submit();
}
function checkbox(){
if (document.getElementById("tc").checked == true)
document.getElementById("submit").disabled = false;
else
document.getElementById("submit").disabled = true;
}
$('input[placeholder],input[placeholder],input[placeholder],input[placeholder],input[placeholder]').placeholder();
</script>
Upload_Logo.php
<html>
<head>
</head>
</html>
<?php
$uploaddir = "./images/";
echo $uploaddir;
mkdir($uploaddir, true);
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<br />";
echo " <b>Your media has been uploaded</b><br /><br /> ";
?>
the <?php echo $_SERVER["PHP_SELF"];?> on the second form calls the php at the bottom of the page this is the one that is working it is the upload_logo.php that is not currently working any help would be much appreciated
You're trying to submit 2 forms at once. That can't work, as your browser can only be directed to 1 page at a time, so your attempt to submit the upload form with JavaScript is cancelled by the contact form being submitted. I'd suggest that you move the file input into the same form as the contact fields, and handle them both in your "the user has submitted the form" section.
Something like this should do the trick:
<?php
if (!isset($_POST["submit"]))
{
?>
<div id="loginborder">
<div id="login">
<form enctype="multipart/form-data" method="POST">
<input name="userfile" type="file" />
<input type="hidden" name="subject" value="Can you create me a Contributors account">
<input type="text" name="first_name" id="first_name" placeholder="Name">
<input type="text" name="company" id="company" placeholder="Company Name">
<input type="checkbox" id="tc" onclick="checkbox()">
<input type="submit" id="submit" name="submit" value="Register" disabled>
</form>
</div>
</div>
<?php
}
else
// the user has submitted the form
{
// Check if the "subject" input field is filled out
if (!empty($_POST["subject"]))
{
sleep(5);
$subject = $_POST["subject"];
$first = $_POST["first_name"];
$company = $_POST["company"];
$therest = "First name= $first" . "\r\n" . "Company= $company" . "\r\n";
echo "$therest <br>";
$first = wordwrap($first, 70);
mail("careersintheclassroom01#gmail.com",$subject,$name,$therest,"subject: $subject\n");
echo "Thank you for sending us feedback";
header( "refresh:5;url=index.php" );
}
if (isset($_FILES['userfile']['name'])) {
$uploaddir = "./images/";
if (!file_exists($uploaddir)) {
mkdir($uploaddir, true);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
echo "<br />";
echo " <b>Your media has been uploaded</b><br /><br /> ";
}
}
?>
</body>
try this after $uploadfile = ...
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
when you submit 2nd form e-mail would be generated becausue it triggers if(isset($_POST["subject"])) condition and the code will follow the next commands.
But when you submit 1st form, it will call onsubmit="alert(); function and that function again submits the same form because of these.
function alert()
{
document.getElementById("upload").submit();
}
so you are just triggering a never ending loop.
My solution is
<script type="text/javascript">
function alert()
{
function checkbox(){
if (document.getElementById("tc").checked == true)
document.getElementById("submit").disabled = false;
else
document.getElementById("submit").disabled = true;
}
}
$('input[placeholder],input[placeholder],input[placeholder],input[placeholder],input[placeholder]').placeholder();
</script>
I'am not 100% sure about your requirement. hope you can get the point what i'am making. gl!

Categories