Codeigniter - form error display underneath the input field - javascript

I am trying to display a form error underneath the input fields but after I click the submit button it will redirect to another page...
Here's my code page controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends CI_Controller{
public function view($page = 'home'){
if(!file_exists(APPPATH.'views/pages/'.$page.'.php')){
show_404();
}
$data['title'] = ucfirst($page);
$this->load->view('template/header');
$this->load->view('pages/'.$page);
$this->load->view('template/footer');
}
public function login(){
echo $this->input->POST('username');
}
public function registercheck(){
echo $this->input->POST('username');
echo $this->input->POST('pwd');
echo $this->input->POST('pwd2');
echo $this->input->POST('fname');
echo $this->input->POST('position');
echo $this->input->POST('contactnumber');
$this->form_validation->set_rules('username', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd2', 'UPPERCASE', 'required|max_lenght[20]');
$this->form_validation->set_rules('fname', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('position', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('contactnumber', 'USERNAME', 'required|max_lenght[20]');
if($this->form_validation->run() == false){
$this->load->view('pages/register');
} else{
echo 'register ok';
}
}
}
?>
And here is my views/pages/register.php
<form action="<?php echo base_url(); ?>pages/registercheck" method="post">
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
</form>
Please help me..
What am I doing wrong?
Thank you in advance!

You are in the right direction. But to achieve the desire functionality, you should do as so:
The form and the input validation should be in the same page (controller). In your example, both should be in register.php.
This basic pseudo code should do the trick:
On register page controller:
If method == get:
Display register form.
If method == post:
Check the form data:
If errors exists:
display register page with error.
else:
redirect to ....
Good Luck!

Related

Displaying a php script result in a div using jquery

I am a beginner on coding. I am working on a WordPress website using beaver builder theme. My challenge is to display a login form (when the user is not logged in) and the user name when he is logged in, to a specific area of the header that has a class "header-text".
Here is my php code located in a file named "file.php"
<?php
if(is_user_logged_in()) {
$user = wp_get_current_user();
$var1 = "<p>Welcome <?php echo $user->display_name; ?></p>
<p><a href='/login/login.php?logout=true'>Click here to log out</a></p>";
$var2 = "<form action='login.php' method='post'>
<input type='text" autocomplete='off' placeholder='Username' name='username'/>
<input type='text' autocomplete='off' placeholder='Password' name='password'/>
<button type='submit' value='Submit'>Submit</button>
</form>";
echo echo json_encode($var1);
} else {
echo echo json_encode($var2);
}
?>
Here is javascript
<script type="text/javascript">
jQuery(document).ready(function($){
function displayAccess() {
$.get("login/file.php");
return false;
}
if(<?php echo json_encode($var1); ?>) {
var variable1 = <?php echo json_encode($var1); ?>;
document.getElementByClassName("header-text").innerHTML = variable1;
}
if(<?php echo json_encode($var2); ?>){
var variable2 = <?php echo json_encode($var2); ?>;
document.getElementByClassName("header-text").innerHTML = variable2;
}
});
</script>
I need help to correct my script. Thanks!
in this case, javascript an jquery is not necessary, because the login status changes on reload, anyway.
all you need is a change in your php code:
<?php
/* put this to your template file (e.g. header.php) */
if(is_user_logged_in()) {
$user = wp_get_current_user();
/* change $var1 to echo it via html block inside php */
?>
<p>Welcome <?php $user->display_name; ?></p>
<p>Click here to log out</p>
<?php
/* cut $var2 because it is not accessible in the else clause */
} else {
/*
paste $var2 here and echo it
btw:
* For tags that are self-closing, the forward slash should have exactly one space preceding it (https://make.wordpress.org/core/handbook/best-practices/coding-standards/html/#self-closing-elements)
* use single or double quotes – make a decision!
*/
?>
<form action="login.php" method="post">
<input type="text" autocomplete="off" placeholder="Username" name="username" />
<input type="text" autocomplete="off" placeholder="Password" name="password" />
<button type="submit" value="Submit">Submit</button>
</form>
<?php
}
?>

Codeigniter update form does not submit

Codeigniter offers you a tutorial to get to know it and how to use it. This tutorial teaches you to create elements in a table in a database, but doesn't teach you how to update this elements. I am trying to make an update query using the codeigniter libraries, but the form from de update view doesn't submit.
AT NEWS_MODEL:
public function update_news($slug)
{
$this->load->helper('url');
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
$this->db->where('slug', $slug);
$this->db->update('news', $data);
}
AT NEWS CONTROLLER:
public function update($slug)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
// The form was NOT posted
// So we load the view
$data['news_item'] = $this->news_model->get_news($slug);
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
$this->load->view('templates/footer');
}
else
{
// The form was submitted
$data = array(
'title' => $this->input->post('title'), //-->post variable
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text')
);
$this->news_model->update_news($slug, $data);
$this->load->view('news/success');
}
}
AT UPDATE VIEW:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ;?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update news item" />
</form>
I've tested the code with "console.log()" and the problem seems to be that the form of the update view doesn't submit, but I cannot figure why, because the form is similar to the create form, which does work perfectly:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
your problem is :
you use === instead of == in this line:
if ($this->form_validation->run() === FALSE)

Getting form field values in php and then disabling it

i am using form in my page like this
<form method='post' action='' class='myform'>
<input type='text' name='name'>
<input type='text' name='email'>
<input class='btn' type='submit' name='submit' >
</form>
what i want i will get the values of form and then disable all its fields , now this is my code to disable all fields when form is submitted
$(document).on('click', '.btn', function(event) {
var currentForm = $(this).closest('form');
currentForm.find('input').prop('disabled', true);
});
and before this i'm trying to get values from $_POST like this
if(isset($_POST["submit"])){
$name= $_POST["name"];
$email= $_POST["email"];
}
but problem is that as i press submit button fields get disabled and i dont get any posted values , how do i get values first and then disable fields ?
Your mistake - You are disabling the input field by
currentForm.find('input').prop('disabled', true);
So when you submit the form, the field will be in disabled state and will not be posted.
Solution - please change the line to
currentForm.find('input').prop('readonly', true);
look this example or try with it....
if(isset($_POST["submit"]))
{
$name= $_POST["name"];
$email= $_POST["email"];
}
?>
<form method='post' action='' class='myform'>
<?php
if($name != '' && $email != '')
{
?>
<input type='hidden' name='name' value="<?php echo $name?>">
<input type='hidden' name='email' value="<?php echo $email?>">
<?php
}
?>
<input type='text' name="<?php echo ($name != ''?'hidden_name':'name')?>" <?php echo ($name != ''?'disabled':'')?> value="<?php echo $name?>">
<input type='text' name='<?php echo ($email != ''?'hidden_email':'email')?>' <?php echo ($email != ''?'disabled':'')?> value="<?php echo $email?>">
<input class='btn' type='submit' name='submit' >
</form>
You can use ajax for that like this:
$('.btn').bind('click', function() {
$.ajax({
url: "your page url here",
type: 'POST',
async:false,
success: function(response) {
$('input').prop('disabled', true);
}
});
});
you don't pass submit parameter to formdata, that's why you can't get it.
try this
<?php if(isset($_POST['name'])){ echo $_POST['name'] }?>

How to dynamically create buttons names and detect which button is pressed in PHP?

This is an experiment int PHP that I'm currently working on. It'll be part of a bigger file.
The idea is, the program will generate a set of submit buttons in a form and a unique name will be assigned to each button in this convention: btn[the order of button]
The page will then poll to find if any button was pressed using isset(). Here's what I've got so far.
<html>
<head>
<title>Test Dynamic Naming</title>
</head>
<body>
<form action="testDynamicNaming.php" method="POST">
<?php
$row = 9;
for($i = 0; $i < $row; $i++) {
$name = 'btn['.$i.']';
?>
<input type="submit" name="<?php echo $name; ?>" value="<?php echo $name; ?>"/>
<?php
echo "<br>";
}
?>
</form>
<?php
extract($_REQUEST);
for($i = 0; $i < $row; $i++) {
$name = 'btn['.$i.']';
if(isset($_POST[$name])) {
echo "<br><br>".$name.' is pressed.';
}
// OR
if(isset($$name)) {
echo "<br><br>".$name.' is pressed.';
}
}
?>
</body>
</html>
I managed to set the name and values of the button as I wanted but the page couldn't detect the button that was pressed. What am I missing here, or is there any other way that I could accomplish the same task?
if(isset($_POST['btn'])){
foreach($_POST['btn'] as $key => $value){
echo "Button {$key}:{$value} pressed";
}
}
you may use
if(isset($_POST['btn'][$i])) {
echo "<br><br>".$_POST['btn'][$i].' is pressed.';
}
Maybe use javascript?
easy e.g.
<input type="submit" name="<?php echo $name; ?>" onclick="document.getElementById('<?php echo $name; ?>_pressed').value='true';" value="1"/>
<input type="hidden" id="<?php echo $name; ?>_pressed" name="x1_pressed" value="false">
if(isset($_POST[$name]) == "true") {

Login form using PHP and JQuery to validate login information from MySQL database

I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.

Categories