article

Friday, November 19, 2021

AngularJS Dynamic Add Remove Input Fields with PHP and Mysql

AngularJS Dynamic Add Remove Input Fields with PHP and Mysql

CREATE TABLE `skills` (
  `id` int(11) NOT NULL,
  `skillname` varchar(150) NOT NULL,
  `username` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


ALTER TABLE `skills`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `skills`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Dynamic Add Remove Input Fields with PHP and Mysql</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.min.js"></script>
</head>
<body>
<div class="container">
	<div class="col-md-8">
   <h3 align="center">AngularJS Dynamic Add Remove Input Fields with PHP and Mysql</h3>
	<br />
	<div ng-app="angularappaddremovefields" ng-controller="dynamicController" class="container" ng-init="fetchData()">
	   
	<div class="alert alert-success alert-dismissible" ng-show="success" >
		<a href="#" class="close" aria-label="close">×</a>
		{{successMessage}}
	</div>

	<div class="alert alert-danger alert-dismissible" ng-show="error" >
		<a href="#" class="close" aria-label="close">×</a>
		{{errorMessage}}
	</div>

    <form method="post" ng-submit="submitForm()">
		<div class="form-group">
			<label>Enter Your Name</label>
			<input type="text" name="username" id="username" ng-model="formData.username" class="form-control" />
		</div>
	
		<fieldset ng-repeat="row in rows">
		 <div class="form-group">
		  <label>Enter Your Skills</label>
		  <div class="row">
		   <div class="col-md-9">
			<input type="text" name="txtskills[]" class="form-control" ng-model="formData.skill[$index + 1]" />
		   </div>
		   <div class="col-md-3">
			<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
		   </div>
		  </div>
		 </div>
		</fieldset>
		<div class="form-group">
		 <button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
		 <input type="submit" name="submit" class="btn btn-info" value="Save" />
		</div>
    </form>

	<div class="table-responsive">
		<table class="table table-bordered table-striped">
		 <tr>
		  <th>Skills</th>
		 </tr>
		 <tr ng-repeat="rs in skillData">
		  <td>{{rs.skillname}}</td>
		 </tr>
		</table>
	</div>
	</div>
  </div>
</div>

<script>
var app = angular.module('angularappaddremovefields', []);

app.controller('dynamicController', function($scope, $http){

	$scope.success = false;
	$scope.error = false;

	$scope.fetchData = function(){
	  $http.get('fetch_data.php').success(function(data){
	   $scope.skillData = data;
	  });
	};

	$scope.rows = [{username: 'txtskills[]', username: 'remove'}];

	$scope.addRow = function(){
	  var id = $scope.rows.length + 1;
	  $scope.rows.push({'id':'dynamic'+id});
	};

	$scope.removeRow = function(row){
	  var index = $scope.rows.indexOf(row);
	  $scope.rows.splice(index, 1);
	};

	$scope.formData = {};
	$scope.formData.username = "cairocoders";

	$scope.submitForm = function(){
	  $http({
	   method:"POST",
	   url:"insert.php",
	   data:$scope.formData
	  }).success(function(data){ console.log(data);
	   if(data.error != '')
	   {
		$scope.success = false;
		$scope.error = true;
		$scope.errorMessage = data.error;
	   }
	   else
	   {
		$scope.success = true;
		$scope.error = false;
		$scope.successMessage = data.message;
		$scope.formData = {};
		$scope.formData.username = "cairocoders";
		$scope.rows = [{username: 'txtskills[]', username: 'remove'}];
		$scope.fetchData();
	   }
	  });
	};

});
</script>
 </body>
</html>
fetch_data.php
//fetch_data.php
<?php
include('dbcon.php');
$query = "SELECT * FROM skills ORDER BY id";
$statement = $connect->prepare($query);
if($statement->execute())
{
	while($row = $statement->fetch(PDO::FETCH_ASSOC))
	{
	  $data[] = $row;
	}
 echo json_encode($data);
}
?>
insert.php
//insert.php
<?php
include('dbcon.php');

$form_data = json_decode(file_get_contents("php://input"));

$error = '';
$message = '';
$validation_error = '';
$username = '';
$txtskills = '';

$username = $form_data->username;

if(empty($form_data->skill))
{
	$error[] = 'Skill is Required';
}else{
	foreach($form_data->skill as $rs)
	{
	  $txtskills .= $rs . ', ';
	}
	 $txtskills = substr($txtskills, 0, -2);
}

$data = array(
	':username'      => $username,
	':txtskills' => $txtskills
);

if(empty($error))
{
	$query = "
	 INSERT INTO skills 
	 (username, skillname) VALUES 
	 (:username, :txtskills)
	 ";
	 $statement = $connect->prepare($query);
	 if($statement->execute($data))
	 { 
	    $message = 'Data Inserted '.$username.' = '.$txtskills.'';
	 }
}else {
	$validation_error = implode(", ", $error);
}

$output = array(
	 'error'  => $validation_error,
	 'message' => $message
);

echo json_encode($output);
?>
dbcon.php
//dbcon.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>

Thursday, November 18, 2021

Vue.js Axios Autocomplete textbox with PHP and MySQL

Vue.js Autocomplete textbox with PHP and MySQL

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Autocomplete textbox with PHP and MySQL</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" type="text/css" href="style.css">
	<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
	<script src='https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'></script>
</head>
<body>
	<div id='myapp' style="padding:20px;">
		<p><h1>Vue.js Autocomplete textbox with PHP and MySQL</h1></p>
		<vueauto-complete v-model="country" @input="handleInput1()"></vueauto-complete>
		<p><b>Selected Country id : {{ country }}</b> </p>
	</div>
	
	<script >
	Vue.component('vueauto-complete', {
	  	data: function () {
	    	return {
	      		searchText:'',
        		suggestiondata:[]
	    	}
	  	},
	  	template: `<div class='vueautocomplete' > 
	  		<div>
		  		<input type='text' @keyup='loadSuggestions' placeholder='Enter some text' v-model='searchText'>	<br> 
		  		<div class='suggestionlist' v-if="suggestiondata.length" >
		  		<ul> 
		  			<li v-for= '(item,index) in suggestiondata' @click='itemSelected(index)'> 
		  				{{ item.name }} 
		  			</li>  
		  		</ul>
		  		</div>  
	  		</div>
	  	</div>`, 
	  	methods: {
			loadSuggestions: function(e){
				var el = this;
				this.suggestiondata = [];
				
				if(this.searchText != ''){

					axios.get('search.php', {
						params: {
							search: this.searchText
						}
					})
					.then(function (response) {
						el.suggestiondata = response.data;
					});
				}	
			},
			itemSelected: function(index){
				var id = this.suggestiondata[index].id;	
				var name = this.suggestiondata[index].name;	

				this.searchText = name;
				this.suggestiondata = [];

				this.$emit("input", id);
			}
		},
	})

	var app = new Vue({
	  	el: '#myapp',
	  	data: {
		    country: 0
		},
		methods: {
			handleInput1: function(){
				console.log("value : " + this.country);
			}
		}
	})
	</script>
</body>
</html>
search.php
//search.php
<?php
include "config.php";

if(isset($_GET['search'])){
	$search = mysqli_real_escape_string($con,trim($_GET['search']));

	$data = array();
	if(!empty($search)){

		$result = mysqli_query($con,"select * from country where country like '%".$search."%'");
		
		while ($row = mysqli_fetch_array($result)) {
		  	$data[] = array(
		  			"id" => $row['id'],
		  			"name"=>$row['country']
		  		);
		}
	}

	echo json_encode($data);
	exit;
}
config.php
//config.php
<?php
$host = "localhost";   
$user = "root";     
$password = "";       
$dbname = "testingdb"; 

// Create connection
$con = mysqli_connect($host, $user, $password,$dbname);

// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
style.css
//style.css
.vueautocomplete,.vueautocomplete .suggestionlist{
    width: 300px;
}
.vueautocomplete input[type=text]{
    width: 100%;
    padding: 5px;
}
.suggestionlist{
    position: absolute;
}
.suggestionlist ul{
    width: 100%;
    background: whitesmoke;
    list-style: none;
    margin: 0;
    padding: 5px;
} 
.suggestionlist ul li{
    background: white;
    padding: 4px;
    margin-bottom: 1px;
}
.suggestionlist li:not(:last-child){
    border-bottom: 1px solid #cecece;
}
.suggestionlist ul li:hover{
    cursor: pointer;
    background: whitesmoke;
}

Wednesday, November 17, 2021

Python Flask Upload multiple images and display with Progress Bar Jquery Ajax

Python Flask Upload multiple images and display with Progress Bar Jquery Ajax

jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.

https://github.com/jquery-form/form
bootstrap progressbar https://getbootstrap.com/docs/4.0/components/progress/

app.py
//app.py
from flask import Flask, flash, request, redirect, url_for, render_template, jsonify
import os
from werkzeug.utils import secure_filename
import urllib.request
 
app = Flask(__name__)
         
UPLOAD_FOLDER = 'static/uploads/'

app.secret_key = "cairocoders-ednalan"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
 
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def index(): 
    return render_template('index.html')
 
@app.route('/', methods=['POST'])
def upload():
	if 'uploadFile[]' not in request.files:
		return redirect(request.url)
	files = request.files.getlist('uploadFile[]')
	file_names = []
	for file in files:
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file_names.append(filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
			msg  = 'File successfully uploaded to /static/uploads!'
		else:
			msg  = 'Invalid Uplaod only png, jpg, jpeg, gif'
	return jsonify({'htmlresponse': render_template('response.html', msg=msg, filenames=file_names)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Python Flask Upload multiple images and display with Progress Bar Jquery Ajax</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
</head>
    <body>
        <div class="container">
            <br />
            <h3 align="center">Python Flask Upload multiple images and display with Progress Bar Jquery Ajax</h3>
            <br />
            <div class="panel panel-default">
                <div class="panel-heading"><b>Ajax File Upload Progress Bar using JQuery Ajax</b></div>
                <div class="panel-body">
					<form id="uploadImage" method="post" action="/" enctype="multipart/form-data">
                        <div class="form-group">
                            <label>File Upload</label>
                            <input type="file" name="uploadFile[]" multiple="true" id="uploadFile" accept=".jpg, .png" />
                        </div>
                        <div class="form-group">
                            <input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
                        </div>
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <div id="targetLayer" style="display:none;"></div>
                    </form>
                </div>
            </div>
        </div>
<script>
$(document).ready(function(){
    $('#uploadImage').submit(function(event){
        if($('#uploadFile').val()){
            event.preventDefault();
            $('#loader-icon').show();
            $('#targetLayer').hide();
            $(this).ajaxSubmit({
                target: '#targetLayer',
                beforeSubmit:function(){
                    $('.progress-bar').width('50%');
                },
                uploadProgress: function(event, position, total, percentageComplete)
                {
                    $('.progress-bar').animate({
                        width: percentageComplete + '%'
                    }, {
                        duration: 1000
                    });
                },
                success:function(data){
                    $('#loader-icon').hide();
                    $('#targetLayer').show();
                    $('#targetLayer').append(data.htmlresponse);
                },
                resetForm: true
            });
        }
        return false;
    });
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<p><b>{{ msg }}</b></p>
{% if filenames %}
	{% for filename in filenames %}
  <div style="padding:20px;float:left;">
    <img width="500" src="/static/uploads/{{ filename }}"> 
  </div>
	{% endfor %}
{% endif %}

SwiftUI Movie Booking Design App UI

SwiftUI Movie Booking Design App UI

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
      
    @State var show = false
    
    var body: some View {
        VStack {
          Home()
          SearchView()
            
          HStack {
            Text("All Movies")
                
            Spacer()
                
            Button(action: {
                    
            }) {
                HStack(spacing: 10) {
                    Text("Filter")
                    Image(systemName: "text.justify.right")
                }
            }.foregroundColor(.black)
          }.padding(.bottom, 15)
            
          Cards()
            
        }.padding()
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Home
 
//
//  Home.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct Home: View {
    
    @State private var selection = 1
    
    var body: some View {
        VStack(spacing: 15) {
            HStack {
                VStack(alignment: .leading, spacing: 15) {
                    Text("Browse").font(.largeTitle)
                    
                    Button(action: {
                        
                    }) {
                        HStack(spacing: 8) {
                            Picker(selection: $selection, label: Text("Movie In")) {
                                Text("Movies in Cinema 1").tag(1)
                                Text("Movies in Cinema 2").tag(2)
                            }
                            Image(systemName: "chevron.down").font(.body)
                        }
                    }
                    .foregroundColor(.black)
                }
                
                Spacer()
                
                Button(action: {
                    
                }) {
                    Image(systemName: "slider.horizontal.3")
                }
                
            }
        }.padding(.top, 15)
    }
}

struct Home_Previews: PreviewProvider {
    static var previews: some View {
        Home()
    }
}
SearchView.swift
 
//
//  SearchView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct SearchView: View {
    @State var txt = ""
    
    var body: some View {
        
        HStack(spacing: 15) {
            Image(systemName: "magnifyingglass").font(.body)
            TextField("Search Movies", text: $txt)
        }
        .padding()
        .foregroundColor(.black)
        .background(Color("Color"))
        .cornerRadius(20)
        //.padding(.vertical, 15)
    }
}

struct SearchView_Previews: PreviewProvider {
    static var previews: some View {
        SearchView()
    }
}
Cards.swift
 
//
//  Cards.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct Cards: View {
    
    @State var show = false
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            VStack(spacing:15) {
                ForEach(datamodel) {rs in
                  
                    ScrollView(.horizontal,showsIndicators: false) {
                        
                        HStack(spacing : 15) {
                            
                            ForEach(rs.row) { i in
                                VStack(alignment: .leading, spacing: 12) {
                                    Image(i.image).renderingMode(.original).resizable().cornerRadius(15)
                                        .onTapGesture {
                                            self.show.toggle()
                                        }
                                    Text(i.name).font(.caption).lineLimit(1)
                                    Text(i.time).font(.caption)
                                }
                                .foregroundColor(Color.black.opacity(0.5))
                                .frame(width: UIScreen.main.bounds.width / 2 - 25, height: 240)
                            }

                        }
                    }
                }
            }
        }
        .padding(.horizontal, 10)
        .sheet(isPresented: $show) {
            Details()
        }
    }
}

struct Cards_Previews: PreviewProvider {
    static var previews: some View {
        Cards()
    }
}
Details.swift
 
//
//  Details.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct Details: View {
    
    @State var selected = ""
    @State var timeselection = ""
    
    var body: some View {
        VStack {
            Image("1").resizable().aspectRatio(1, contentMode: .fill).frame(height:250)
            
            VStack {
                VStack(spacing: 15) {
                    Text("Avengers").foregroundColor(.black)
                    
                    HStack(spacing: 15) {
                        
                        HStack {
                            Image(systemName: "star.fill").font(.caption)
                            Text("4.52")
                        }
                          
                        HStack {
                            Image(systemName: "clock").font(.caption)
                            Text("45 Min")
                        }
                        
                        HStack {
                            Image(systemName: "film").font(.caption)
                            Text("Imax")
                        }
                    }
                    
                    Divider().padding(.vertical, 15)
                    VStack(alignment: .leading) {
                        Text("StoryLine")
                            .background(Color.gray)
                            .foregroundColor(.white)
                            .padding(.bottom, 10)
                        Text("Earth's mightiest heroes must come together and learn to fight as a team if they are going to stop the mischievous Loki and his alien army from enslaving humanity.").font(.caption)
                    }
                }
                .padding()
                .background(Color("Color"))
                .foregroundColor(Color.black.opacity(0.5))
                .cornerRadius(25)
                
                VStack(alignment: .leading) {
                    Text("Date")
                    HStack(spacing: 5) {
                        ForEach(dates) { i in
                            
                            Button(action: {
                                self.selected = i.date
                            }) {
                                VStack(spacing :5) {
                                    Text(i.date)
                                        .font(.system(size: 30, weight: .bold))
                                    Text(i.day)
                                }.padding()
                            }
                            .foregroundColor(Color.white)
                            .background(self.selected == i.date ? Color.blue : Color.gray)
                            .cornerRadius(10)
                        }
                    }
                    .padding(.vertical, 10)
                    
                    Text("Time")
                    HStack(spacing: 5) {
                        ForEach(times) { t in
                            
                            Button(action: {
                                self.timeselection = t.time
                            }) {
                                VStack(spacing :5) {
                                    Text(t.time)
                                }.padding()
                            }
                            .foregroundColor(Color.white)
                            .background(self.timeselection == t.time ? Color.blue : Color.gray)
                            .cornerRadius(10)
                        }
                    }
                    .padding(.vertical, 10)
                }
                

                
                HStack(spacing: 15) {
                    Text("$45")
                    
                    Button(action : {
                        
                    }) {
                        Text("Book Now").padding(.vertical, 15).padding(.horizontal, 15)
                    }
                    .foregroundColor(.white)
                    .background(Color.orange)
                    .clipShape(Capsule())
                }.padding(.top, 15)
                
                Spacer()
            }
            .padding(.horizontal, 25)
            .padding(.top, -35)
        }
    }
}

struct Details_Previews: PreviewProvider {
    static var previews: some View {
        Details()
    }
}
Model.swift
 
//
//  Model.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct type : Identifiable {
    var id : Int
    var row : [row]
}

struct row : Identifiable {
    var id : Int
    var name : String
    var time : String
    var image : String
}

struct datetype : Identifiable {
    var id : Int
    var date : String
    var day : String
}

var datamodel = [type(id: 0, row: [
    row(id: 0, name: "Avengers", time: "1h 12m", image: "1"),
    row(id: 1, name: "Onward", time: "1h 42m", image: "2"),
    row(id: 2, name: "Soul", time: "1h 40m", image: "3"),
]),
type(id: 1, row: [
    row(id: 0, name: "Cruella", time: "1h 12m", image: "4"),
    row(id: 1, name: "Jungle Cruise", time: "1h 42m", image: "5"),
    row(id: 2, name: "The Call of the Wild", time: "1h 40m", image: "6"),
]),
type(id: 2, row: [
    row(id: 0, name: "Joker", time: "1h 12m", image: "7"),
    row(id: 1, name: "Mulan", time: "1h 42m", image: "8"),
    row(id: 2, name: "Mortal Komba", time: "1h 40m", image: "9"),
])]

var dates = [datetype(id: 0, date: "15", day: "01/20"),
             datetype(id: 1, date: "16", day: "01/20"),
             datetype(id: 2, date: "17", day: "01/20"),
             datetype(id: 3, date: "18", day: "01/20")]

struct timetype : Identifiable {
    var id : Int
    var time : String
}

var times = [timetype(id: 0, time: "0:00"),
            timetype(id: 1, time: "1:00"),
            timetype(id: 2, time: "2:00"),
            timetype(id: 3, time: "3:00")]

Sunday, November 14, 2021

SwiftUI Swipe Actions - swipeActions in SwiftUI

SwiftUI Swipe Actions - swipeActions in SwiftUI

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        List{
            ForEach(1...15, id: \.self) { index in
                
                Text("List \(index)")
                    .swipeActions(edge: .leading) {
                    Button {
                            //action
                    } label: {
                        if index % 2 == 0 {
                            Label("Read", systemImage: "envelope.open")
                        }else {
                            Label("Unread", systemImage: "envelope.badge")
                        }
                    }
                }
                    .swipeActions(edge: .trailing) {
                        Button(role: .destructive) {
                            //action
                        } label: {
                            Label("Delete", systemImage: "trash")
                        }
                        Button {
                            //action
                        } label: {
                            Label("Flag", systemImage: "flag")
                        }
                    }
            }//end foreach
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Python Flask Upload multiple images and display multiple images uploaded

Python Flask Upload multiple images and display multiple images uploaded

app.py
//app.py
from flask import Flask, flash, request, redirect, url_for, render_template
import urllib.request
import os
from werkzeug.utils import secure_filename
import urllib.request

app = Flask(__name__)
 
UPLOAD_FOLDER = 'static/uploads/'

app = Flask(__name__)
app.secret_key = "cairocoders-ednalan"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
	
@app.route('/')
def upload_form():
	return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_image():
	if 'files[]' not in request.files:
		flash('No file part')
		return redirect(request.url)
	files = request.files.getlist('files[]')
	file_names = []
	for file in files:
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file_names.append(filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
		else:
			flash('Allowed image types are -> png, jpg, jpeg, gif')
			return redirect(request.url)

	return render_template('upload.html', filenames=file_names)

@app.route('/display/<filename>')
def display_image(filename):
	#print('display_image filename: ' + filename)
	return redirect(url_for('static', filename='uploads/' + filename), code=301)
 
if __name__ == "__main__":
    app.run()
templates/upload.html
//templates/upload.html
<html>
<head>
<title>Python Flask Upload multiple images and display multiple images uploaded</title>
</head>
<body>
<div style="padding:20px;">
<h2>Python Flask Upload multiple images and display multiple images uploaded</h2>
<p>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul class=flashes>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
		</ul>
	  {% endif %}
	{% endwith %}
</p>
<form method="post" action="/" enctype="multipart/form-data">
    <dl>
		<p>
			<input type="file" name="files[]" multiple="true" autocomplete="off" required>
		</p>
    </dl>
    <p>
		<input type="submit" value="Submit">
	</p>
</form>

{% if filenames %}
	{% for filename in filenames %}
		<div style="padding:20px;float:left;">
			<img width="500" src="{{ url_for('display_image', filename=filename) }}"> 
		</div>
	{% endfor %}
{% endif %}
</div>
</body>
</html>

Saturday, November 13, 2021

AngularJS CRUD (Create, Read, Update and Delete) with PHP Mysql

AngularJS CRUD (Create, Read, Update and Delete) with PHP Mysql

This tutorial used CDN for Bootstrap, Angular JS

index.html
//index.html
<!DOCTYPE html>  
<html>  
<head>  
<title>AngularJS CRUD with PHP Mysql</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
</head>  
<body>  
<br /><br />  
<div class="container" style="width:600px;">  
	<h3 align="center">AngularJS CRUD (Create, Read, Update and Delete) with PHP Mysql</h3>  
    <div ng-app="angularcrud" ng-controller="usercontroller" ng-init="displayData()">  
        <label>Name</label>  
        <input type="text" name="txtname" ng-model="txtname" class="form-control" />  
        <br />  
        <label>User Name</label>  
        <input type="text" name="txtusername" ng-model="txtusername" class="form-control" />  
        <br />  
		<input type="hidden" name="txtid" ng-model="id" /> 
        <input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="{{btnName}}"/>  
        <br /><br />  
		
        <table class="table table-bordered">  
            <tr>  
                <th>Name</th>  
                <th>User Name</th>  
                <th>Update</th>  
                <th>Delete</th>  
            </tr>  
            <tr ng-repeat="x in names">  
                <td>{{x.fullname}}</td>  
                <td>{{x.username}}</td>  
                <td><button ng-click="updateData(x.userid, x.fullname, x.username)" class="btn btn-info btn-xs">Update</button></td>  
                <td><button ng-click="deleteData(x.userid )"class="btn btn-danger btn-xs">Delete</button></td>  
            </tr>  
        </table>  
    </div>  
</div> 
<script>  
 var app = angular.module("angularcrud",[]);  
 app.controller("usercontroller", function($scope, $http){  
      $scope.btnName = "ADD";  
      $scope.id = 0;  
      $scope.insertData = function(){  
           if($scope.txtname == null)  
           {  
                alert("Name is required");  
           }  
           else if($scope.txtusername == null)  
           {  
                alert("Username is required");  
           }  
           else  
           {  
				$http.post(  
                     "insert_update.php",  
                     {'txtname':$scope.txtname, 'txtusername':$scope.txtusername, 'txtid':$scope.id, 'btnName':$scope.btnName}  
                ).success(function(data){  
                     alert(data);  
                     $scope.txtname = null;  
                     $scope.txtusername = null;  
                     $scope.txtid = null;  
                     $scope.btnName = "ADD";  
                     $scope.displayData();  
                });  
           }  
      }  
      $scope.displayData = function(){  
           $http.get("list.php")  
           .success(function(data){  
                $scope.names = data;  
           });  
      }  
      $scope.updateData = function(id, fullname, username){  
           $scope.id = id;  
           $scope.txtname = fullname;  
           $scope.txtusername = username;  
           $scope.btnName = "Update";  
      }  
      $scope.deleteData = function(id){  
           if(confirm("Are you sure you want to delete this data?"))  
           {  
                $http.post("delete.php", {'id':id})  
                .success(function(data){  
                     alert(data);  
                     $scope.displayData();  
                });  
           }  
           else  
           {  
                return false;  
           }  
      }  
 });  
</script>  		   
</body>  
</html>  
db.php
//db.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>
list.php
//list.php
<?php  
include('db.php');

$query = "SELECT * FROM tbl_user ORDER BY userid DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}

?>
insert_update.php
//insert_update.php
<?php
include('db.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));
 
if ($form_data->txtid == '0') {

	$data = array(
	 ':txtname'  => $form_data->txtname,
	 ':txtusername'  => $form_data->txtusername
	); 
		
	$query = "
	 INSERT INTO tbl_user 
	 (fullname, username) VALUES 
	 (:txtname, :txtusername)
	";

	$statement = $connect->prepare($query);

	if($statement->execute($data))
	{
	 $message = 'Data Inserted';
	}else {
	 $message = 'Error';	
	}	
}else {
	
	$data = array(
	 ':txtname'  => $form_data->txtname,
	 ':txtusername'  => $form_data->txtusername,
	 ':txtid'  => $form_data->txtid
	); 
	
	$query = "
	 UPDATE tbl_user 
	 SET fullname = :txtname, username = :txtusername 
	 WHERE userid = :txtid
	";

	$statement = $connect->prepare($query);
	if($statement->execute($data))
	{
	 $message = 'Data Edited';
	}
}	
echo $message; 
?>
delete.php
//delete.php
<?php
include('db.php');

$message = '';

$data = json_decode(file_get_contents("php://input"));
$id = $data->id;  
$query = "DELETE FROM tbl_user WHERE userid='$id'";  

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}else{
  $message = 'Error';	
}	
echo $message;
?>

AngularJS Login with PHP MySQLi

AngularJS Login with PHP MySQLi

This tutorial used CDN for Bootstrap, Angular JS and Angular Route

CREATE TABLE `tbl_user` (
  `userid` int(11) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `tbl_user` (`userid`, `fullname`, `username`, `email`, `password`) VALUES
(1, 'cairocoder Ednalan', 'cairocoders', '', '123456'),
(2, 'tutorial101', 'tutorial101', '', '123456');

ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `tbl_user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
index.html
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS Login with PHP MySQLi</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
  <h1 class="page-header text-center">AngularJS Login with PHP MySQLi</h1>
  <div ng-view></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script src="js/angular.js"></script>
<script src="js/controllers/loginCtrl.js"></script>
<script src="js/services/loginService.js"></script>
</body>
</html>
login.html
//login.html
<div class="col-md-4 col-md-offset-4">
    <div class="login-panel panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
            </h3>
        </div>
    	<div class="panel-body">
        	<form role="form" name="logform">
            	<fieldset> sdfsdfsf
                	<div class="form-group">
                    	<input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
                	</div>
                	<div class="form-group">
                    	<input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
                	</div>
                	<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block" ng-disabled="logform.$invalid" ng-click="login(user)"><span class="glyphicon glyphicon-log-in"></span> <span id="logtext">Login</span></button>
            	</fieldset>
        	</form>
    	</div>
    </div>

    <div class="alert alert-danger text-center" ng-show="errorLogin">
        <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
        {{ errorMsg }}
    </div>

    <div class="alert alert-success text-center" ng-show="successLogin">
        <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
        {{ successMsg }}
    </div>
</div>
angular.js
//angular.js
var app = angular.module('app', ['ngRoute']); //Routing - ngRoute module helps your application to become a Single Page Application.

app.config(function($routeProvider){
	$routeProvider
	.when('/', {
		templateUrl: 'login.html',
		controller: 'loginCtrl'
	})
	.when('/home', {
		templateUrl: 'home.html'
	})
	.otherwise({
		redirectTo: '/'
	});
});
js/services/loginService.js
//js/services/loginService.js
'use strict';

app.factory('loginService', function($http){
	return{
		login: function(user, $scope){
			var validate = $http.post('login.php', user);
			validate.then(function(response){
				if(response.data.error == true){
					$scope.successLogin = false;
					$scope.errorLogin = true;
					$scope.errorMsg = response.data.message;
				}
				else{
					$scope.errorLogin = false;
					$scope.successLogin = true;
					$scope.successMsg = response.data.message;
                    setTimeout(function(){
						window.location.href="http://localhost/devtest/angularjs/angularlogin/#/home";
					},2000);
				}
			});
		}
	}
});
js/controller/loginCtrl.js
//js/controller/loginCtrl.js
'use strict';

app.controller('loginCtrl', function($scope, loginService){
	$scope.errorLogin = false;
	$scope.successLogin = false;

	$scope.login = function(user){
		loginService.login(user, $scope);
	}

	$scope.clearMsg = function(){
		$scope.errorLogin = false;
		$scope.successLogin = false;
	}
});
login.php
//login.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$out = array('error' => false);

$user = json_decode(file_get_contents('php://input'));

$username = $user->username;
$password = $user->password;

$sql = "SELECT * FROM tbl_user WHERE username='$username' AND password='$password'";
$query = $conn->query($sql);

if($query->num_rows>0){
	$out['message'] = 'Login Successful';
}
else{
	$out['error'] = true;
	$out['message'] = 'Invalid Login';
}

echo json_encode($out);
?>

Vue.js Axios Live Search using PHP Mysqli

Vue.js Axios Live Search using PHP Mysqli

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `position` varchar(100) NOT NULL,
  `office` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`id`, `name`, `position`, `office`, `age`, `salary`) VALUES
(1, 'Tiger Wood', 'Accountant', 'Tokyo', 36, 5689),
(2, 'Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648),
(3, 'Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689),
(4, 'cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654),
(5, 'Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465),
(6, 'Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465),
(8, 'Tiger Nixon', 'Software Engineer', 'London', 45, 456),
(9, 'Airi Satou updated', 'Pre-Sales Support updated', 'New York', 25, 4568),
(10, 'Angelica Ramos updated', 'Sales Assistant updated', 'New York', 45, 456),
(11, 'Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565),
(12, 'Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485),
(13, 'Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468),
(14, 'Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685),
(15, 'Bruno Nash', 'Customer Support', 'New York', 36, 65465),
(16, 'cairocoders', 'Sales Assistant', 'Sydney', 45, 56465),
(17, 'Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548),
(18, 'Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545),
(19, 'Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468),
(20, 'Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646),
(21, 'Shad Decker', 'Regional Director', 'Tokyo', 45, 4545);

ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Axios Live Search using PHP Mysqli</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div id="vueappsearch">
	<div class="container">
		<h1 class="page-header text-center">Vue.js Axios Live Search using PHP Mysqli</h1>
		<div class="col-md-8 col-md-offset-2">
			<div class="row">
				<div class="col-md-4 col-md-offset-8">
					<input type="text" class="form-control" placeholder="Search Name or Position" v-on:keyup="searchMonitor" v-model="search.keyword">
				</div>
			</div>
			<div style="height:5px;"></div>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Name</th>
					<th>Position</th>
					<th>Office</th>
					<th>Age</th>
					<th>Salary</th>
				</thead>
				<tbody>
					
					<tr v-if="noMember">
						<td colspan="2" align="center">No member match your search</td>
					</tr>
					
					<tr v-for="member in employee">
						<td>{{ member.name }}</td>
						<td>{{ member.position }}</td>
						<td>{{ member.office }}</td>
						<td>{{ member.age }}</td>
						<td>{{ member.salary }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="vuesearchapp.js"></script>
</body>
</html>
vuesearchapp.js
//vuesearchapp.js
var app = new Vue({
	el: '#vueappsearch',
	data:{
		employee: [],
		search: {keyword: ''},
		noMember: false
	},

	mounted: function(){
		this.fetchemployee();
	},

	methods:{
		searchMonitor: function() {
			var keyword = app.toFormData(app.search);
	   		axios.post('action.php?action=search', keyword)
				.then(function(response){
					app.employee = response.data.employee;

					if(response.data.employee == ''){
						app.noMember = true;
					}
					else{
						app.noMember = false;
					}
				});
       	},

       	fetchemployee: function(){
			axios.post('action.php')
				.then(function(response){
					app.employee = response.data.employee;
				});
       	},

		toFormData: function(obj){
			var form_data = new FormData();
			for(var key in obj){
				form_data.append(key, obj[key]);
			}
			return form_data;
		},

	}
});
action.php
//action.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$out = array('error' => false);

$action="show";

if(isset($_GET['action'])){
	$action=$_GET['action'];
}

if($action=='show'){
	$sql = "select * from employee";
	$query = $conn->query($sql);
	$employee = array();

	while($row = $query->fetch_array()){
		array_push($employee, $row);
	}

	$out['employee'] = $employee;
}

if($action=='search'){
	$keyword=$_POST['keyword'];
	$sql="select * from employee where name like '%$keyword%' or position like '%$keyword%'";
	$query = $conn->query($sql);
	$employee = array();

	while($row = $query->fetch_array()){
		array_push($employee, $row);
	}

	$out['employee'] = $employee;
}

$conn->close();

header("Content-type: application/json");
echo json_encode($out);
die();
?>

Vue.js Axios Login with PHP MySQLi

Vue.js Axios Login with PHP MySQLi

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

CREATE TABLE `vueuser` (
  `id` int(11) NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `vueuser` (`id`, `username`, `password`) VALUES
(1, 'cairocoders', '123456'),
(2, 'tutorial101.blogspot.com', '1234567');

ALTER TABLE `vueuser`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `vueuser`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:success.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios Login with PHP MySQLi</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">Vue.js Axios Login with PHP MySQLi</h1>
	<div id="vueapplogin">
		<div class="col-md-4 col-md-offset-4">
			<div class="panel panel-primary">
			  	<div class="panel-heading"><span class="glyphicon glyphicon-lock"></span> Sign in</div>
			  	<div class="panel-body">
			    	<label>Username:</label>
			    	<input type="text" class="form-control" v-model="logDetails.username" v-on:keyup="keymonitor">
			    	<label>Password:</label>
			    	<input type="password" class="form-control" v-model="logDetails.password" v-on:keyup="keymonitor">
			  	</div>
			  	<div class="panel-footer">
			  		<button class="btn btn-primary btn-block" @click="checkLogin();"><span class="glyphicon glyphicon-log-in"></span> Login</button>
			  	</div>
			</div>

			<div class="alert alert-danger text-center" v-if="errorMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-alert"></span> {{ errorMessage }}
			</div>

			<div class="alert alert-success text-center" v-if="successMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-check"></span> {{ successMessage }}
			</div>

		</div>
	</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="applogin.js"></script>
</body>
</html>
applogin.js
//applogin.js
var app = new Vue({
	el: '#vueapplogin',
	data:{
		successMessage: "",
		errorMessage: "",
		logDetails: {username: '', password: ''},
	},

	methods:{
		keymonitor: function(event) {
       		if(event.key == "Enter"){
         		app.checkLogin();
        	}
       	},

		checkLogin: function(){
			var logForm = app.toFormData(app.logDetails);
			axios.post('login.php', logForm)
				.then(function(response){

					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message;
						app.logDetails = {username: '', password:''};
						setTimeout(function(){
							window.location.href="success.php";
						},2000);
						
					}
				});
		},

		toFormData: function(obj){
			var form_data = new FormData();
			for(var key in obj){
				form_data.append(key, obj[key]);
			}
			return form_data;
		},

		clearMessage: function(){
			app.errorMessage = '';
			app.successMessage = '';
		}

	}
});
login.php
//login.php
<?php
session_start();
include('dbcon.php');

$out = array('error' => false);

$username = $_POST['username'];
$password = $_POST['password'];

if($username==''){
	$out['error'] = true;
	$out['message'] = "Username is required";
}
else if($password==''){
	$out['error'] = true;
	$out['message'] = "Password is required";
}
else{
	$sql = "select * from vueuser where username='$username' and password='$password'";
	$query = $conn->query($sql);

	if($query->num_rows>0){
		$row=$query->fetch_array();
		$_SESSION['user']=$row['id'];
		$out['message'] = "Login Successful";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Login Failed. User not Found";
	}
}
	
$conn->close();

header("Content-type: application/json");
echo json_encode($out);
die();
?>
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
success.php
//success.php
<?php
	session_start();
	include('dbcon.php');

	if (!isset($_SESSION['user']) ||(trim ($_SESSION['user']) == '')){
		header('location:index.php');
	}

	$sql="select * from vueuser where id='".$_SESSION['user']."'";
	$query=$conn->query($sql);
	$row=$query->fetch_array();

?>
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios Login with PHP MySQLi</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<div class="jumbotron">
			<h1 class="text-center">Welcome, <?php echo $row['username']; ?>!</h1>
			<a href="logout.php" class="btn btn-primary"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
		</div>
	</div>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>

Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi

Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi

Download or Include 

axios
https://github.com/axios/axios

Using jsDelivr CDN: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

VueJS 
https://vuejs.org/v2/guide/installation.html

CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

CREATE TABLE `members` (
  `memid` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`memid`, `firstname`, `lastname`) VALUES
(2, 'Airi', 'Satou'),
(3, 'Angelica', 'Ramos'),
(4, 'Ashton', 'Cox'),
(5, 'Bradley', 'Greer'),
(6, 'Brenden', 'Wagner');

ALTER TABLE `members`
  ADD PRIMARY KEY (`memid`);

ALTER TABLE `members`
  MODIFY `memid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">Vue.js Axios CRUD (Create, Read, Update and Delete) using PHP MySQLi</h1>
	<div id="vuejscrudmembers">
		<div class="col-md-8 col-md-offset-2">
			<div class="row">
				<div class="col-md-12">
					<h2>Member List
					<button class="btn btn-primary pull-right" @click="showAddModal = true"><span class="glyphicon glyphicon-plus"></span> Member</button>
					</h2>
				</div>
			</div>

			<div class="alert alert-danger text-center" v-if="errorMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-alert"></span> {{ errorMessage }}
			</div>
			
			<div class="alert alert-success text-center" v-if="successMessage">
				<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-ok"></span> {{ successMessage }}
			</div>

			<table class="table table-bordered table-striped">
				<thead>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Action</th>
				</thead>
				<tbody>
					<tr v-for="member in members">
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
						<td>
							<button class="btn btn-success" @click="showEditModal = true; selectMember(member);"><span class="glyphicon glyphicon-edit"></span> Edit</button> 
							<button class="btn btn-danger" @click="showDeleteModal = true; selectMember(member);"><span class="glyphicon glyphicon-trash"></span> Delete</button>
						</td>
					</tr>
				</tbody>
			</table>
		</div>
		<?php include('modal.php'); ?>
	</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
var app = new Vue({
	el: '#vuejscrudmembers',
	data:{
		showAddModal: false,
		showEditModal: false,
		showDeleteModal: false,
		errorMessage: "",
		successMessage: "",
		members: [],
		newMember: {firstname: '', lastname: ''},
		clickMember: {}
	},

	mounted: function(){
		this.getAllMembers();
	},

	methods:{
		getAllMembers: function(){
			axios.get('api.php')
				.then(function(response){
					//console.log(response);
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.members = response.data.members;
					}
				});
		},

		saveMember: function(){
			//console.log(app.newMember);
			var memForm = app.toFormData(app.newMember);
			axios.post('api.php?crud=create', memForm)
				.then(function(response){
					//console.log(response);
					app.newMember = {firstname: '', lastname:''};
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message
						app.getAllMembers();
					}
				});
		},

		updateMember(){
			var memForm = app.toFormData(app.clickMember);
			axios.post('api.php?crud=update', memForm)
				.then(function(response){
					//console.log(response);
					app.clickMember = {};
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message
						app.getAllMembers();
					}
				});
		},

		deleteMember(){
			var memForm = app.toFormData(app.clickMember);
			axios.post('api.php?crud=delete', memForm)
				.then(function(response){
					//console.log(response);
					app.clickMember = {};
					if(response.data.error){
						app.errorMessage = response.data.message;
					}
					else{
						app.successMessage = response.data.message
						app.getAllMembers();
					}
				});
		},

		selectMember(member){
			app.clickMember = member;
		},

		toFormData: function(obj){
			var form_data = new FormData();
			for(var key in obj){
				form_data.append(key, obj[key]);
			}
			return form_data;
		},

		clearMessage: function(){
			app.errorMessage = '';
			app.successMessage = '';
		}

	}
});
api.php
//api.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$out = array('error' => false);

$crud = 'read';

if(isset($_GET['crud'])){
	$crud = $_GET['crud'];
}


if($crud == 'read'){
	$sql = "select * from members";
	$query = $conn->query($sql);
	$members = array();

	while($row = $query->fetch_array()){
		array_push($members, $row);
	}

	$out['members'] = $members;
}

if($crud == 'create'){

	$firstname = $_POST['firstname'];
	$lastname = $_POST['lastname'];

	$sql = "insert into members (firstname, lastname) values ('$firstname', '$lastname')";
	$query = $conn->query($sql);

	if($query){
		$out['message'] = "Member Added Successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Could not add Member";
	}
	
}

if($crud == 'update'){

	$memid = $_POST['memid'];
	$firstname = $_POST['firstname'];
	$lastname = $_POST['lastname'];

	$sql = "update members set firstname='$firstname', lastname='$lastname' where memid='$memid'";
	$query = $conn->query($sql);

	if($query){
		$out['message'] = "Member Updated Successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Could not update Member";
	}
	
}

if($crud == 'delete'){

	$memid = $_POST['memid'];

	$sql = "delete from members where memid='$memid'";
	$query = $conn->query($sql);

	if($query){
		$out['message'] = "Member Deleted Successfully";
	}
	else{
		$out['error'] = true;
		$out['message'] = "Could not delete Member";
	}
	
}


$conn->close();

header("Content-type: application/json");
echo json_encode($out);
die();
?>
modal.php
//modal.php
<!-- Add Modal -->
<div class="myModal" v-if="showAddModal">
	<div class="modalContainer">
		<div class="modalHeader">
			<span class="headerTitle">Add New Member</span>
			<button class="closeBtn pull-right" @click="showAddModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Firstname:</label>
				<input type="text" class="form-control" v-model="newMember.firstname">
			</div>
			<div class="form-group">
				<label>Lastname:</label>
				<input type="text" class="form-control" v-model="newMember.lastname">
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" @click="showAddModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-primary" @click="showAddModal = false; saveMember();"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Edit Modal -->
<div class="myModal" v-if="showEditModal">
	<div class="modalContainer">
		<div class="editHeader">
			<span class="headerTitle">Edit Member</span>
			<button class="closeEditBtn pull-right" @click="showEditModal = false">×</button>
		</div>
		<div class="modalBody">
			<div class="form-group">
				<label>Firstname:</label>
				<input type="text" class="form-control" v-model="clickMember.firstname">
			</div>
			<div class="form-group">
				<label>Lastname:</label>
				<input type="text" class="form-control" v-model="clickMember.lastname">
			</div>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" @click="showEditModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-success" @click="showEditModal = false; updateMember();"><span class="glyphicon glyphicon-check"></span> Save</button>
			</div>
		</div>
	</div>
</div>

<!-- Delete Modal -->
<div class="myModal" v-if="showDeleteModal">
	<div class="modalContainer">
		<div class="deleteHeader">
			<span class="headerTitle">Delete Member</span>
			<button class="closeDelBtn pull-right" @click="showDeleteModal = false">×</button>
		</div>
		<div class="modalBody">
			<h5 class="text-center">Are you sure you want to Delete</h5>
			<h2 class="text-center">{{clickMember.firstname}} {{clickMember.lastname}}</h2>
		</div>
		<hr>
		<div class="modalFooter">
			<div class="footerBtn pull-right">
				<button class="btn btn-default" @click="showDeleteModal = false"><span class="glyphicon glyphicon-remove"></span> Cancel</button> <button class="btn btn-danger" @click="showDeleteModal = false; deleteMember(); "><span class="glyphicon glyphicon-trash"></span> Yes</button>
			</div>
		</div>
	</div>
</div>
style.css
//style.css
.myModal{
	position:fixed;
	top:0;
	left:0;
	right:0;
	bottom:0;
	background: rgba(0, 0, 0, 0.4);
}

.modalContainer{
	width: 555px;
	background: #FFFFFF;
	margin:auto;
	margin-top:50px;
}

.modalHeader{
	padding:10px;
	background: #008CBA;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.editHeader{
	padding:10px;
	background: #4CAF50;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.deleteHeader{
	padding:10px;
	background: #f44336;
	color: #FFFFFF;
	height:50px;
	font-size:20px;
	padding-left:15px;
}

.modalBody{
	padding:40px;
}

.modalFooter{
	height:36px;
}

.footerBtn{
	margin-right:10px;
	margin-top:-9px;
}

.closeBtn{
	background: #008CBA;
	color: #FFFFFF;
	border:none;
}

.closeEditBtn{
	background: #4CAF50;
	color: #FFFFFF;
	border:none;
}

.closeDelBtn{
	background: #f44336;
	color: #FFFFFF;
	border:none;
}

Thursday, November 11, 2021

SwiftUI Customization TabView with Tab Bar

SwiftUI Customization TabView with Tab Bar

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var selection = 0
    
    var body: some View {
        ZStack(alignment: .topTrailing) {
            NavigationView {
                TabView(selection: $selection) {
                    
                    Home()
                        .tabItem {
                            Image(systemName: "house.fill")
                            Text("Home")
                        }
                        .tag(0)
                 
                    Text("Bookmark Tab")
                        .font(.system(size: 30, weight: .bold, design: .rounded))
                        .tabItem {
                            Image(systemName: "bookmark.circle.fill")
                            Text("Bookmark")
                        }
                        .tag(1)
                 
                    Text("Video Tab")
                        .font(.system(size: 30, weight: .bold, design: .rounded))
                        .tabItem {
                            Image(systemName: "video.circle.fill")
                            Text("Video")
                        }
                        .tag(2)
                 
                    Text("Profile Tab")
                        .font(.system(size: 30, weight: .bold, design: .rounded))
                        .tabItem {
                            Image(systemName: "person.crop.circle")
                            Text("Profile")
                        }
                        .tag(3)
                } //end tabview
                .onAppear() {
                    UITabBar.appearance().barTintColor = .white
                }
                .accentColor(.orange) //Tab Bar Color
                
                
                .navigationTitle("TabView Demo")
                .navigationBarItems(leading:
                    HStack {
                         Button(action: {
                             selection = (selection + 1) % 4
                         }) {
                             Text("Next")
                                 .font(.system(.headline, design: .rounded))
                                 .padding()
                                 .foregroundColor(.white)
                                 .background(Color.green)
                                 .cornerRadius(10.0)
                                 .padding()
                         }
                    }
                )
            }// end NavigationView
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Home.swift
 
//
//  Home.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct Home: View {
    var body: some View {
        List(1...50, id: \.self) { index in
            NavigationLink(
                destination: Text("Item #\(index) Details"),
                label: {
                    Text("Item #\(index)")
                        .font(.system(size: 20, weight: .bold, design: .rounded))
                })
 
        }
    }
}

struct Home_Previews: PreviewProvider {
    static var previews: some View {
        Home()
    }
}

Wednesday, November 10, 2021

SwiftUI Fashion Shop App UI Design

SwiftUI Fashion Shop App UI Design

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        
        NavigationView{
            ZStack(alignment: .leading) {
                TabView{
                    MainView().tabItem {
                    
                        Image(systemName: "house").font(.title)
                    }
                     
                    Text("Discover").tabItem {
                        Image(systemName: "magnifyingglass").font(.title)
                    }
                     
                    Text("Favorites").tabItem {
                        Image(systemName: "suit.heart").font(.title)
                    }
                     
                    Text("Alert").tabItem {
                        Image(systemName: "bell").font(.title)
                    }
                }.accentColor(.red)
                .edgesIgnoringSafeArea(.top)
            }
            .navigationBarTitle(Text(""), displayMode: .inline)
            .navigationBarItems(leading:
                HStack {
                    Button(action: {
                        withAnimation {
                           
                        }
                        print("Open the side menu")
                    }) {
                        Image("photo1").resizable().frame(width: 35, height: 35).clipShape(Circle())
                    }
                 
                    Text("Home").font(.title)
                }
                ,trailing:
                    HStack(spacing: 18){
                                        
                        Button(action: {
                        }) {
                           Image(systemName: "magnifyingglass")
                        }
                                        
                        Button(action: {
                        }) {
                            Image(systemName: "bell")
                        }
                                        
                        Button(action: {
                        }) {
                           Image(systemName: "cart")
                        }
                     }
            )
        }// End Navigation
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
MainView.swift
 
//
//  MainView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct MainView : View {
    
    @State var selected = "Dress"
    @State private var selection = 1
    var body : some View{
        
        VStack(alignment: .leading,spacing: 12){
            HStack{
                
                HStack{
                    
                    
                    Button(action: {
                        
                    }) {
                        
                        HStack{
                            
                            Picker(selection: $selection, label: Text("Category")) {
                                 Text("Casual Dress").tag(1)
                                 Text("Pants").tag(2)
                            }.foregroundColor(.black)
                            .background(Color.white)
                            .font(.title)
                            
                            Spacer()
                            
                            Image(systemName: "arrow.down.circle")
                            
                        }.padding()
                        
                    }.foregroundColor(.black)
                    .background(Color.white)
                    
                    
                    Button(action: {
                        
                        
                    }) {
                        
                        Image(systemName: "slider.vertical.3")
                        
                    }.background(Color.white)
                }
            }
            
            HStack{
                
                ForEach(types,id: \.self){ i in
                    
                    HStack{
                        
                        Button(action: {
                            
                            self.selected = i
                            
                        }) {
                            
                            Text(i).padding()
                        }
                        .foregroundColor(self.selected == i ? .white : .black)
                        .background(self.selected == i ? Color.black : Color.clear)
                        .cornerRadius(10)
                        
                        Spacer(minLength: 0)
                        
                    }
                }
            }
            
            DetailsScroll()
            
        }.padding()
        .background(Color("Color"))
        .animation(.spring())
        
    }
}

struct MainView_Previews: PreviewProvider {
    static var previews: some View {
        MainView()
    }
}
DetailsScroll.swift
 
//
//  DetailsScroll.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct DetailsScroll : View {
    
    @State var show = false
    
    var body : some View{
        
        ScrollView(.vertical, showsIndicators: false) {
            
            VStack(spacing: 12){
                
                ForEach(datas){i in
                    
                    HStack{
                        
                        ForEach(i.rows){j in
                            
                            Cards(row: j)
                        }
                    }
                }
            }
        }
    }
}

struct DetailsScroll_Previews: PreviewProvider {
    static var previews: some View {
        DetailsScroll()
    }
}
Cards.swift
 
//
//  Cards.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct Cards : View {
    
    var row : row
    @State var show  = false
    
    
    var body : some View{
        
        VStack(spacing: 8){
            
            NavigationLink(destination: DetailView(show: $show), isActive: $show) {
                
                Image(row.image).renderingMode(.original).resizable().frame(width: UIScreen.main.bounds.width / 2 - 25, height: 240)
            }
            
           
            
            HStack{
                
                VStack(alignment: .leading, spacing: 10){
                    
                    Text(row.name)
                    Text(row.price).fontWeight(.heavy)
                    
                }
                
                Spacer()
                
                Button(action: {
                    
                }) {
                    
                    Image(systemName: "text.redaction")
                    
                }.padding(.trailing, 15)
            }
        }
    }
}

struct Cards_Previews: PreviewProvider {
    static var previews: some View {
        Cards(row: row(id: 1, name: "Test", price: "$199", image: "details"))
    }
}
DetailView.swift
 
//
//  DetailView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct DetailView : View {
    
    @Binding var show : Bool
    @State var size = ""
    
    var body : some View{
        
        VStack(spacing : 0){
            
            HStack(spacing: 18){
                
                Button(action: {
                    
                    self.show.toggle()
                    
                }) {
                    
                    Image(systemName: "arrow.left")
                }
                
                Spacer()
                
                Button(action: {
                    
                }) {
                    
                    Image(systemName: "magnifyingglass")
                }
                
                Button(action: {
                    
                }) {
                    
                    Image(systemName: "cart")
                }

            }.navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            .padding(15)
                
            
            Image("dress4").resizable()
            
            VStack(alignment: .leading ,spacing: 15){
                
                HStack{
                    
                    VStack(alignment: .leading, spacing: 8){
                        
                        Text("Dresses Slimfit").font(.largeTitle)
                        Text("$199.99").fontWeight(.heavy)
                    }
                    
                    Spacer()
                    
                    HStack(spacing: 10){
                        
                        Circle().fill(Color.green).frame(width: 20, height: 20)
                        Circle().fill(Color.blue).frame(width: 20, height: 20)
                        Circle().fill(Color.red).frame(width: 20, height: 20)
                    }
                }

                
                Text("Fitted top made from a polyamide blend. Features wide straps and chest reinforcement.")
                
                
                
                Text("Select Size")
                
                HStack{
                    
                    ForEach(sizes,id: \.self){i in
                        
                        Button(action: {
                            
                            self.size = i
                            
                        }) {
                            
                            Text(i).padding().border(Color.black, width: self.size == i ? 1.5 : 0)
                            
                        }.foregroundColor(.black)
                    }
                }

                
                HStack{
                    
                    Button(action: {
                        
                    }) {
                        
                        Text("Add To Cart").padding().border(Color.black, width: 1.4)
                        
                    }.foregroundColor(.black)
                    
                    Spacer()
                    
                    Button(action: {
                        
                    }) {
                        
                        Text("Buy Now").padding()
                        
                    }.foregroundColor(.white)
                    .background(Color.black)
                    .cornerRadius(10)
                    
                }.padding([.leading,.trailing], 15)
                .padding(.top, 15)
                
            }.padding()
            .background(rounded().fill(Color.white))
            .padding(.top, -50)
            
        }
    }
}

struct DetailView_Previews: PreviewProvider {
    @State static var show = false
    
    static var previews: some View {
        DetailView(show: $show)
    }
}

struct rounded : Shape {
    
    func path(in rect: CGRect) -> Path {
    
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft,.topRight], cornerRadii: CGSize(width: 35, height: 35))
        
        return Path(path.cgPath)
    }
}
Model.swift
 
//
//  Model.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct type : Identifiable{
    
    var id : Int
    var rows : [row]
}

struct row : Identifiable {
    
    var id : Int
    var name : String
    var price : String
    var image : String
   
}

var sizes = ["S","M","X","XL"]

var types = ["Dress","Pants","Blazers","Jackets"]

var datas = [
    
    type(id: 0,rows: [row(id:0,name: "Trendy Sexsy", price: "$56", image: "dress1"),
                      row(id:1,name: "Floral Smock", price: "$120", image: "dress2")]),

    type(id: 2,rows: [row(id:0,name: "Backless Dress", price: "$136", image: "dress3"),
                      row(id:1,name: "Dresses Slimfit", price: "$150", image: "dress4")]),
]

ReactJS Datepicker using React Flatpickr

ReactJS Datepicker using React Flatpickr

React datepicker Flatpikr https://flatpickr.js.org/

Flatpickr is a lightweight, UX-driven JavaScript library with Angular, Vue, Ember, and React compatibility. 

Install React Datepicker

install the react-flatpickr
C:\reactdev\myreactdev>install the react-flatpickr
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_orange.css"; //material_green.css, material_blue.css, material_red.css, material_orange.css, dark.css

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  render() {
    const { date } = this.state;
    return (
      <div style={{ padding: 20 }}><h2>ReactJS Datepicker using React Flatpickr</h2>
            <div >
                <Flatpickr
                    data-enable-time
                    value={date}
                    onChange={date => {
                    this.setState({ date });
                    }}
                />
            </div>
            <div>
                <h3>React Flatpickr: minDate</h3>
                <Flatpickr
                    data-enable-time
                    value={date}
                    options={{
                        minDate: 'today',
                        }}
                    onChange={date => {
                    this.setState({ date });
                    }}
                />
            </div>
            <div>
                <h3>React Flatpickr: minTime</h3>
                <Flatpickr
                    data-enable-time
                    value={date}
                    options={{
                        minTime: "08:00",
                        }}
                    onChange={date => {
                    this.setState({ date });
                    }}
                />
            </div>
            <div>
                <h3>React Flatpickr: maxTime</h3>
                <Flatpickr
                  data-enable-time
                  value={date}
                  options={{
                        maxTime: "17:00",
                      }}
                  onChange={date => {
                    this.setState({ date });
                  }}
                />
            </div>
            <div>
                <h3>React Flatpickr: altFormat</h3>
                <Flatpickr
                  data-enable-time
                  value={date}
                  options={{
                        altFormat: "m/d/Y h:i K",
                        altInput:true,
                      }}
                  onChange={date => {
                    this.setState({ date });
                  }}
                />
            </div>
            <div>
                <h3>React Flatpickr: Disable certain day of the week</h3>
                <Flatpickr
                  data-enable-time
                  value={date}
                  options={{
                        disable: [
                        function(date) {
                            // return true to disable
                            return (date.getDay() === 0 || date.getDay() === 6);}],
                      }}
                  onChange={date => {
                    this.setState({ date });
                  }}
                />
            </div>


      </div>
    );
  }
}

export default App;

Tuesday, November 9, 2021

SwiftUI Customize List with section header and footer

SwiftUI Customize List with section header and footer

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    let hikingTrails = [
        Trail(name: "Mount Pinatubo", location: "Botolan", distance: 2.9),
        Trail(name: "Mount Balingkilat", location: "Subic", distance: 1.2),
        Trail(name: "Sampaloc Cove", location: "Subic", distance: 1.1),
        Trail(name: "Mount Tapulao", location: "Palauig", distance: 1.3),
        Trail(name: "Pundakit", location: "San Antonio", distance: 2.7),
    ]
    
    var body: some View {
        VStack{
            GeometryReader { geometry in
                Image("details")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .offset(y: geometry.frame(in: .global).minY/100)
                    .edgesIgnoringSafeArea(.all)
            }
            VStack {
                List {
                    Section(header: ListHeader(), footer: ListFooter()) {
                        ForEach(hikingTrails) { trail in
                            TrailRow(trail: trail)
                        }
                    }
                }.listStyle(GroupedListStyle())
            }
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ListHeader: View {
    var body: some View {
        HStack {
            Image(systemName: "map")
            Text("Best Trails in Zambales")
        }
    }
}

struct ListFooter: View {
    var body: some View {
        Text("Ready to check out the best trails in Zambales for hiking, mountain biking, climbing or other outdoor activities? AllTrails has 12 hiking trails, mountain biking routes, backpacking trips and more.")
    }
}

struct TrailRow: View {
    var trail: Trail
    
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text(trail.name)
                Text(trail.location).font(.subheadline).foregroundColor(.gray)
            }
            Spacer()
            Text(String(format: "%.1f miles", trail.distance))
        }
    }
}

struct Trail: Identifiable {
    var id = UUID()
    var name: String
    var location: String
    var distance: Double
}

Related Post