Saturday, February 6, 2021

Loading data remotely in Select2 with AJAX

Select2 is a jQuery plugin that extends the functionality of a simple HTML drop-down element by allowing to search the list, adding the image with options, navigate to the option with arrow keys, etc.

It comes with the AJAX supports where you can call it in the same way as $.ajax in the jQuery.

The plugin provides the currently inputted value in the search box which can be used as data in the AJAX request.

Contents

  1. Table structure
  2. Configuration
  3. Download and Include
  4. HTML
  5. PHP
  6. jQuery
  7. Demo
  8. Conclusion

1. Table structure

I am using users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for database configuration.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Download and Include

  • Download the library from here.
  • Include select2.min.css and select2.min.js files with the jQuery library in the <head> section. You can also use the CDN.
<meta charset="UTF-8">
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>

4. HTML

Create a drop-down element.

Completed Code

<select id='selUser' style='width: 200px;'>
 <option value='0'>- Search user -</option>
</select>

5. PHP

Create a getData.php file.

Select all records with the limit of 5 when $_POST['searchTerm'] is not set otherwise select record according to the search term.

Create an array that initializes with user id and name. Return the array in JSON format.

NOTE – While creating associative array for initialize the Array make sure that their you have defined id and text keys otherwise the HTML element will not be initialized.

Completed Code

<?php
include 'config.php';

if(!isset($_POST['searchTerm'])){ 
  $fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{ 
  $search = $_POST['searchTerm'];   
  $fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
} 

$data = array();
while ($row = mysqli_fetch_array($fetchData)) {    
  $data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);

6. jQuery

Call select2() method on the <select id='selUser'> to initialize the plugin. To load records remotely specify ajax option where set its url, type, dataType, delay, data, and processResults.

Get the entered values using params.term in data. The successful callback handle by processResults function where initialize results with the response.

Completed Code

$(document).ready(function(){

 $("#selUser").select2({
  ajax: { 
   url: "getData.php",
   type: "post",
   dataType: 'json',
   delay: 250,
   data: function (params) {
    return {
      searchTerm: params.term // search term
    };
   },
   processResults: function (response) {
     return {
        results: response
     };
   },
   cache: true
  }
 });
});

 

Credits: https://makitweb.com/loading-data-remotely-in-select2-with-ajax/


Sunday, December 20, 2020

Best Way to redirect http to https in CodeIgniter

Follow the below steps to enable http to https on your codeIgnitor 3.x using.

STEP 1. Config changes :- Go to “application/config/config.php” and enable or set hooks to true.

$config['enable_hooks'] = TRUE;

STEP 2: Create a new file named hooks.php in “application/config/hooks.php” if not exists and if its already exists just add below code in hooks.php

$hook['post_controller_constructor'][] = array(

                                'function' => 'redirect_ssl',

                                'filename' => 'ssl.php',

                                'filepath' => 'hooks'

                                );

STEP 3: Now create a new directory with named “hooks” under application directory and then create new file named “ssl.php” in “application/hooks/ssl.php” and add below code to “ssl.php”

function redirect_ssl() {

    $CI =& get_instance();

    $class = $CI->router->fetch_class();

    $exclude =  array('client');  // add all your controllers name to exclude ssl.

    if(!in_array($class,$exclude)) {

      // redirecting to ssl.

      $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);

      if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());

    }

    else {

      // redirecting with no ssl.

      $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);

      if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());

    }

}


Credits: https://stackoverflow.com/users/2261069/preetham-hegde

Thursday, December 17, 2020

JavaScript : HTML Form validation - checking for password

Password validation

Sometimes a password validation in a form is essential. You can create a password in different ways, it's structure may be simple, reasonable or strong. Here we validate various type of password structure through JavaScript codes and regular expression.

  • Check a password between 7 to 16 characters which contain only characters, numeric digits and underscore and first character must be a letter.
  • Check a password between 6 to 20 characters which contain at least one numeric digit, one uppercase and one lowercase letter.
  • Check a password between 7 to 15 characters which contain at least one numeric digit and a special character.
  • Check a password between 8 to 15 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character.

Following code blocks contain actual codes for the said validations. We have kept the CSS code part common for all the validations.

CSS Code:

li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

To check a password between 7 to 16 characters which contain only characters, numeric digits, underscore and first character must be a letter

To validate the said format we use the regular expression ^[A-Za-z]\w{7,15}$, where \w matches any word character (alphanumeric) including the underscore (equivalent to [A-Za-z0-9_]).  Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
title>JavaScript form validation - Password Checking - 1</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input Password and Submit [7 to 15 characters which contain only characters, numeric digits, underscore and first character must be a letter]</h2
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="CheckPassword(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="check-password-1.js"></script>
</body>
</html>

JavaScript Code:

function CheckPassword(inputtxt) 
{ 
var passw=  /^[A-Za-z]\w{7,14}$/;
if(inputtxt.value.match(passw)) 
{ 
alert('Correct, try another...')
return true;
}
else
{ 
alert('Wrong...!')
return false;
}
}

View the example in the browser

To check a password between 6 to 20 characters which contain at least one numeric digit, one uppercase and one lowercase letter

To validate the said format we use the regular expression ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$.  Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - Password Checking - 2</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input Password and Submit [6 to 20 characters which contain at least one numeric digit, one uppercase and one lowercase letter]</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="CheckPassword(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="check-password-2.js"></script>
</body>
</html>

JavaScript Code:

function CheckPassword(inputtxt) 
{ 
var passw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
if(inputtxt.value.match(passw)) 
{ 
alert('Correct, try another...')
return true;
}
else
{ 
alert('Wrong...!')
return false;
}
}

View the example in the browser

To check a password between 7 to 15 characters which contain at least one numeric digit and a special character

To validate the said format we use the regular expression ^^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$.  Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - Password Checking - 3</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input Password and Submit [7 to 15 characters which contain at least one numeric digit and a special character]</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li>&nbsp;</li>
<li><input type="submit" name="submit" value="Submit" onclick="allnumericplusminus(document.form1.text1)" /></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="check-password-3.js"></script>
</body>
</html>

JavaScript Code

function CheckPassword(inputtxt) 
{ 
var paswd=  /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$/;
if(inputtxt.value.match(paswd)) 
{ 
alert('Correct, try another...')
return true;
}
else
{ 
alert('Wrong...!')
return false;
}
}  

View the example in the browser

To check a password between 8 to 15 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character

To validate the said format we use the regular expression ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$.  Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - Password Checking - 4</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input Password and Submit [8 to 15 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character]</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li>&nbsp;</li>
<li><input type="submit" name="submit" value="Submit" onclick="allnumericplusminus(document.form1.text1)" /></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="check-password-4.js"></script>
</body>
</html>

JavaScript Code:

function CheckPassword(inputtxt) 
{ 
var decimal=  /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
if(inputtxt.value.match(decimal)) 
{ 
alert('Correct, try another...')
return true;
}
else
{ 
alert('Wrong...!')
return false;
}
} 

View the example in the browser

Source & Credit: https://www.w3resource.com/javascript/form/password-validation.php

 

How to change the PHP version for subfolders or subdomains

  How to change the PHP version for subfolders or subdomains Setting a specific PHP version for a specific websites, subfolders or subdomain...