article

Thursday, December 2, 2021

SwiftUI Furniture Shop App UI

SwiftUI Furniture Shop App UI

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var search: String = ""
    @State private var selectedIndex: Int = 1
    
    private let categories = ["All", "Chair", "Sofa", "Sofabeds", "Mattresses", "Table"]
    var body: some View {
        NavigationView {
            ZStack {
                Color("Bg")
                    .ignoresSafeArea()
                
                ScrollView (showsIndicators: false) {
                    VStack (alignment: .leading) {
                        
                        AppBarView()
                        
                        TagLineView()
                            .padding()
                        
                        SearchAndScanView(search: $search)
                        
                        ScrollView (.horizontal, showsIndicators: false) {
                            HStack {
                                ForEach(0 ..< categories.count) { i in
                                    Button(action: {selectedIndex = i}) {
                                        CategoryView(isActive: selectedIndex == i, text: categories[i])
                                    }
                                }
                            }
                            .padding()
                        }
                        
                        Text("Popular")
                            .font(.system(size: 24))
                            .padding(.horizontal)
                        
                        ScrollView (.horizontal, showsIndicators: false) {
                            HStack (spacing: 0) {
                                ForEach(popular) { i in
                                    NavigationLink(
                                        destination: DetailScreen(viewmodel: i),
                                        label: {
                                            ProductCardView(image: Image(i.imageName), size: 210, title: i.title, rating: i.rating)
                                        })
                                        .navigationBarHidden(true)
                                        .foregroundColor(.black)
                                }
                                .padding(.leading)
                            }
                        }
                        .padding(.bottom)
                        
                        Text("Best")
                            .font(.system(size: 24))
                            .padding(.horizontal)
                        
                        ScrollView (.horizontal, showsIndicators: false) {
                            HStack (spacing: 0) {
                                ForEach(best) { i in
                                    ProductCardView(image: Image(i.imageName), size: 180, title: i.title, rating: i.rating)
                                }
                                .padding(.leading)
                            }
                        }
                        
                    }
                }
                
                VStack {
                    Spacer()
                    BottomNavBarView()
                }
            }
        }
    }
}

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


struct BottomNavBarView: View {
    var body: some View {
        HStack {
            BottomNavBarItem(image: Image(systemName: "house"), action: {})
            BottomNavBarItem(image: Image(systemName: "suit.heart"), action: {})
            BottomNavBarItem(image: Image(systemName: "cart"), action: {})
            BottomNavBarItem(image: Image(systemName: "person"), action: {})
        }
        .padding()
        .background(Color("Primary")).foregroundColor(Color.white)
        .clipShape(Capsule())
        .padding(.horizontal)
        .shadow(color: Color.blue.opacity(0.15), radius: 8, x: 2, y: 6)
    }
}

struct BottomNavBarItem: View {
    let image: Image
    let action: () -> Void
    var body: some View {
        Button(action: action) {
            image
                .frame(maxWidth: .infinity)
        }
    }
}
AppBarView.swift
 
//
//  AppBarView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct AppBarView: View {
    var body: some View {
        HStack {
            Button(action: {}) {
                Image(systemName: "slider.horizontal.3")
                    .padding()
                    .background(Color.white)
                    .cornerRadius(10.0)
            }
            
            Spacer()
            
            Button(action: {}) {
                Image(uiImage: #imageLiteral(resourceName: "photo1"))
                    .resizable()
                    .frame(width: 42, height: 42)
                    .cornerRadius(10.0)
            }
        }
        .padding(.horizontal)
    }
}

struct AppBarView_Previews: PreviewProvider {
    static var previews: some View {
        AppBarView()
    }
}
TagLineView.swift
 
//
//  TagLineView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct TagLineView: View {
    var body: some View {
        Text("Shop \nBest ")
            .font(.system(size: 28))
            .foregroundColor(Color("Primary"))
            + Text("Furniture!")
            .font(.system(size: 28))
            .fontWeight(.bold)
            .foregroundColor(Color("Primary"))
    }
}

struct TagLineView_Previews: PreviewProvider {
    static var previews: some View {
        TagLineView()
    }
}
SearchAndScanView.swift
 
//
//  SearchAndScanView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct SearchAndScanView: View {
    @Binding var search: String
    var body: some View {
        HStack {
            HStack {
                Image(systemName: "magnifyingglass")
                    .padding(.trailing, 8)
                TextField("Search Furniture", text: $search)
            }
            .padding(.all, 20)
            .background(Color.white)
            .cornerRadius(10.0)
            .padding(.trailing, 8)
            
            Button(action: {}) {
                Image(systemName: "text.magnifyingglass")
                    .padding().foregroundColor(Color.white)
                    .background(Color("Primary"))
                    .cornerRadius(10.0)
            }
        }
        .padding(.horizontal)
    }
}

struct SearchAndScanView_Previews: PreviewProvider {
    @State static var search: String = ""
    static var previews: some View {
        SearchAndScanView(search: $search)
    }
}
CategoryView.swift
 
//
//  CategoryView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct CategoryView: View {
    let isActive: Bool
    let text: String
    var body: some View {
        VStack (alignment: .leading, spacing: 0) {
            Text(text)
                .font(.system(size: 18))
                .fontWeight(.medium)
                .foregroundColor(isActive ? Color("Primary") : Color.black.opacity(0.5))
            if (isActive) { Color("Primary")
                .frame(width: 15, height: 2)
                .clipShape(Capsule())
            }
        }
        .padding(.trailing)
    }
}
ProductCardView.swift
 
//
//  ProductCardView.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct ProductCardView: View {
    let image: Image
    let size: CGFloat
    let title: String
    let rating: Int
    var body: some View {
        VStack {
            image
                .resizable()
                .frame(width: size, height: 200 * (size/210))
                .cornerRadius(20.0)
            Text(title).font(.title3).fontWeight(.bold)
            
            HStack (spacing: 2) {
                ForEach(0..<rating) { rating in
                    Image(systemName: "star.fill")
                        .resizable()
                        .frame(width: 20, height: 20)
                        .foregroundColor(.yellow)
                }
                Spacer()
                Text("$1299")
                    .font(.title3)
                    .fontWeight(.bold)
            }
        }
        .frame(width: size)
        .padding()
        .background(Color.white)
        .cornerRadius(20.0)
        
    }
}
DetailScreen.swift
 
//
//  DetailScreen.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI

struct DetailScreen: View {
    
    let viewmodel: Furniture
    
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    var body: some View {
        ZStack {
            Color("Bg")
            ScrollView  {
                //Product Image
                Image(viewmodel.imageName)
                        .resizable()
                        .aspectRatio(1,contentMode: .fit)
                        .edgesIgnoringSafeArea(.top)
                
                DescriptionView(title: viewmodel.title, rating: viewmodel.rating)
                
            }
            .edgesIgnoringSafeArea(.top)
            
            HStack {
                Text("$1299")
                    .font(.title)
                    .foregroundColor(.white)
                Spacer()
                
                Text("Add to Cart")
                    .font(.title3)
                    .fontWeight(.semibold)
                    .foregroundColor(Color("Primary"))
                    .padding()
                    .padding(.horizontal, 8)
                    .background(Color.white)
                    .cornerRadius(10.0)
                
            }
            .padding()
            .padding(.horizontal)
            .background(Color("Primary"))
            .cornerRadius(60.0, corners: .topLeft)
            .frame(maxHeight: .infinity, alignment: .bottom)
            .edgesIgnoringSafeArea(.bottom)
        }
        .navigationBarBackButtonHidden(true)
        .navigationBarItems(leading: BackButton(action: {presentationMode.wrappedValue.dismiss()}), trailing: Image(systemName: "lineweight"))
    }
}


struct RoundedCorner: Shape {

    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

extension View {
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape( RoundedCorner(radius: radius, corners: corners) )
    }
}

struct DetailScreen_Previews: PreviewProvider {
    static var previews: some View {
        DetailScreen(viewmodel: Furniture(id: 1, title: "Sofas", imageName: "1", rating: 5))
    }
}


struct ColorDotView: View {
    let color: Color
    var body: some View {
        color
            .frame(width: 24, height: 24)
            .clipShape(Circle())
    }
}

struct DescriptionView: View {
    let title : String
    let rating : Int
    
    @State var selected = -1
    @State var message = false
    @State private var count = 0
    
    var body: some View {
        VStack (alignment: .leading) {
            //                Title
            Text(title)
                .font(.title)
                .fontWeight(.bold)
            //                Rating
            HStack (spacing: 4) {
                ForEach(0..<5) { rate in
                    Image(systemName: "star.fill")
                        .resizable()
                        .frame(width: 25, height: 25)
                        .foregroundColor(self.selected >= rate ? .yellow : .gray)
                        .onTapGesture {
                            self.selected = rate
                            self.message.toggle()
                        }
                }
                Text("(\(rating))")
                    .opacity(0.5)
                    .padding(.leading, 8)
                Spacer()
            }
            .alert(isPresented: $message) {
               Alert(title: Text("Rating Submit"), message: Text("You Rated \(self.selected + 1) out of 5 Star Rating"), dismissButton: .none)
            }
            
            Text("Description")
                .fontWeight(.medium)
                .padding(.vertical, 8)
            Text("A Mid-Century Modern Modern dining chair with arm rest inspired by Eiffel chair made from polycarbonate plastic and has metal legs.")
                .lineSpacing(8.0)
                .opacity(0.6)
            
            //                Info
            HStack (alignment: .top) {
                VStack (alignment: .leading) {
                    Text("Size")
                        .font(.system(size: 16))
                        .fontWeight(.semibold)
                    Text("W53xD46.5xH83.5 cm")
                        .opacity(0.6)
                }
            }
            .padding(.vertical)
            
            //                Colors and Counter
            HStack {
                VStack (alignment: .leading) {
                    Text("Colors")
                        .fontWeight(.semibold)
                    HStack {
                        ColorDotView(color: Color.red)
                        ColorDotView(color: Color.orange)
                        ColorDotView(color: Color.green)
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
                
                HStack {
                    //                        Minus Button
                    Button(action: {
                        stepCountminus()
                    }) {
                        Image(systemName: "minus")
                            .padding(.all, 8)
                        
                    }
                    .frame(width: 30, height: 30)
                    .overlay(RoundedCorner(radius: 50).stroke())
                    .foregroundColor(.black)
                    
                    Text("\(self.count)")
                        .font(.title2)
                        .fontWeight(.semibold)
                        .padding(.horizontal, 8)
                    
                    //                        Plus Button
                    Button(action: {
                        stepCount()
                    }) {
                        Image(systemName: "plus")
                            .foregroundColor(.white)
                            .padding(.all, 8)
                            .background(Color("Primary"))
                            .clipShape(Circle())
                    }
                }
                
            }
        }
        .padding()
        .padding(.top)
        .background(Color("Bg"))
        .cornerRadius(30, corners: [.topLeft, .topRight])
        .offset(x: 0, y: -30.0)
    }
    
    func stepCount() {
        count += 1
    }
    func stepCountminus() {
        count -= 1
    }
}


struct BackButton: View {
    let action: () -> Void
    var body: some View {
        Button(action: action) {
            Image(systemName: "chevron.backward")
                .foregroundColor(.black)
                .padding(.all, 12)
                .background(Color.white)
                .cornerRadius(8.0)
        }
    }
}
Model.swift
 
//
//  Model.swift
//  SwiftUITest
//
//  Created by Cairocoders
//

import SwiftUI
 
struct Furniture : Identifiable {
    var id : Int
    var title : String
    var imageName : String
    var rating: Int
}
 
var popular = [Furniture(id: 0, title: "Pea Swivel Accent Chair", imageName: "1", rating: 4),
                   Furniture(id: 1, title: "Adelie Accent Chair", imageName: "2", rating: 3),
                   Furniture(id: 2, title: "Asha II Accent Chair", imageName: "3", rating: 5),
                   Furniture(id: 3, title: "Jenpeg Center Table", imageName: "4", rating: 4)]

var best = [Furniture(id: 0, title: "Cologne Sofabed", imageName: "5", rating: 3),
                   Furniture(id: 1, title: "Cleve Sofabed", imageName: "6", rating: 4),
                   Furniture(id: 2, title: "Cleve Sofabed", imageName: "7", rating: 5),
                   Furniture(id: 3, title: "Ivy Dining Chair", imageName: "4", rating: 2)]

Monday, November 29, 2021

ReactJS AG Grid fetch json

ReactJS AG Grid fetch json

In this tutorial we will create a sample to load static data in a grid.

AG Grid is a fully-featured and highly customizable JavaScript data grid. It delivers outstanding performance, has no 3rd party dependencies and integrates smoothly with React as React Component.


C:\reactdev\myreactdev>npm install --save ag-grid-community

https://www.npmjs.com/package/ag-grid-community

Module not found: Can't resolve 'ag-grid-react' in 'C:\reactdev\myreactdev\src'
C:\reactdev\myreactdev>npm i --save ag-grid-community ag-grid-react react-dom-factories

https://www.npmjs.com/package/ag-grid-react
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 { useEffect, useState } from 'react';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

import './App.css';

function App() {

  const [rowData, setRowData] = useState([]);

  useEffect(() => {
    fetch('https://reqres.in/api/users?per_page=12')
      .then(res => res.json())
      .then(result => setRowData(result.data));
  }, []);

  const avatarFormatter = ({ value }) => {
    return <img src={value} width="50px" height="50px" alt="images"/>
  }

  return (
    <div className="App">
      <h2>ReactJS AG Grid fetch json</h2>
      <div className="ag-theme-alpine ag-style">
        <AgGridReact
          defaultColDef={{ flex: 1 }}
          rowHeight={60}
          rowData={rowData} >
          <AgGridColumn field="first_name" headerName="First Name" sortable={true} filter={true} cellClass="vertical-middle" />
          <AgGridColumn field="last_name" headerName="Last Name" sortable={true} filter={true} cellClass="vertical-middle" />
          <AgGridColumn field="email" headerName="Email" sortable={true} filter={true} cellClass="vertical-middle" />
          <AgGridColumn field="avatar" headerName="Avatar" sortable={true} filter={true} cellRendererFramework={avatarFormatter} cellClass="vertical-middle" />
        </AgGridReact>
      </div>
    </div>
  );
}

export default App;
src/App.css
//src/App.css
.ag-style {
  height: 500px;
  width: 100%;
}

.vertical-middle {
  display: flex;
  align-items: center;
}

.vertical-middle img {
  display: block;
  border: 1px solid #ddd;
  border-radius: 3px;
}

PHP Mysql Login using Cookie and Session

PHP Mysql Login using Cookie and Session

index.php
//index.php
<?php
	session_start();
	include('conn.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Using Cookie with Logout</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
</head>
<body id="LoginForm">
<div class="container">
<h1 class="form-heading">PHP Mysql Login using Cookie and Session</h1>
	<div class="login-form">
	<div class="main-div">
		<div class="panel">
			<h2>Admin Login</h2>
			<p>Please enter your username and password</p>
		</div>
		<form id="Login" method="POST" action="login.php">
			<div class="form-group">
				<input type="text" value="<?php if (isset($_COOKIE["user"])){echo $_COOKIE["user"];}?>" name="username" class="form-control" id="inputEmail" placeholder="Email Address">
			</div>
			<div class="form-group">
				<input type="password" value="<?php if (isset($_COOKIE["pass"])){echo $_COOKIE["pass"];}?>" name="password" class="form-control" id="inputPassword" placeholder="Password">
			</div>
			<div class="form-group" style="text-align:left;">
				<label><input type="checkbox" name="remember" <?php if (isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){ echo "checked";}?>> Remember me </label>
			</div>
			<div class="forgot">
				<a href="#">Forgot password?</a>
			</div>
			<input type="submit" class="btn btn-primary" value="Login" name="login">
			<span>	<?php
				if (isset($_SESSION['message'])){
					echo $_SESSION['message'];
				}
				unset($_SESSION['message']);
			?></span>
		</form>
		</div>
		<p class="botto-text"> by Cairocoders</p>
	</div>
</div>
<style>
body#LoginForm{ background-image:url("img/bgblur.jpg"); background-repeat:no-repeat; background-position:center; background-size:cover; padding:10px;}

.form-heading { color:#fff; font-size:23px;text-align:center;}
.panel h2{ color:#444444; font-size:18px; margin:0 0 8px 0;}
.panel p { color:#777777; font-size:14px; margin-bottom:30px; line-height:24px;}
.login-form .form-control {
  background: #f7f7f7 none repeat scroll 0 0;
  border: 1px solid #d4d4d4;
  border-radius: 4px;
  font-size: 14px;
  height: 50px;
  line-height: 50px;
}
.main-div {
  background: #ffffff none repeat scroll 0 0;
  border-radius: 2px;
  margin: 10px auto 30px;
  max-width: 38%;
  padding: 50px 70px 70px 71px;
}

.login-form .form-group {
  margin-bottom:10px;
}
.login-form{ text-align:center;}
.forgot a {
  color: #777777;
  font-size: 14px;
  text-decoration: underline;
}
.login-form  .btn.btn-primary {
  background: #f0ad4e none repeat scroll 0 0;
  border-color: #f0ad4e;
  color: #ffffff;
  font-size: 14px;
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding: 0;
}
.forgot {
  text-align: left; margin-bottom:30px;
}
.botto-text {
  color: #ffffff;
  font-size: 14px;
  margin: auto;
}
.login-form .btn.btn-primary.reset {
  background: #ff9900 none repeat scroll 0 0;
}
.back { text-align: left; margin-top:10px;}
.back a {color: #444444; font-size: 13px;text-decoration: none;}
</style>
</body>
</html>
login.php
//login.php
<?php
	if(isset($_POST['login'])){
		
		session_start();
		include('conn.php');
	
		$username=$_POST['username'];
		$password=$_POST['password'];
	
		$query=mysqli_query($conn,"select * from user where user_name='$username' && user_password='$password'");
	
		if (mysqli_num_rows($query) == 0){
			$_SESSION['message']="Login Failed. User not Found!";
			header('location:index.php');
		}
		else{
			$row=mysqli_fetch_array($query);
			
			if (isset($_POST['remember'])){
				//set up cookie
				setcookie("user", $row['user_name'], time() + (86400 * 30)); 
				setcookie("pass", $row['user_password'], time() + (86400 * 30)); 
			}
			
			$_SESSION['id']=$row['user_id'];
			header('location:success.php');
		}
	}
	else{
		header('location:index.php');
		$_SESSION['message']="Please Login!";
	}
?>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
success.php
//success.php
<?php
	session_start();
	
	if (!isset($_SESSION['id']) ||(trim ($_SESSION['id']) == '')) {
		header('index.php');
		exit();
	}
	include('conn.php');
	$query=mysqli_query($conn,"select * from user where user_id='".$_SESSION['id']."'");
	$row=mysqli_fetch_assoc($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Success</title>
</head>
<body>
	<h2>Login Success</h2>
	<?php echo $row['user_email']; ?>
	<br>
	<a href="logout.php">Logout</a>
</body>
</html>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	
	if (isset($_COOKIE["user"]) AND isset($_COOKIE["pass"])){
		setcookie("user", '', time() - (3600));
		setcookie("pass", '', time() - (3600));
	}

	header('location:index.php');

?>
user table
CREATE TABLE `user` (
  `user_id` bigint(20) NOT NULL,
  `user_name` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `user` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
(1, 'cairocoders', 'cairocoders@gmail.com', 'pass'),
(2, 'tutorial101.blogspot.com', 'cairocoders08@gmail.com', 'pass');

ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

ALTER TABLE `user`
  MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

Friday, November 26, 2021

AngularJS Show Alert with Timeout

AngularJS Show Alert with Timeout

index.html
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AngularJS Create Alert with Timeout</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <style type="text/css">
    	.bottom-left{
			display:block;
			position:absolute;
			bottom:50px;
			left:50px;
		}
    </style>
</head>
<body  ng-app="app" ng-controller="myController">
<div class="container">
    <h1 class="page-header text-center">AngularJS Show Alert with Timeout</h1>
    <div class="row">
	    <div class="col-sm-4 col-sm-offset-4">
	    	<div class="panel panel-default">
	    		<div class="panel-body">
	    			<form name="myForm" ng-submit="submitForm()">
	    				<div class="form-group">
		    				<label>User Name:</label>
		    				<input type="text" class="form-control" ng-model="user.username" required>
		    			</div>
		    			<div class="form-group">
		    				<label>Password:</label>
		    				<input type="password" class="form-control" ng-model="user.password" required>
		    			</div>
	    				<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid"><span class="glyphicon glyphicon glyphicon-send"></span> Submit</button>
					</form>
	    		</div>
			</div>		
		</div>
	</div>
</div>
<div class="alert alert-success text-center bottom-left" ng-show="success">
	<button type="button" class="close" ng-click="closeAlert()">×</button>
   	<span class="glyphicon glyphicon-check"></span> {{ message }}
</div>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope, $timeout){
    $scope.success = false;

    $scope.submitForm = function(){
    	//success request
    	$scope.success = true;
    	$scope.message = 'Successfully Login'; 
    	
    	//after 5 sec call to close the alert
    	$timeout( function(){
            $scope.closeAlert();
        }, 5000 );
    }

    $scope.closeAlert = function(){
    	$scope.success = false;
    }
});
</script>
</body>
</html>

Thursday, November 25, 2021

PHP Mysql PDO CRUD (Create, Read, Update and Delete ) with jquery Ajax and Bootstrap4 Modal

PHP Mysql PDO CRUD (Create, Read, Update and Delete ) with jquery Ajax and Bootstrap4 Modal

Bootstrap 4 CDN
https://getbootstrap.com/docs/4.3/getting-started/introduction/

https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css
https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js

Modal
https://getbootstrap.com/docs/4.3/components/modal/

jquery
https://releases.jquery.com/jquery/

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

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle ', 'Williamson', 'New York');

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

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

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Mysql PDO CRUD (Create, Read, Update and Delete ) with jquery Ajax and Bootstrap4 Modal</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
	<h1 class="page-header text-center">PHP Mysql PDO CRUD (Create, Read, Update and Delete ) with jquery Ajax and Bootstrap4 Modal</h1>
	<div class="row">
		<div class="col-12">
			<button id="addnew" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Add New Member</button>
            <div id="alert" class="alert alert-info text-center" style="margin-top:20px; display:none;">
            	<button class="close"><span aria-hidden="true">×</span></button>
                <span id="alert_message"></span>
            </div>  
			<table class="table table-bordered table-striped" style="margin-top:20px;">
				<thead>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
					<th width="150">Action</th>
				</thead>
				<tbody id="tbody"></tbody>
			</table>
		</div>
	</div>
</div>
<!-- Modals -->
<?php include('modal.html'); ?>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>
modal.html
//modal.html
<!-- Add New -->
<div class="modal fade" id="add" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">Add New</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
				  <span aria-hidden="true">×</span>
				</button>
			</div>
            <div class="modal-body">
			<form id="addForm">
				<div class="row form-group">
					<div class="col-sm-2">
						<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="firstname">
					</div>
				</div>
				<div class="row form-group">
					<div class="col-sm-2">
						<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="lastname">
					</div>
				</div>
				<div class="row form-group">
					<div class="col-sm-2">
						<label class="control-label" style="position:relative; top:7px;">Address:</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="address">
					</div>
				</div>
			</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
			</form>
            </div>

        </div>
    </div>
</div>

<!-- Edit -->
<div class="modal fade" id="edit" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
		    <div class="modal-header">
				<h5 class="modal-title">Edit Member</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
				  <span aria-hidden="true">×</span>
				</button>
			</div>
            <div class="modal-body">
			<form id="editForm">
				<input type="hidden" class="id" name="id">
				<div class="row form-group">
					<div class="col-sm-2">
						<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="form-control firstname" name="firstname">
					</div>
				</div>
				<div class="row form-group">
					<div class="col-sm-2">
						<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="form-control lastname" name="lastname">
					</div>
				</div>
				<div class="row form-group">
					<div class="col-sm-2">
						<label class="control-label" style="position:relative; top:7px;">Address:</label>
					</div>
					<div class="col-sm-10">
						<input type="text" class="form-control address" name="address">
					</div>
				</div>
			</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                <button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Update</a>
			</form>
            </div>

        </div>
    </div>
</div>

<!-- Delete -->
<div class="modal fade" id="delete" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
		    <div class="modal-header">
				<h5 class="modal-title">Delete Member</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
				  <span aria-hidden="true">×</span>
				</button>
			</div>
            <div class="modal-body">	
            	<p class="text-center">Are you sure you want to Delete</p>
				<h2 class="text-center fullname"></h2>
			</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                <button type="button" class="btn btn-danger id"><span class="glyphicon glyphicon-trash"></span> Yes</button>
            </div>

        </div>
    </div>
</div>
script.js
//script.js
$(document).ready(function(){
	fetch();
	//add
	$('#addnew').click(function(){
		$('#add').modal('show');
	});
	$('#addForm').submit(function(e){
		e.preventDefault();
		var addform = $(this).serialize();
		//console.log(addform);
		$.ajax({
			method: 'POST',
			url: 'add.php',
			data: addform,
			dataType: 'json',
			success: function(response){
				$('#add').modal('hide');
				if(response.error){
					$('#alert').show();
					$('#alert_message').html(response.message);
				}
				else{
					$('#alert').show();
					$('#alert_message').html(response.message);
					fetch();
				}
			}
		});
	});
	//

	//edit
	$(document).on('click', '.edit', function(){
		var id = $(this).data('id');
		getDetails(id);
		$('#edit').modal('show');
	});
	$('#editForm').submit(function(e){
		e.preventDefault();
		var editform = $(this).serialize();
		$.ajax({
			method: 'POST',
			url: 'edit.php',
			data: editform,
			dataType: 'json',
			success: function(response){
				if(response.error){
					$('#alert').show();
					$('#alert_message').html(response.message);
				}
				else{
					$('#alert').show();
					$('#alert_message').html(response.message);
					fetch();
				}

				$('#edit').modal('hide');
			}
		});
	});
	//

	//delete
	$(document).on('click', '.delete', function(){
		var id = $(this).data('id');
		getDetails(id);
		$('#delete').modal('show');
	});

	$('.id').click(function(){
		var id = $(this).val();
		$.ajax({
			method: 'POST', 
			url: 'delete.php',
			data: {id:id},
			dataType: 'json',
			success: function(response){
				if(response.error){
					$('#alert').show();
					$('#alert_message').html(response.message);
				}
				else{
					$('#alert').show();
					$('#alert_message').html(response.message);
					fetch();
				}
				
				$('#delete').modal('hide');
			}
		});
	});
	//

	//hide message
	$(document).on('click', '.close', function(){
		$('#alert').hide();
	});

});

function fetch(){
	$.ajax({
		method: 'POST',
		url: 'fetch.php',
		success: function(response){
			$('#tbody').html(response);
		}
	});
}

function getDetails(id){
	$.ajax({
		method: 'POST',
		url: 'fetch_row.php',
		data: {id:id},
		dataType: 'json',
		success: function(response){
			if(response.error){
				$('#edit').modal('hide');
				$('#delete').modal('hide');
				$('#alert').show();
				$('#alert_message').html(response.message);
			}
			else{
				$('.id').val(response.data.id);
				$('.firstname').val(response.data.firstname);
				$('.lastname').val(response.data.lastname);
				$('.address').val(response.data.address);
				$('.fullname').html(response.data.firstname + ' ' + response.data.lastname);
			}
		}
	});
}
db.php
//db.php
<?php
Class connDB{
 
	private $server = "mysql:host=localhost;dbname=testingdb";
	private $username = "root";
	private $password = "";
	private $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
	protected $conn;
 	
	public function open(){
 		try{
 			$this->conn = new PDO($this->server, $this->username, $this->password, $this->options);
 			return $this->conn;
 		}
 		catch (PDOException $e){
 			echo "There is some problem in connection: " . $e->getMessage();
 		}
 
    }
 
	public function close(){
   		$this->conn = null;
 	}
}
?>
fetch.php
//fetch.php
<?php
	include_once('db.php');
	$database = new connDB();
	$db = $database->open();

	try{	
	    $sql = 'SELECT * FROM members';
	    foreach ($db->query($sql) as $row) {
	    	?>
	    	<tr>
	    		<td><?php echo $row['id']; ?></td>
	    		<td><?php echo $row['firstname']; ?></td>
	    		<td><?php echo $row['lastname']; ?></td>
	    		<td><?php echo $row['address']; ?></td>
	    		<td>
	    			<button class="btn btn-success btn-sm edit" data-id="<?php echo $row['id']; ?>"><span class="glyphicon glyphicon-edit"></span> Edit</button>
	    			<button class="btn btn-danger btn-sm delete" data-id="<?php echo $row['id']; ?>"><span class="glyphicon glyphicon-trash"></span> Delete</button>
	    		</td>
	    	</tr>
	    	<?php 
	    }
	}
	catch(PDOException $e){
		echo "There is some problem in connection: " . $e->getMessage();
	}

	//close connection
	$database->close();
?>
add.php
//add.php
<?php
	include_once('db.php');
	$output = array('error' => false);

	$database = new connDB();
	$db = $database->open();
	try{
		//use of prepared statement to prevent sql injection
		$stmt = $db->prepare("INSERT INTO members (firstname, lastname, address) VALUES (:firstname, :lastname, :address)");
		//if-else statement executing prepared statement
		if ($stmt->execute(array(':firstname' => $_POST['firstname'] , ':lastname' => $_POST['lastname'] , ':address' => $_POST['address'])) ){
			$output['message'] = 'Member added successfully';
		}
		else{
			$output['error'] = true;
			$output['message'] = 'Something went wrong. Cannot add member';
		} 
		   
	}
	catch(PDOException $e){
		$output['error'] = true;
 		$output['message'] = $e->getMessage();
	}

	//close connection
	$database->close();

	echo json_encode($output);
?>
edit.php
//edit.php
<?php
	include_once('db.php');

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

	$database = new connDB();
	$db = $database->open();
	try{
		$id = $_POST['id'];
		$firstname = $_POST['firstname'];
		$lastname = $_POST['lastname'];
		$address = $_POST['address'];

		$sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$id'";
		//if-else statement executing query
		if($db->exec($sql)){
			$output['message'] = 'Member updated successfully';
		} 
		else{
			$output['error'] = true;
			$output['message'] = 'Something went wrong. Cannot update member';
		}

	}
	catch(PDOException $e){
		$output['error'] = true;
		$output['message'] = $e->getMessage();
	}

	//close connection
	$database->close();

	echo json_encode($output);
?>
fetch_row.php
//fetch_row.php
<?php
	include_once('db.php');

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

	$database = new connDB();
	$db = $database->open();

	try{
		$id = $_POST['id'];
		$stmt = $db->prepare("SELECT * FROM members WHERE id = :id");
		$stmt->bindParam(':id', $id);
		$stmt->execute();
		$output['data'] = $stmt->fetch();
	}
	catch(PDOException $e){
		$output['error'] = true;
		$output['message'] = $e->getMessage();
	}

	//close connection
	$database->close();

	echo json_encode($output);
?>
delete.php
//delete.php
<?php
	include_once('db.php');

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

	$database = new connDB();
	$db = $database->open();
	try{
		$sql = "DELETE FROM members WHERE id = '".$_POST['id']."'";
		//if-else statement executing query
		if($db->exec($sql)){
			$output['message'] = 'Member deleted successfully';
		}
		else{
			$output['error'] = true;
			$output['message'] = 'Something went wrong. Cannot delete member';
		} 
	}
	catch(PDOException $e){
		$output['error'] = true;
		$output['message'] = $e->getMessage();;
	}

	//close connection
	$database->close();

	echo json_encode($output);
?>

SwiftUI Simple Food Delivery App UI Design

SwiftUI Simple Food Delivery App UI Design

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

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack {
            ZStack (alignment: .leading) {
                VStack (alignment: .leading) {
                    HStack {
                        Image(systemName: "line.3.horizontal")
                            .resizable()
                            .frame(width: 24, height: 24)
                        
                        Spacer()
                        
                        Image(systemName: "magnifyingglass").resizable()
                            .frame(width: 24, height: 24)
                            .padding()
                            .foregroundColor(.white)
                            .background(Color.secondary)
                            .clipShape(Circle())
                            .shadow(radius: 8)
                    }
                    Text("Food Bazzar").font(.title).foregroundColor(.secondary)
                    Text("15 Results").font(.title).foregroundColor(.primary)
                    
                    ScrollView(.vertical, showsIndicators: false) {
                        HStack (spacing: 20) {
                            FoodItem()
                            FoodItem()
                        }
                        HStack (spacing: 20) {
                            FoodItem()
                            FoodItem()
                        }
                        HStack (spacing: 20) {
                            FoodItem()
                            FoodItem()
                        }
                    }
                }

            }.padding().edgesIgnoringSafeArea(.bottom)
            
            Button(action: {}) {
                Image(systemName: "cart").resizable().frame(width: 12, height: 12).padding().background(Color.yellow).clipShape(Circle()).padding()
                Text("4 items").foregroundColor(.white).padding(.horizontal)
            }.background(Color.black.opacity(0.8)).clipShape(Capsule())
                .shadow(color: Color.black.opacity(0.2), radius: 2, x: 0, y: 20)
        }
    }
}

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

import SwiftUI

struct FoodItem: View {
    var body: some View {
        VStack (alignment: .leading) {
            HStack {
                Image(systemName: "flame.fill").resizable().frame(width: 16, height: 16).foregroundColor(.red)
                Text("Very Hot").font(.footnote).foregroundColor(.primary)
            }
            Image("pic").resizable().aspectRatio(contentMode: .fill).frame(width: 100, height: 100)
            
            Text("Classic").font(.headline)
            Text("Platter").foregroundColor(.secondary).font(.subheadline).padding(.bottom, 12)
            Text("$25.99").font(.title)
        }
        .frame(width: 160, height: 250).background(Color.secondary.opacity(0.3)).cornerRadius(12)
    }
}

struct FoodItem_Previews: PreviewProvider {
    static var previews: some View {
        FoodItem()
    }
}

SwiftUI Landing Page

SwiftUI Landing Page

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

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        ZStack {
            Image("onboarding").resizable().aspectRatio(contentMode: .fill).edgesIgnoringSafeArea(.all)
            
            Rectangle()
                .foregroundColor(.clear)
                .background(LinearGradient(gradient: Gradient(colors: [.clear, .black]), startPoint: .bottom, endPoint: .top))
                .edgesIgnoringSafeArea(.all)
            
            VStack (spacing :29) {
                Text("GigaPro").font(.title).fontWeight(.heavy)
                Spacer()
                VStack {
                    Text("Good App").font(.system(size: 40, design: .monospaced)).fontWeight(.heavy)
                    Text("Make Live Better").font(.system(size: 30, design: .monospaced)).fontWeight(.heavy)
                }.padding(.vertical, 20)
                
                Text("Check out the trendy App")
                    .lineLimit(2)
                    .multilineTextAlignment(.center)
                
                Button(action: {}) {
                    Text("Join Now").padding()
                }.frame(width:300).background(Color.orange)
            }.frame(width: UIScreen.main.bounds.width - 40)
                .foregroundColor(.white)
        }
    }
}

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

Wednesday, November 24, 2021

SwiftUI Horizontal Carousel Parallax Animation

SwiftUI Horizontal Carousel Parallax Animation

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

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            ScrollView {
                MoviesCarousel(categoryName: "Top Movies")
            }.navigationBarTitle("Browse", displayMode: .large)
        }
    }
}

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

import SwiftUI

struct MoviesCarousel: View {
    
    let categoryName: String
    
    var body: some View {
        VStack {
            HStack {
                Text(categoryName)
                    .font(.system(size: 14, weight: .heavy))
                    .padding(.vertical, 6)
                    .padding(.horizontal, 12)
                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(2)
                Spacer()
            }.padding(.horizontal)
            .padding(.top)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(alignment: .top, spacing: 16) {
                    ForEach(latestmovie) { num in
                        GeometryReader { proxy in
                            let scale = getScale(proxy: proxy)
                            NavigationLink(
                                destination: MovieDetailsView(movie: num),
                                label: {
                                    VStack(spacing: 8) {
                                        Image(num.imageName)
                                            .resizable()
                                            .scaledToFill()
                                            .frame(width: 180)
                                            .clipped()
                                            .cornerRadius(8)
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 8)
                                                    .stroke(Color(white: 0.4))
                                            )
                                            .shadow(radius: 3)
                                        Text(num.title)
                                            .font(.system(size: 16, weight: .semibold))
                                            .multilineTextAlignment(.center)
                                            .foregroundColor(.black)
                                        HStack(spacing: 0) {
                                            ForEach(0..<5) { num in
                                                Image(systemName: "star.fill")
                                                    .foregroundColor(.orange)
                                                    .font(.system(size: 14))
                                            }
                                        }.padding(.top, -4)
                                    }
                                })
                            
                                .scaleEffect(.init(width: scale, height: scale))
                                //.animation(.spring(), value: 1)
                                .animation(.easeOut(duration: 1))
                                
                                .padding(.vertical)
                        } //End Geometry
                        .frame(width: 125, height: 400)
                        .padding(.horizontal, 32)
                        .padding(.vertical, 32)
                    } //End ForEach
                    Spacer()
                        .frame(width: 16)
                } //End HStack
            }// End ScrollView
        }//End VStack
    }
    
    func getScale(proxy: GeometryProxy) -> CGFloat {
        let midPoint: CGFloat = 125
        
        let viewFrame = proxy.frame(in: CoordinateSpace.global)
        
        var scale: CGFloat = 1.0
        let deltaXAnimationThreshold: CGFloat = 125
        
        let diffFromCenter = abs(midPoint - viewFrame.origin.x - deltaXAnimationThreshold / 2)
        if diffFromCenter < deltaXAnimationThreshold {
            scale = 1 + (deltaXAnimationThreshold - diffFromCenter) / 500
        }
        
        return scale
    }
}


struct MoviesCarousel_Previews: PreviewProvider {
    static var previews: some View {
        MoviesCarousel(categoryName: "Top Movie")
    }
}
MovieDetailsView.swift
 
//
//  MovieDetailsView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct MovieDetailsView: View {
    
    let movie: Movie
    
    var body: some View {
        Image(movie.imageName)
            .resizable()
            .scaledToFill()
            .navigationTitle(movie.title)
    }
}

struct MovieDetailsView_Previews: PreviewProvider {
    static var previews: some View {
        MovieDetailsView(movie: Movie(id: 1, title: "Avengers", imageName: "1"))
    }
}
Model.swift
 
//
//  Model.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct Movie : Identifiable {
    var id : Int
    var title : String
    var imageName : String
}

var latestmovie = [Movie(id: 0, title: "The Avengers", imageName: "1"),
             Movie(id: 1, title: "Onward", imageName: "2"),
             Movie(id: 2, title: "Soul", imageName: "3"),
             Movie(id: 3, title: "Cruella", imageName: "4"),
             Movie(id: 4, title: "Jungle Cruise", imageName: "5"),
             Movie(id: 5, title: "The Call of the wild", imageName: "6"),
             Movie(id: 6, title: "Joker", imageName: "7"),
             Movie(id: 7, title: "Mulan", imageName: "8"),
             Movie(id: 8, title: "Mortal Kombat", imageName: "9")]

Monday, November 22, 2021

ReactJS Simple Multi Step Forms with Bootstrap

ReactJS Simple Multi Step Forms with Bootstrap

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 App.js
//App.js
import 'bootstrap/dist/css/bootstrap.min.css';
import MultiStepForm from "./components/MultiStepForm";
import './App.css';

function App() {
    return (
      <div>
        <MultiStepForm />
      </div>
    );   
}

export default App;
SimpleForm.js
//SimpleForm.js
import React, { Component } from 'react';
import Container from 'react-bootstrap/Container';
import Form from 'react-bootstrap/Form';

class SimpleForm extends Component {
  render() {
    return (
    <Container>
      <Form>
        <Form.Group controlId="form.Name">
            <Form.Label>Name</Form.Label>
            <Form.Control type="text" placeholder="Enter name" />
        </Form.Group>
        <Form.Group controlId="form.Email">
            <Form.Label>Email address</Form.Label>
            <Form.Control type="email" placeholder="name@example.com" />
        </Form.Group>
        <Form.Group controlId="form.Textarea">
            <Form.Label>Comment</Form.Label>
            <Form.Control as="textarea" rows={3} />
        </Form.Group>
      </Form>
    </Container>
    );
  }
       
}
export default SimpleForm;
MultistepForm.js
//MultistepForm.js
import React, { Component } from 'react';
import UserDetails from "./UserDetails";
import AddressDetails from "./AddressDetails";
import Confirmation from "./Confirmation";

class MultiStepForm extends Component {
    state = {
        step: 1,
        firstName: '',
        lastName: '',
        email: '',
        address: '',
        city: '',
        state: '',
        zip:'',
    }

    nextStep = () => {
        const { step } = this.state
        this.setState({
            step : step + 1
        })
    }

    prevStep = () => {
        const { step } = this.state
        this.setState({
            step : step - 1
        })
    }

    handleChange = (event) => {
        this.setState({[event.target.name]: event.target.value})
    }

    render(){
        const { step, firstName, lastName, email, address, city, state, zip } = this.state;
        const inputValues = { firstName, lastName, email, address, city, state, zip };
        switch(step) {
        case 1:
            return <UserDetails
                    nextStep={this.nextStep}
                    handleChange = {this.handleChange}
                    inputValues={inputValues}
                    />
        case 2:
            return <AddressDetails
                    nextStep={this.nextStep}
                    prevStep={this.prevStep}
                    handleChange = {this.handleChange}
                    inputValues={inputValues}
                    />
        case 3:
            return <Confirmation
                    nextStep={this.nextStep}
                    prevStep={this.prevStep}
                    inputValues={inputValues}
                    />
        }
    }
}

export default MultiStepForm;
UserDetails.js
//UserDetails.js
import React, { Component } from 'react';
import { Form, Button, Col, Container } from 'react-bootstrap';


class UserDetails extends Component{

    back  = (e) => {
        e.preventDefault();
        this.props.prevStep();
    }

    saveAndContinue = (e) => {
        e.preventDefault();
        this.props.nextStep();
    };


    render() {
        return( <Container>
                    <Form>
                        <Form.Row>
                            <Form.Group as={Col} controlId="formFirstName">
                                <Form.Label className="label">First Name</Form.Label>
                                <Form.Control
                                type="text"
                                defaultValue={this.props.inputValues.firstName}
                                name="firstName"
                                required
                                onChange={this.props.handleChange}
                                />
                            </Form.Group>

                            <Form.Group as={Col} controlId="formLastName">
                                <Form.Label className="label">Last Name</Form.Label>
                                <Form.Control
                                type="text"
                                defaultValue={this.props.inputValues.lastName}
                                name="lastName"
                                required
                                onChange={this.props.handleChange}
                                />
                            </Form.Group>
                        </Form.Row>

                        <Form.Group controlId="formEmail">
                            <Form.Label className="label">Email Address</Form.Label>
                            <Form.Control
                            type="email"
                            defaultValue={this.props.inputValues.email}
                            name="email"
                            required
                            onChange={this.props.handleChange}
                            />
                        </Form.Group>

                        <Button variant="primary" onClick={this.saveAndContinue}>Next</Button>
                    </Form>
                </Container>
        );
    }
}

export default UserDetails;
AddressDetails.js
//AddressDetails.js
import React, { Component } from 'react';
import { Form, Button, Col, Container } from 'react-bootstrap';


class AddressDetails extends Component{

    back  = (e) => {
        e.preventDefault();
        this.props.prevStep();
    }

    saveAndContinue = (e) => {
        e.preventDefault();
        this.props.nextStep();
    };


    render() {
        return( <Container>
                    <Form>
                        <Form.Group controlId="formAddress">
                            <Form.Label>Address</Form.Label>
                            <Form.Control
                                type="text"
                                defaultValue={this.props.inputValues.address}
                                name="address"
                                required
                                onChange={this.props.handleChange}
                            />
                        </Form.Group>

                        <Form.Row>
                            <Form.Group as={Col} controlId="formCity">
                                <Form.Label>City</Form.Label>
                                <Form.Control
                                type="text"
                                defaultValue={this.props.inputValues.city}
                                name="city"
                                required
                                onChange={this.props.handleChange}
                                />
                            </Form.Group>

                            <Form.Group as={Col} controlId="formState">
                                <Form.Label>State</Form.Label>
                                <Form.Control as="select" name="state" defaultValue={this.props.inputValues.state} onChange={this.props.handleChange}>
                                    <option value="AL">Alabama</option>
                                    <option value="AK">Alaska</option>
                                    <option value="AZ">Arizona</option>
                                </Form.Control>
                            </Form.Group>

                            <Form.Group as={Col} controlId="formZip">
                                <Form.Label>Zip</Form.Label>
                                <Form.Control
                                type="text"
                                defaultValue={this.props.inputValues.zip}
                                name="zip"
                                required
                                onChange={this.props.handleChange}
                                />
                            </Form.Group>
                        </Form.Row>

                        <Button variant="secondary" onClick={this.back}>Back</Button>{' '}
                        <Button variant="primary" onClick={this.saveAndContinue}>Next</Button>
                    </Form>
                </Container>
        );
    }
}

export default AddressDetails;
Confirmation.js
//Confirmation.js
import React, { Component } from 'react';
import { Button, Container } from 'react-bootstrap';

class Confirmation extends Component{

    back  = (e) => {
        e.preventDefault();
        this.props.prevStep();
    }

    saveAndContinue = (e) => {
        e.preventDefault();
        this.props.nextStep();
    };

    render(){
        const {inputValues: { firstName, lastName, email, address, city, state, zip }} = this.props;

        return(
            <Container>
                <h1>Confirm your Details</h1>
                <p>Confirm if the following details are correct.</p>
                <p>First Name: {firstName}</p>
                <p>Last Name: {lastName}</p>
                <p>Email: {email}</p>
                <p>Adress: {address}</p>
                <p>City: {city}</p>
                <p>State: {state}</p>
                <p>Zip: {zip}</p>
                <Button variant="secondary" onClick={this.back}>Back</Button>{' '}
                <Button variant="primary">Confirm</Button>
            </Container>
        )
    }
}

export default Confirmation;

Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql

Vue.js Axios Dynamic Dependent Select Box 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

CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO `country` (`id`, `country`) VALUES
(1, 'Afghanistan'),
(171, 'Philippines'),
(227, 'United States of America');


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

ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;


CREATE TABLE `state` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `state` (`id`, `name`, `country_id`) VALUES
(1, 'ARMM', 171),
(2, 'Bicol', 171),
(3, 'Central Luzon', 171),
(4, 'Central Mindanao', 171),
(5, 'Alabama', 227),
(6, 'Alaska', 227),
(7, 'Arizona', 227),
(8, 'California', 227),
(9, 'Florida', 227);

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

ALTER TABLE `state`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

CREATE TABLE `city` (
  `id` int(11) NOT NULL,
  `cityname` varchar(150) NOT NULL,
  `stateid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `city` (`id`, `cityname`, `stateid`) VALUES
(1, 'Anaheim', 8),
(2, 'Arden-Arcade', 8),
(3, 'Bakersfield', 8),
(4, 'Carson', 8),
(5, 'Daly City', 8),
(6, 'Angeles City', 3),
(7, 'Olongapo', 3),
(8, 'San Fernando', 3),
(9, 'Tarlac', 3);

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

ALTER TABLE `city`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<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 class="container" id="dynamicselectboxApp">
		<h3 align="center">Vue.js Axios Dynamic Dependent Select Box with PHP and Mysql</h3>
		<br />
		<div class="panel panel-default">
			<div class="panel-heading">Dynamic Dependent Select Box</div>
			<div class="panel-body">
				<div class="form-group">
					<label>Select Country</label>
					<select class="form-control input-lg" v-model="selcountry" @change="fetchState">
					   <option value="">Select Country</option>
					   <option v-for="data in country_data" :value="data.id">{{ data.country }}</option>
					</select>
				</div>
				
				<div class="form-group">
					<label>Select State</label>
					<select class="form-control input-lg" v-model="selstate" @change="fetchCity">
					   <option value="">Select state</option>
					   <option v-for="data in state_data" :value="data.id">{{ data.name }}</option>
					</select>
				</div>
				
				<div class="form-group">
					<label>Select City</label>
					<select class="form-control input-lg" v-model="selcity">
					   <option value="">Select City</option>
					   <option v-for="data in city_data" :value="data.id">{{ data.cityname }}</option>
					</select>
				</div>
			</div>
		</div>
	</div>
	
<script>
var app = new Vue({
	el:'#dynamicselectboxApp',
	data:{
		selcountry:'',
		country_data:'',
		selstate:'',
		state_data:'',
		selcity:'',
		city_data:''
	},
	
	methods:{
		fetchCountry:function(){
		   axios.post("action.php", {
			postRequest:'country'
		   }).then(function(response){
			app.country_data = response.data;
			app.selstate = '';
			app.state_data = '';
			app.selcity = '';
			app.city_data = '';
		   });
		},
		  
		fetchState:function(){
		   axios.post("action.php", {
			postRequest:'state',
			country_id:this.selcountry
		   }).then(function(response){
			app.state_data = response.data;
			app.selstate = '';
			app.selcity = '';
			app.city_data = '';
		   });
		},
		
		fetchCity:function(){
		   axios.post("action.php", {
			postRequest:'city', 
			state_id:this.selstate
		   }).then(function(response){
			app.city_data = response.data;
			app.selcity = '';
		   });
		}
	},
 
	created:function(){
	  this.fetchCountry();
	}
});
</script>
 </body>
</html>
action.php
//action.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");

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

if($received_data->postRequest == 'country')
{
	$query = "SELECT * FROM country ORDER BY country ASC";
}

if($received_data->postRequest == 'state')
{
	$query = "SELECT * FROM state WHERE country_id = '".$received_data->country_id."' ORDER BY name ASC";
}

if($received_data->postRequest == 'city')
{
	$query = "SELECT * FROM city WHERE stateid = '".$received_data->state_id."' ORDER BY cityname ASC";
} 

$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
	$data[] = $row;
}
echo json_encode($data);
?>

SwiftUI AsyncImage Loading Fetching Data with Asnc and Await

SwiftUI AsyncImage Loading Fetching Data with Asnc and Await

json file : https://dl.dropboxusercontent.com/s/ypknurke7e3062x/swiftuasyncimage.json?dl=0

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

import SwiftUI

struct ContentView: View {

    @ObservedObject var vmodel = ViewModel()

    var body: some View {
        NavigationView {
            ScrollView {
                if vmodel.isFetching {
                    ProgressView()
                }

                VStack {
                    ForEach(vmodel.courses) { asycimage in
                        let url = URL(string: asycimage.imageUrl)
                        AsyncImage(url: url) { image in
                            image.resizable()
                                .scaledToFill()
                        } placeholder: {
                            ProgressView()
                        }

                        Text(asycimage.name)
                    }
                }

            }
            .navigationTitle("AsyncImage Loading")
            .task {
                await vmodel.fetchData()
            }
            .navigationBarItems(trailing: refreshButton)
        }

    }

    private var refreshButton: some View {
        Button {
            Task.init {
                vmodel.courses.removeAll()
                await vmodel.fetchData()
            }

        } label: {
            Text("Refresh")
        }
    }
}

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

import SwiftUI

class ViewModel: ObservableObject {

    @Published var isFetching = false
    @Published var courses = [Course]()

    @Published var errorMessage = ""

    @MainActor
    func fetchData() async {
        let urlString = "https://dl.dropboxusercontent.com/s/ypknurke7e3062x/swiftuasyncimage.json?dl=0"

        guard let url = URL(string: urlString) else { return }

        do {
            isFetching = true
            let (data, response) = try await URLSession.shared.data(from: url)

            if let resp = response as? HTTPURLResponse, resp.statusCode >= 300 {
                self.errorMessage = "Failed to hit endpoint with bad status code"
            }

            self.courses = try JSONDecoder().decode([Course].self, from: data)
            isFetching = false
        } catch {
            isFetching = false
            print("Failed to reach endpoint: \(error)")
        }
    }

}

struct Course: Decodable, Identifiable {
    let id: Int
    let name, link, imageUrl: String
}

Sunday, November 21, 2021

SwiftUI Multiline TextField

SwiftUI Multiline TextField

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

import SwiftUI

struct ContentView: View {
    
    @State var txt = ""
    
    var body: some View {
        VStack{
            HStack{
                Button(action: {
                   
                }) {
                    Text("Cancel")
                }
                 
                Spacer()
                 
                Button(action: {

                }) {
                    Text("Submit").padding()
                }.background(Color.orange)
                .foregroundColor(.white)
                .clipShape(Capsule())
            }
            multilineTextField(txt: $txt)
                .background(Color.orange)
                .cornerRadius(10)
        }.padding()
    }
}

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

struct multilineTextField : UIViewRepresentable {
   
   
  @Binding var txt : String
   
  func makeCoordinator() -> multilineTextField.Coordinator {
      return multilineTextField.Coordinator(parent1 : self)
  }
  func makeUIView(context: UIViewRepresentableContext) -> UITextView {
      let text = UITextView()
      text.isEditable = true
      text.isUserInteractionEnabled = true
      text.text = "Type Something"
      text.textColor = .white
      text.font = .systemFont(ofSize: 20)
      text.delegate = context.coordinator
      text.backgroundColor = .clear
      return text
  }
   
  func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext) {
       
  }
   
  class Coordinator : NSObject,UITextViewDelegate{
      var parent : multilineTextField
      init(parent1 : multilineTextField) {
          parent = parent1
      }
      func textViewDidBeginEditing(_ textView: UITextView) {
          textView.text = ""
          textView.textColor = .black
      }
      func textViewDidChange(_ textView: UITextView) {
          self.parent.txt = textView.text
      }
  }
}

AngularJS Auto complete Textbox

AngularJS Auto complete Textbox

index.html
//index.html
<!DOCTYPE html>  
 <html>  
<head>  
<title>AngularJS Auto complete Textbox</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>  
<style>  
    li{  
        cursor:pointer;  
    }  
    li:hover {  
        background-color:#f9f9f9;  
    }  
</style>  
</head>  
<body>  
<br /><br />  
<div class="container" style="width:600px;">  
    <h1 align="center">AngularJS Auto complete Textbox</h1>  
    <div ng-app="angularautocomplete" ng-controller="membercontroller">  
        <label>Enter Member Name</label>  
        <input type="text" name="members" id="members" ng-model="members" ng-keyup="complete(members)" class="form-control" />  
        <ul class="list-group" ng-model="hidethis" ng-hide="hidethis">  
            <li class="list-group-item" ng-repeat="membersdata in filterMember" ng-click="fillTextbox(membersdata)">{{membersdata}}</li>  
        </ul>  
    </div>  
</div>  
<script>  
	var app = angular.module("angularautocomplete",[]);  
	app.controller("membercontroller", function($scope){  
      $scope.membersList = [  
           "Airi Satou", "Angelica Ramos", "Ashton Cox", "Bradley Greer", "Brenden Wagner", "Brielle Williamson", "Bruno Nash", "Caesar Vance", "Cara Stevens", "Cedric Kelly" 
      ];  
	  
    $scope.complete = function(string){  
        $scope.hidethis = false;  
        var output = [];  
        angular.forEach($scope.membersList, function(members){  
            if(members.toLowerCase().indexOf(string.toLowerCase()) >= 0)  
            {  
                output.push(members);  
            }  
        });  
        $scope.filterMember = output;  
	}  
    $scope.fillTextbox = function(string){  
           $scope.members = string;  
           $scope.hidethis = true;  
    }  
 });  
</script> 
</body>  
</html>  

Angularjs PHP Image Upload With Preview

Angularjs PHP Image Upload With Preview

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <title>Angularjs PHP Image Upload With Preview</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="main-App" ng-controller="MemberController">
<div class="container py-5">
    <header class="text-white text-center">
        <h1 class="display-4">Angularjs PHP Image Upload With Preview</h1>
    </header>
    <div class="row py-4">
        <div class="col-lg-6 mx-auto">

			<form ng-submit="submit()" name="form" role="form">
            <div class="input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm">
                <input id="upload" ng-model="form.image" type="file" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)" class="form-control border-0">
                <label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>
                <div class="input-group-append">
                    <label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
                </div>
            </div>
			
			<input type="submit" id="submit" value="Submit" class="btn btn-info"/>
			
            <!-- Uploaded image area-->
            <p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
            <div class="image-area mt-4"><img ng-src="{{image_source}}" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
			</form>
        </div>
    </div>
</div>
<style>
#upload {
    opacity: 0;
}

#upload-label {
    position: absolute;
    top: 50%;
    left: 1rem;
    transform: translateY(-50%);
}

.image-area {
    border: 2px dashed rgba(255, 255, 255, 0.7);
    padding: 1rem;
    position: relative;
}

.image-area::before {
    content: 'Uploaded image result';
    color: #fff;
    font-weight: bold;
    text-transform: uppercase;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 0.8rem;
    z-index: 1;
}

.image-area img {
    z-index: 2;
    position: relative;
}
body {
    min-height: 100vh;
    background-color: #757f9a;
    background-image: linear-gradient(147deg, #757f9a 0%, #d7dde8 100%);
}
</style>
<script type="text/javascript">
	var app =  angular.module('main-App',[]);
	app.controller('MemberController', function($scope, $http) {

	$scope.form = [];
	$scope.files = [];

	$scope.submit = function() {
	    $scope.form.image = $scope.files[0];
		
		$http({
			method  : 'POST',
			url     : 'upload.php',
			processData: false,
			transformRequest: function (data) { 
			    var formData = new FormData();
			    formData.append("image", $scope.form.image);  
			    return formData;  
			},  
			data : $scope.form,
			headers: {
			       'Content-Type': undefined
			}
		 }).success(function(data){
		    alert(data);
		});
	};

	$scope.uploadedFile = function(element) {
		$scope.currentFile = element.files[0];
		var reader = new FileReader();

		reader.onload = function(event) {
		    $scope.image_source = event.target.result
		    $scope.$apply(function($scope) {
		        $scope.files = element.files;
		      });
		    }
            reader.readAsDataURL(element.files[0]);
		}
	});
	</script>
</body>
</html>
upload.php
//upload.php
<?php
	if(!empty($_FILES['image'])){
		$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
                $image = time().'.'.$ext;
                move_uploaded_file($_FILES["image"]["tmp_name"], 'images/'.$image);
		echo "Profile Image uploaded successfully as ".$image;
	}else{
		echo "Profile Image Is Empty";
	}
?>

Vue.Js Multi Step Form

Vue.Js Multi Step Form

index.html
//index.html
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vue.Js Multi Step Form</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
 </head>
 <body>
<div class="container">
	<h1 class="page-header text-center">Vue.Js Multi Step Form</h1>
	<div id="app">
		<template id="user_detail1" v-if="activePhase == 1">
			<h1>Step 1</h1>
			<div class="form-group col">
				<label>Name</label><input name="name" v-model="user_detail1.name" placeholder="name" class="form-control">
			</div>
			<div class="form-group col">
				<label>Email</label><input name="email" v-model="user_detail1.email" placeholder="email" class="form-control">
			</div>
			<button type="button" @click.prevent="goToStep(2)" class="btn btn-primary">Continue</button>
		</template>
		
		<template id="user_detail2" v-if="activePhase == 2">
			<h1>Step 2</h1>
			<div class="form-group col">
				<label>City</label><input name="city" v-model="user_detail2.city" placeholder="city" class="form-control">
			</div>
			<div class="form-group col">
				<label>State</label><input name="state" v-model="user_detail2.state" placeholder="state" class="form-control">
			</div>
			<button type="button" @click.prevent="goToStep(3)" class="btn btn-primary">Finish</button>
		</template>
		
		<template id="step3" v-if="activePhase == 3">
			<strong>Name:</strong> {{ user_detail1.name }}<br />
			<strong>Email:</strong> {{ user_detail1.email }}<br />
			<strong>City:</strong> {{ user_detail2.city }}<br />
			<strong>State:</strong> {{ user_detail2.state }}
		</template>
	</div>
</div>
<script>
Vue.component('user_detail1', {
    template: '#user_detail1',
    props: [
        'activePhase',
        'user_detail1'
    ]
});

Vue.component('user_detail2', {
    template: '#user_detail2',
    props: [
        'activePhase',
        'user_detail2'
    ]
});

Vue.component('step3', {
    template: '#step3',
    props: [
        'activePhase',
        'user_detail1',
        'user_detail2'
    ]
});

var app = new Vue({
    el: '#app',
    data: {
        activePhase: 1,
        user_detail1: {
            name: '',
            email: ''
        },
        user_detail2: {
            city: '',
            state: ''
        }
    },
    ready: function() {
        console.log('ready');
    },
    methods: {
        goToStep: function(step) {
            this.activePhase = step;
        }
    }
});
</script>
</body>
</html>

Friday, November 19, 2021

Vue.js Axios upload file with PHP

Vue.js Axios upload file with PHP

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>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vue.js Axios upload file with PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <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 class="container" id="vuejsuploadapp">
	   <br />
	   <h3 align="center">Vue.js Axios upload file with PHP</h3>
	   <br />
	   <div v-if="successAlert" class="alert alert-success alert-dismissible">
		  <a href="#" class="close" aria-label="close" @click="successAlert=false">×</a>
		  {{ successMessage }}
	   </div>

	   <div v-if="errorAlert" class="alert alert-danger alert-dismissible">
		  <a href="#" class="close" aria-label="close" @click="errorAlert=false">×</a>
		  {{ errorMessage }}
	   </div>
	   
	    <div class="panel panel-default">
			<div class="panel-heading">
				<div class="row">
				  <div class="col-md-6">
				   <h3 class="panel-title">Upload File</h3>
				  </div>
				  <div class="col-md-6" align="right"></div>
				</div>
			</div>
			<div class="panel-body">
				<div class="row">
				  <div class="col-md-4" align="right">
				   <label>Select Image</label>
				  </div>
				  <div class="col-md-4">
				   <input type="file" ref="file" />
				  </div>
				  <div class="col-md-4">
				   <button type="button" @click="btnUpload" class="btn btn-success">Upload Image</button>
				  </div>
				</div>
			 <br />
			 <br />
			 <div v-html="uploadedImage" align="center"></div>
			</div>
	    </div>
  </div>
<script>
var application = new Vue({
	 el:'#vuejsuploadapp',
	 data:{
		file:'',
		successAlert:false,
		errorAlert:false,
		uploadedImage:'',
	 },
	 methods:{
	    btnUpload:function(){
			application.file = application.$refs.file.files[0];

			var formData = new FormData();

			formData.append('file', application.file);

			axios.post('upload.php', formData, {
				header:{
					'Content-Type' : 'multipart/form-data'
				}
			}).then(function(response){
				if(response.data.image == '') {
					 application.errorAlert = true;
					 application.successAlert = false;
					 application.errorMessage = response.data.message;
					 application.successMessage = '';
					 application.uploadedImage = '';
				}else{
				 application.errorAlert = false;
					 application.successAlert = true;
					 application.errorMessage = '';
					 application.successMessage = response.data.message;
					 var image_html = "<img src='"+response.data.image+"' class='img-thumbnail' width='500' />";
					 application.uploadedImage = image_html;
					 application.$refs.file.value = '';
				}
		   });
	   
	  }
	},
});
</script>
 </body>
</html>
upload.php
//upload.php
<?php
$image = '';
if(isset($_FILES['file']['name']))
{
	$image_name = $_FILES['file']['name'];
	$valid_extensions = array("jpg","jpeg","png");
	$extension = pathinfo($image_name, PATHINFO_EXTENSION);
	if(in_array($extension, $valid_extensions)){
		$upload_path = 'upload/' . time() . '.' . $extension;
		if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)){
		   $message = 'Image Succesfully Uploaded';
		   $image = $upload_path;
		}else{
		   $message = 'There is an error while uploading image';
		}
	}else{
	  $message = 'Only .jpg, .jpeg and .png Image allowed to upload';
	}
}else{
	$message = 'Select Image';
}

$output = array(
 'message'  => $message,
 'image'   => $image
);

echo json_encode($output);
?>

Related Post