Here is defined codeigniter4 controller with form validation and view file. How can be reflected on view pages with errors.
Controller code is not reflected on view page . Could anyone clarify the issue of codeigniter4 validation.
Controller
public function register_user(){
helper(['form', 'url']);
$this->validation = \Config\Services::validation();
$validation = $this->validation;
$rules = [
'user_name' => [
'required' => 'All accounts must have usernames provided',
],
];
$this->validation->setRules([
'user_name' => 'required|min_length[2]',
],
$rules
);
if (! $this->validate($rules))
{
$validationErrors = $this->validation->getErrors();
return redirect()->back()->withInput()->with('errors', $validationErrors);
}
}
View
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="screen" title="no title">
</head>
<body>
<style type="text/css">
.error{color: red;}
</style>
<span style="background-color:red;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Please do Registration here</h3>
</div>
<div class="panel-body">
<form role="form" method="post" action="<?php echo base_url('user/register_user'); ?>">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Please enter Name" name="user_name" type="text" autofocus>
<span class="error"><?php echo $validation->getError('user_name'); ?></span>
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Register" name="register" >
</fieldset>
</form>
<center><b>You have Already registered ?</b> <br></b> Please Login</center>
</div>
</div>
</div>
</div>
</div>
</span>
</body>
</html>
Following is the current result:
you can try this controller
public function register_user(){
helper('form');
if (! $this->validate([
'user_name' => 'required|min_length[3]|max_length[255]'
]))
{
echo view('user/login');
}
else{
echo view('user/login_view');
}
}
and this view:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="screen" title="no title">
</head>
<body>
<h2></h2>
<style type="text/css">
.error{color: red;}
</style>
<span style="background-color:red;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Please do Registration here</h3>
</div>
<div class="panel-body">
<form role="form" method="post" action="<?php echo base_url('user/register_user'); ?>">
<fieldset>
<div class="form-group">
<?= esc($user_name); ?>
<span class="error"><?= \Config\Services::validation()->listErrors(); ?></span>
<input class="form-control" placeholder="Please enter Name" name="user_name" type="text" autofocus>
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Register" name="register" >
</fieldset>
</form>
<center><b>You have Already registered ?</b> <br></b> Please Login</center>
</div>
</div>
</div>
</div>
</div>
</span>
</body>
</html>
Dont forget to add route if this use:
$routes->add('/login', 'Login::login');
$routes->add('/user/register_user', 'User::register_user');
This post is not validated but the response of Wandi Tiger is ok for me.
With several rules you can do simply :
$validation = $this->validate([
'user_name' => 'required|min_length[10]|max_length[255]',
'user_pass' => 'required|min_length[10]|max_length[255]'
]);
if($validation)
{
echo view('user/login');
}
else{
echo view('user/login_view');
}
// Keep the old input values upon redirect so they can be used by the old() function
return redirect()->back()->withInput();
// Set a flash message
return redirect()->back()->with('foo', 'message');
You have combined both in your example which will not work
because the variable $validation which you are trying to access in view doesn't contain any data because you have not assigned any data to it
So you have to replace
if (! $this->validate($rules))
{
$validationErrors = $this->validation->getErrors();
return redirect()->back()->withInput()->with('errors', $validationErrors);
}
with this code:
if (! $this->validate($rules))
{
$data['validation'] = $this->validatior;
return view('view-name',$data); //note don't forget to replace view-name.
}
Don't change anything in the view file.
Related
My form somehow only seems to send the last data entry (user_feel).
It's my first time working with forms and I can't figure out why the other entries aren't sent with the rest of the form:
<!DOCTYPE html>
<head>
<title>How was your day? (So far)</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
<link href='custom.css' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">
<h1>Activity form</h1>
<p class="lead">Please indicate what you've eaten and which social activities (if any) you've participated in.</p>
<form id="activity-form" method="post" action="form.php">
<div class="messages"></div>
<div class="controls">
<br />
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">What is your name? *</label>
<input id="name" type="text" name="user_name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="time">Which part of the day are you reporting on? *</label>
<select id="time" name="current_time" class="form-control" required="required" data-error="Please specify the time of day.">
<option value="">Select the time of day</option>
<option value="morning">Morning</option>
<option value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="feel">How do you feel? *</label>
<p>Level three is the base level. It's where you don't feel especially good or bad, and consider yourself feeling 'neutral' compared to how you usually feel.</p>
<select id="feel" name="user_feel" class="form-control" required="required" data-error="Please specify how you feel.">
<option value="">Select how you feel</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Save data">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" integrity="sha256-dHf/YjH1A4tewEsKUSmNnV05DDbfGN3g7NMq86xgGh8=" crossorigin="anonymous"></script>
<script src="form.js"></script>
</body>
</html>
I serialize the form and send it using ajax, the php script echo's out all key:value pairs it gained form the post. This is where i only get the user_feel selection, all other selections from the form seem to be ignored.
This is the JS file:
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#activity-form').validator();
// when the form is submitted
$('#activity-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "form.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#activity-form').find('.messages').html(alertBox);
// empty the form
$('#activity-form')[0].reset();
}
}
});
return false;
}
})
});
And this is the PHP script:
<?php
$okMessage = 'Your data has been submitted succesfully! Thanks a bunch!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
foreach ($_POST as $key => $value) {
$debug = "";
$debug .= "$key: $value\n";
}
$responseArray = array('type' => 'success', 'message' => $okMessage."\r\n".$debug);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
It's based on the code from: https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
I have one small web app for learning purposes, and I realised "required" attribute doesn´t work, and I can´t find why. It happens on many browsers, so I guess it is not a browser problem.
Things I tried:
Check <!DOCTYPE html> tag is included
Semi-closed the input tags (but deleted that since I have read here it could make some browsers to work in a wrong way).
Check no value attribute is included, since it could make the required attribute be useless
Just to test, put the input button out of the enclosing tags
The two forms seem to be properly closed
Links I looked:
HTML input required attribute not working for a field
html required tag doesn't work for form submission
textarea's "required" attribute doesn't work even though the value is empty
'Required' attribute not working
Required attribute doesn't work
And many others
My code:
index.php
<?php
session_start();
require_once('models/UsuarioPDO.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/form-styles.css">
<link rel="stylesheet" href="assets/css/styles.css">
<link rel="stylesheet" href="assets/css/cookies.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css">
<!--jquery always bwfore bootsrap, sine bootsrap need it-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" defer></script>
<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css" >
<script src="/bootstrap/js/bootstrap.min.js" defer></script>
<script src="controls/registerSubmit.js" defer></script>
<!------ Include the above in your HEAD tag ---------->
</head>
<body>
<?php
/*if there is the two cookies, we start the session with the user
who belog the data of that cookie*/
if(isset($_COOKIE["id_usuario_myreminder"]) && isset($_COOKIE["random_number_user_myreminder"]))
{
$usuarioAlogear= usuarioPDO::getUserWhenCookie($_COOKIE["id_usuario_myreminder"],$_COOKIE["random_number_user_myreminder"]);
$_SESSION["usuario"]=$usuarioAlogear;
}
/*if there is user logged in, back to main*/
if(isset($_SESSION["usuario"]))
{
header('Location:views/main.php');
exit;
}else
{/*if there is not logged user, show index components*/
/*is comes from registerUser.php but was not possible to insert the user due to repeated email,
we send a session variables here to make this page show a flag, then we destroy the session
to ensure it won´t appear again*/
if( (isset($_SESSION["mailrepetido"]))&&($_SESSION["mailrepetido"])==true )
{
?>
<div class="alert alert-danger" role="alert">
E Mail already exists for another user
</div>
<?php
session_destroy();
}
/*if login attempt was wrong, another flag*/
if( isset($_SESSION["wrongLogIn"]) )
{
if($_SESSION["wrongLogIn"]==true)
{
?>
<div class="alert alert-danger" role="alert">
wrong login
</div>
<?php
session_destroy();
}
}
/*if session is closed*/
if( isset($_SESSION["closedSession"]) )
{
if($_SESSION["closedSession"]==true)
{
?>
<div class="alert alert-info">
Closed Session
</div>
<?php
session_destroy();
}
}
?>
<?php include("views/view_login_register_forms.php"); ?>
<br><br>
<?php include("views/view_footer.php"); ?>
<?php
}/* end else*/
include('views/view_cookies-banner.php');
?>
</body>
</html>
view_login_register_forms.php
<div class="container">
<div class="card bg-light">
<article class="card-body mx-auto" style="max-width: 400px;">
<h4 class="card-title mt-3 text-center">MY REMINDER</h4>
<img src="assets/imagenes/bombilla.svg" class="img-responsive" alt="man_and_bulb">
<p class="divider-text">
<span class="bg-light">LOG IN </span>
</p>
<?php /* remember action path will be called from index*/ ?>
<form id="formLogIn" method="post" action="controls/loginUser.php">
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-envelope"></i> </span>
</div>
<input name="email-Input-Name" class="form-control" placeholder="Email address" type="email" required>
</div> <!-- form-group// -->
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-lock"></i> </span>
</div>
<input name="password-Input-Name" class="form-control" placeholder="Enter password" type="password" required>
</div> <!-- form-group// -->
<!--remember me checkbox-->
<div class="form-group input-group">
<input name="remember-Input-Name" id="id_remember_checkbox" type="checkbox" value="remember"> <label for="id_remember_checkbox" id="id_label_remember">Remember me</label>
</div> <!-- form-group// -->
<p>
<button type="submit" class="btn btn-primary" id="loginButton">Log in to your reminder</button>
</p>
</form>
<p class="divider-text">
<span class="bg-light">OR REGISTER</span>
</p>
<?php /* remember action path will be called from index*/ ?>
<form id="formRegister" method="post" action="controls/loginUser.php">
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-user"></i> </span>
</div>
<input name="newUserName" class="form-control" placeholder="Name (required)" type="text" required>
</div> <!-- form-group// -->
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-envelope"></i> </span>
</div>
<input name="email-Input-Name" id="id_email-Input-Name" class="form-control" placeholder="Email address (required)" type="email" required>
</div> <!-- form-group// -->
<label for="password-Input-Name">Password must be between 8-20 characters</label>
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-lock"></i> </span>
</div>
<input name= "password-Input-Name" id="id_password-Input-Name" maxlength="20" class="form-control" placeholder="Password (required)" type="password" required>
</div> <!-- form-group// -->
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-lock"></i> </span>
</div>
<input name="newUserPassRepeat" id="id_newUserPassRepeat" maxlength="20" class="form-control" placeholder="Repeat password (required)" type="password" required>
</div> <!-- form-group// -->
<input name="registerUserInputName" type="hidden" value="true">
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block" id="registerButton"> Create Account </button>
</div> <!-- form-group// -->
</form>
</article>
</div> <!-- card.// -->
</div>
<!--container end.//-->
The app is here
https://myreminder.avanzartewebs.com/index.php
You can check how, for example, if you include en ampty email, it says things like "E mail already exists for another user" if there is an already created user with an empty email, and it should never be submitted when that happens.
The thing is, when I was developing it, I think required attribute worked... but it stopped working and I don´t know why or when.
I found part of the solution on this post
html5 required validator not working with input type=button
That's because the required validator is only called on submit
I had this code on another file that was causing the error:
$("#registerButton").click(function(e){
e.preventDefault();
//some code
}
What I did is to start working on the submit() event of the form, and not on the click() event of the button.
I found on this post, which helped me a lot.
Submit form after calling e.preventDefault()
I discovered it was a better idea to move the e.preventDefault() to the condition were validation is not right, so I could avoid the submit action only in case the condition is not true.
This is the resulting code which seems to be working now:
$(`#formRegister`).submit(function(e){
//e.preventDefault(); NOT HERE
let newPass=$(`#id_password-Input-Name`).val();
let repeatPass=$(`#id_newUserPassRepeat`).val();
let tamanioNewPass=newPass.length;
let tamanioRepeatPass=repeatPass.length;
/*if passwords are the same, and have minimun 8 characters, ok (16 characters maximum is controlled with html)*/
/*it is only neccesary to test if one of them is >= 8 , because if they are the same and one of them is >=8, the other is equal valid too*/
if((newPass===repeatPass) && (tamanioNewPass>=8) )
{
$(`#formRegister`).submit();
}
else
{
e.preventDefault(); //if pass is wrong, don´t submit!
alert(`could not be possible to do registration submit`);
}
});
I am still looking forward to getting this solved. The simple thing to be done is to use autocomplete in an input form control, to my surprise it not puling the records from into the text input. If I query the result through the browser, I do see the results thus:
http://localhost:2222/json/redirects/
I do see this result:
[{"id":null,"value":"Andorra"},{"id":null,"value":"United Arab Emirates"},{"id":null,"value":"Afghanistan"},{"id":null,"value":"Antigua and Barbuda"},{"id":null,"value":"Anguilla"},{"id":null,"value":"Albania"},{"id":null,"value":"Armenia"},{"id":null,"value":"Netherlands Antilles"},{"id":null,"value":"Angola"},{"id":null,"value":"Antarctica"},
This is the blade file:
<!DOCTYPE html>
<html>
<head>
{!! Html::style('bootstrap/css/bootstrap.css') !!}
{!! Html::style('bootstrap/css/bootstrap.min.css') !!}
<link href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" media="all" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<section class="panel panel-default">
<header class="panel-heading">
<input type="text" name="searchname" id="searchname" class="form-control" placeholder="enter name">
</header>
<div class="panel-body">
<table>
<tr>
<td><input type="text" name="id" id="id" class="form-control" placeholder="ID" ></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td><input type="text" name="name" id="name" class="form-control" placeholder="Name" ></td>
</tr>
</table>
</div>
</section>
</div>
</div>
</body>
<script type="text/javascript">
$('#searchname').autocomplete({
source: '{!! Url::route('jsonRedirect') !!}',
minlength: 1,
autofocus: true,
select: function(e, ui){
alert(ui);
}
});
</script>
</html>
This is the controller:
public function SelectLocationPlaces(Request $userAdressRequest)
{
$term = $userAdressRequest->term;
$data = Country::where('name', 'LIKE', '%'.$term.'%')->take(10)->get();
$results = array();
foreach ($data as $key => $value) {
$results[] = ['id'=>$value->id, 'value'=>$value->name];
}
return response()->json($results);
}
This is the route:
Route::get('json/redirects', array('as'=>'jsonRedirect', 'uses'=>'UserAddressController#SelectLocationPlaces'));
Error log:
<body>
<div id="sf-resetcontent" class="sf-reset">
<h1>Whoops, looks like something went wrong.</h1>
<h2 class="block_exception clear_fix">
<span class="exception_counter">1/1</span>
<span class="exception_title"><abbr title="Symfony\Component\Debug\Exception\FatalErrorException">FatalErrorException</abbr> in <a title="C:\Users\ken4ward\Documents\xampp\htdocs\tradersmart\storage\framework\views\d12352064f8db7567c7110c110aa0321 line 39" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">d12352064f8db7567c7110c110aa0321 line 39</a>:</span>
<span class="exception_message">Class 'Url' not found</span>
</h2>
<div class="block">
<ol class="traces list_exception">
<li> in <a title="C:\Users\ken4ward\Documents\xampp\htdocs\tradersmart\storage\framework\views\d12352064f8db7567c7110c110aa0321 line 39" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">d12352064f8db7567c7110c110aa0321 line 39</a></li>
</ol>
</div>
Please,kind hearts, what could be the reason why the autocomplete not working but yet I can view the json response on the url?
Thanks, everyone. It's finally working. It was caused by passing the wrong URL format as the source. So, all I changed is this:
From: source: '{!! Url::route('jsonRedirect') !!}',
To: '{{ url('json/redirects') }}',
I am working in a project with codeigniter and bootstrap, I made an autocomplete system, but the css looks broken like this
https://gyazo.com/4af7ae2bbdfd5547233d192b80ef947e
There is no custom style, only the bootstrap min css, here is my view html code, any help to look like it should be would be appreciated
<h2>Welcome to Crossover Laboratory</h2>
<div class="row">
<div class="col-md-1">
</div>
<div class='col-md-10 text-center'>
<h3>Patients</h3>
<?php echo $error2; ?>
<?php
$attributes2 = array(
"class"=>"form-horizontal",
"id" => "LoginForm2",
"name" => "LoginForm2",
"method" => "post"
);
echo form_open("laboratory/patients", $attributes2); ?>
<div class="form-group">
<input type="text" name="username_patients" id="username_patients" class="ui-autocomplete-input" value="" required placeholder="Name" />
<p id="patient_name"></p>
</div>
<div class="form-group">
<input type="password" name="password_patients" id="password_patients" value="" required placeholder="Code"/>
</div>
<div class="form-group">
<?php echo form_submit("Login2","Login"); ?>
</div>
<?php echo form_close(); ?>
</div>
<div class="col-md-1">
</div>
</div>
<script type="text/javascript">
$(document).ready(function($) {
$("#username_patients").autocomplete({
source: '<?php echo site_url('laboratory/autocomplete'); ?>',
minlenght: 2,
html: true,
open: function(event, ui)
{
$(".ui-autocomplete").css("z-index",1000);
}
});
});
</script>
I think you have missed the jQueryUI CSS references. Add the below CSS in your application <head> section and try..
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
I'm trying to allow a pop up to display always when a user is basically unregistered and wishes to view the certain page. I saw an example of how to do it but I am completely stuck it's not appearing on my page. Any ideas?
Thanks!
Image: http://puu.sh/cr1Zz/1b5da28635.png
My code on that page(CSS is listed in the image above)
<?php
session_start();
include ('../includes/config.php');
include ('../includes/header.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Honda | </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href='http://fonts.googleapis.com/css?family=Julius+Sans+One' rel='stylesheet' type='text/css'>
<link href="../css/style.css" rel="stylesheet" type="text/css" media="all" />
<!--start lightbox -->
<link rel="stylesheet" type="text/css" href="../css/jquery.lightbox.css">
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.lightbox.js"></script>
<script>
// Initiate Lightbox
$(function() {
$('.gallery1 a').lightbox();
});
</script>
</head>
<body>
<div class='modalDialog'>You cannot view this page! Please register</div>
<!--start header-->
<div class="h_bg">
<div class="wrap">
<div class="wrapper">
<div class="header">
<div class="logo">
<img src="../images/logo.png">
</div>
<div class="cssmenu">
<ul>
<li><span>Home</span></li>
<li><span>About</span></li>
<li class="active" class="has-sub"><span>Gallery</span>
</li>
<li class="last"><span>Contact</span></li>
<div class="clear"></div>
<div class="search">
<h2>search</h2>
<form>
<input type="text" value="" placeholder="Enter Your search...">
<input type="submit" value="">
</form>
</div>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['user']) && !empty($_POST['pass'])) {
$user=$_POST['user'];
$pass=$_POST['pass'];
$pass = strip_tags($pass);
$pass = md5($pass); // md5 is used to encrypt your password to make it more secure.
$query=mysql_query("SELECT * FROM login WHERE username='".$user."' AND password='".$pass."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($user == $dbusername && $pass == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$user;
/* Redirect browser */
header("Location: member.php");
}
} else {
echo "<div class='results'>Invalid username or password!</div>";
}
} else {
echo "All fields are required!";
}
}
?>
<div class="search1">
<h2>login/Register</h2>
<form action="" method="POST">
<label>Username:</label>
<input type="text" name="user" required />
<label>Password:</label>
<input type="password" name="pass" required />
<input type="submit" value="Login" name="submit" class="submit" />
<br><br>
<center>
<h2><p>Register</p></h2>
</center>
</form>
</div>
</div>
</ul>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<!-- start content -->
<div class="footer_bg">
<div class="wrap">
<div class="wrapper">
<div class="footer2">
<div class="copy">
<p class="w3-link">© </p>
</div>
<div class="f_nav">
<ul>
<li>Skype</li>
<li>Linked in</li>
<li>Twitter</li>
<li>Facebook</li>
</ul>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
</body>
</html>
Although you include jQuery, the modal dialog is part of the jQueryUI. But that on its own won't solve your problem. You have declared a div with the class modalDialog, so I suppose this is the line to be shown in the dialog. I would suggest you to use id's instead of classes because a class covers multiple document objects, and you really want to show one dialog here. From the jQueryUI docs:
<div id="dialog" title="Please register">
<p>You cannot view this page! Please register</p>
</div>
Add the jQuery call:
$(function() {
$( "#dialog" ).dialog();
});
And that should work just fine
If you decide to go with the lightbox modal dialog your code should look like:
<div id="test-modal" class="white-popup-block mfp-hide">
<h1>lease register</h1>
<p>You cannot view this page! Please register</p>
<p><a class="popup-modal-dismiss" href="#">Dismiss</a></p>
</div>
To call the code use:
$(function () {
$('.popup-modal').magnificPopup({
type: 'inline',
preloader: false,
focus: '#username',
modal: true
});
$(document).on('click', '.popup-modal-dismiss', function (e) {
e.preventDefault();
$.magnificPopup.close();
});
});