article

Monday, March 28, 2022

ReactJS PHP Mysqli Export Data Table into EXCEL Sheet

ReactJS PHP Mysqli Export Data Table into EXCEL Sheet


Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

ReactHTMLTableToExcel
Provides a client side generation of Excel (.xls) file from HTML table element.

react-html-table-to-excel
https://www.npmjs.com/package/react-html-table-to-excel

Install
npm install --save react-html-table-to-excel
C:\reactdev\myreactdev>npm install --save react-html-table-to-excel

run
C:\reactdev\myreactdev>npm start

Database table

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,
  `date_of_join` date NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

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


//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min.js'

ReactDOM.render(
  ,
  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 {useState,useEffect} from 'react';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
  
function App(){
 
    const[result,setResult]= useState([]);
 
    const getData = ()=>
    {
        fetch('http://localhost/devtest/reactjs/employee.php')
        .then(response => response.json())
        .then(res => setResult( res));
    }
    
    useEffect(() => {
        getData();
    },)
 
        return (
            <div className="container">
                <h3 className="mt-3 text-success"><center>ReactJS PHP Mysqli Export Data Table into EXCEL Sheet</center></h3>
                <div className="row mt-4">
                <ReactHTMLTableToExcel
                    id="test-table-xls-button"
                    className="download-table-xls-button btn btn-success mb-3"
                    table="table-to-xls"
                    filename="tablexls"
                    sheet="tablexls"
                    buttonText="Export Data to Excel Sheet"/>
                   <table className="table" id="table-to-xls">
                    <thead className="thead-dark">
                    <tr>
                        <th>Name</th>
                        <th>Position</th>
                        <th>Office</th>
                        <th>Age</th>
                        <th>Salary</th>
                        <th>Date Hire</th>
                    </tr>
                    </thead>
                    <tbody>
                   
                         {result.map((res)=>
                            <tr>
                            <td>{res.name}</td>
                            <td>{res.position}</td>
                            <td>{res.office}</td>
                            <td>{res.age}</td>
                            <td>{res.salary}</td>
                            <td>{res.date_of_join}</td>
                            </tr>
                          )}   
                       
                    </tbody>   
                </table>
             </div>
            </div>
        );
    }
  
export default App
employee.php http://localhost/devtest/reactjs/employee.php
//employee.php http://localhost/devtest/reactjs/employee.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

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

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
		$sql = "select * from employee"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    echo ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();

Sunday, March 27, 2022

ReactJs PHP Mysqli Select Country State Dropdown Select Box

ReactJs PHP Mysqli Select Country State Dropdown Select Box

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

Database Table

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'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(171, 'Philippines'),
(226, 'United Kingdom'),
(227, 'United States of America'),
(228, 'Uruguay');

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

ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=243;
  
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;
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min.js'

ReactDOM.render(
  ,
  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, { useState, useEffect } from "react";

function Country() {
  const [country, setCountry]= useState([]);
  const [countryid, setCountryid]= useState('');
  const [stetes, setSat]= useState([]);

  useEffect( ()=>{
   const getcountry= async ()=>{
     const req= await fetch("http://localhost/devtest/reactjs/country.php");
     const getres= await req.json();
     console.log(getres);
     setCountry(await getres);

   }
   getcountry();


  },[]);

  const handlecountry=(event)=>{
    const getcoutryid= event.target.value;
    setCountryid(getcoutryid);
    event.preventDefault();
  }

  useEffect( ()=>{

    const getstate= async ()=>{
      const resstate= await fetch(`http://localhost/devtest/reactjs/state.php?id=${countryid }`);
      const getst= resstate.json();
	  console.log(getst);
      setSat(await getst);

    }
    getstate();

  },[countryid]);

   
  return (
    <div className="container">
     <div className="row">
       <div className="col-sm-12">
         <h5 className="mt-4 mb-4 fw-bold">ReactJs PHP Mysqli Select Country State Dropdown Select Box</h5>
           
             <div className="row mb-3">
                 <div className="form-group col-md-4">
                 <label className="mb-2">Country</label>
                 <select name="country" className="form-select" onChange={(e)=>handlecountry(e)}>
                   <option>--Select Country--</option>
                   {
                     country.map( (getcon)=>(
                   <option key={getcon.id} value={getcon.id }> { getcon.country}</option>
                     ))
                }
                 
                 </select>
               </div>
               <div className="form-group col-md-4">
               <label className="mb-2">State</label>
               <select name="state" className="form-select">
                   <option>--Select State--</option>
                   {
                     stetes.map( (st,index)=>(                    
                   <option key={index} value={st.id}>{ st.name}</option>
                     ))
                     }
                 </select>
               </div>

               <div className="form-group col-md-2 mt-4">              
               <button className="btn btn-success mt-2" >Submit</button>               
               </div>
            </div>
               
       </div>
     </div>
    </div>
  );
}
export default Country;
country.php http://localhost/devtest/reactjs/country.php
//country.php http://localhost/devtest/reactjs/country.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

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

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from country"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    echo ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();
state.php http://localhost/devtest/reactjs/state.php?id=171
//state.php http://localhost/devtest/reactjs/state.php?id=171
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

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

$method = $_SERVER['REQUEST_METHOD'];

if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
	      if(isset($_GET["id"])){
			$id = $_GET['id'];  
		  } 
		$sql = "select * from state".($id?" where country_id=$id":''); 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
	
	$total = mysqli_num_rows($result); 
	if ($total <= 0) {
		echo '[';
		$arr = array('id' => "0", 'name' => "No Record Found");
		echo json_encode($arr);
		echo ']';
	}else{
	echo '[';
	for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
		echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
	}
	echo ']';
	}
}else {
    echo mysqli_affected_rows($con);
}
$con->close();

ReactJS PHP Mysqli Display Record in Modal Box | Bootstrap Modal

ReactJS PHP Mysqli Display Record in Modal Box | Bootstrap Modal

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

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,
  `date_of_join` date NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

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

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

URL : http://localhost/devtest/reactjs/employee.php
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min.js'

ReactDOM.render(
  ,
  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';
 
const Dashboard = () => {
   
  const[record,setRecord] = useState([])
  const [rs,setrs] = useState({
     id:'',
     userName:'',
     username:'',
     email:'',
     website:''
  })
 
   const getData = () =>
   {
       fetch('http://localhost/devtest/reactjs/employee.php')
       .then(resposne=> resposne.json())
       .then(res=>setRecord(res))
   }
 
   useEffect(() => {
      getData();
   },[])
   
    const showDetail = (id) =>
    {
      
      fetch(`http://localhost/devtest/reactjs/employee.php?id=${id}`)
      .then(resposne=> resposne.json())
      .then(res=>setrs(res))
    }
 
 
    return (
    <div class="container mt-2">
        <div class="row mt-2 ">
            <div class="col-lg-1 col-md-6 col-sm-12">
            </div>  
            <div class="col-lg-11 col-md-6 col-sm-12">
              <h4 class="mt-3 mb-3 text-secondary">
               ReactJS PHP Mysqli Display Record in Modal Box | Bootstrap Modal
              </h4>
                <div class=" mt-5">
                    <table class="table table-striped table-sm">
                        <thead class="thead-light">
                            <tr>
                                <th>No</th>
                                <th>Name</th>
                                <th>Position</th>
                                <th>Show Details</th>
                            </tr>
                        </thead>
                        <tbody>
                        
                          {record.map((names,index)=>
                           <tr key={index}>
                               <td>{names.id}</td>
                              <td>{names.name}</td>
                              <td>{names.position}</td>
                              <td><button class="btn btn-primary" onClick={(e)=>showDetail(names.id)} data-bs-toggle="modal" data-bs-target="#myModal">View Details</button></td>
                           </tr>
                           )}
                        </tbody>
                    </table>
                </div>
            </div>
            
        </div>


      <div class="modal" id="myModal">
        <div class="modal-dialog" style={{width:"700px"}}>
          <div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="exampleModalLabel">Employee Details</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
            <div class="modal-body">
				<p>Employee ID : {rs.id}</p>
				<p>Name : {rs.name}</p>
				<p>Position : {rs.position}</p>
				<p>Office : {rs.office}</p>
				<p>Age : {rs.age}</p>
				<p>Salary : {rs.salary}</p>
				<p>Date Hire : {rs.date_of_join}</p>
            </div>
             
            <div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
			</div>
             
          </div>
        </div>
      </div>
 
    </div>
    )
}
 
 
export default Dashboard
employee.php http://localhost/devtest/reactjs/employee.php
//employee.php http://localhost/devtest/reactjs/employee.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 
$id = '';

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

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
	      if(isset($_GET["id"])){
			$id = $_GET['id'];  
		  } 
		//$sql = "select * from employee"; 
		$sql = "select * from employee".($id?" where id=$id":''); 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    if (!$id) echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    if (!$id) echo ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();

ReactJS Display Record in Modal Box Bootstrap Modal with json API

ReactJS Display Record in Modal Box Bootstrap Modal with json API

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start


src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.min.js'

ReactDOM.render(
  ,
  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';
 
const Dashboard = () => {
   
  const[record,setRecord] = useState([])
  const [rs,setrs] = useState({
     id:'',
     userName:'',
     username:'',
     email:'',
     website:''
  })
 
   const getData = () =>
   {
       fetch('https://jsonplaceholder.typicode.com/users/')
       .then(resposne=> resposne.json())
       .then(res=>setRecord(res))
   }
 
   useEffect(() => {
      getData();
   },[])
   
    const showDetail = (id) =>
    {
      
      fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
      .then(resposne=> resposne.json())
      .then(res=>setrs(res))
    }
 
 
    return (
    <div class="container mt-2">
        <div class="row mt-2 ">
            <div class="col-lg-1 col-md-6 col-sm-12">
            </div>  
            <div class="col-lg-11 col-md-6 col-sm-12">
              <h4 class="mt-3 mb-3 text-secondary">
               ReactJS Display Record in Modal Box Bootstrap Modal with json API
              </h4>
                <div class=" mt-5">
                    <table class="table table-striped table-sm">
                        <thead class="thead-light">
                            <tr>
                                <th>No</th>
                                <th>Name</th>
                                <th>Username</th>
                                <th>Show Details</th>
                            </tr>
                        </thead>
                        <tbody>
                        
                          {record.map((names,index)=>
                           <tr key={index}>
                               <td>{names.id}</td>
                              <td>{names.name}</td>
                              <td>{names.username}</td>
                              <td><button class="btn btn-primary" onClick={(e)=>showDetail(names.id)} data-bs-toggle="modal" data-bs-target="#myModal">View Details</button></td>
                           </tr>
                           )}
                        </tbody>
                    </table>
                </div>
            </div>
            
        </div>


      <div class="modal" id="myModal">
        <div class="modal-dialog" style={{width:"700px"}}>
          <div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="exampleModalLabel">Employee Details</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
            <div class="modal-body">
				<p>Employee ID : {rs.id}</p>
				<p>Name : {rs.name}</p>
				<p>Username : {rs.username}</p>
				<p>Email : {rs.email}</p>
				<p>Website : {rs.website}</p>
            </div>
             
            <div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
			</div>
             
          </div>
        </div>
      </div>
 
    </div>
    )
}
 
 
export default Dashboard

React js Contact form validation

React js Contact form validation

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  ,
  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, {  useState, useEffect } from "react";

function Contact() {

    const [formvalue, setFormvalue]= useState({ name:'',email:'',address:''});
    const [formerror, setFormerror] = useState({});
    const [issubmit, setSubmit]= useState(false);

    const handlevalidation =(e)=>{
        const {name, value}= e.target;
        setFormvalue({...formvalue, [name]: value});
    }
    const handlesubmit= (e)=>{
        e.preventDefault();
        setFormerror(validationform(formvalue));
        setSubmit(true);
    }
    const validationform = (value)=>{
        const errors= {};
        const emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        if(!value.name){
            errors.name="Please Enter Name";
        }

        if(!value.email){
            errors.email="Please Enter Email";
        } else if(!emailPattern.test(value.email))
        {
            errors.email="Enter Valid Email";
        }
        if(!value.address){
            errors.address="Please Enter Address";
        }

        return errors;
    }

    useEffect( ()=>{
        if(Object.keys(formerror).length===0 && issubmit)
        {
            console.log(formvalue);
        }
    },[formerror, formvalue, issubmit]);
	
 return (
        <div className="container">
        <div className="row mb-5">
			<div className="col-sm-6 text-success">
				<h3 className="fw-bold"> React js Contact form validation</h3>
            </div>

            <form onSubmit={ handlesubmit} >

                <div className="row mb-4">
                    <label className="col-sm-2 col-form-label">Name<span className="astriccolor">*</span></label>
                    <div className="col-sm-5">
                    <input type="text" className="form-control" name="name" value={ formvalue.name}  onChange={ handlevalidation} />
                    <span className="text-danger">{ formerror.name } </span>
                    </div>
                </div>

                <div className="row mb-4">
                    <label className="col-sm-2 col-form-label">Email<span className="astriccolor">*</span></label>
                    <div className="col-sm-5">
                    <input type="text" className="form-control" name="email" value={ formvalue.email} onChange={ handlevalidation}   />
                    <span className="text-danger">{ formerror.email}  </span>
                    </div>
                </div>

                <div className="row mb-4">
                    <label className="col-sm-2 col-form-label">Address<span className="astriccolor">*</span></label>
                    <div className="col-sm-5">
                    <textarea  className="form-control" name="address" value={ formvalue.address} onChange={ handlevalidation}   />
                    <span className="text-danger">{ formerror.address}  </span>
                    </div>
                </div>

                <div className="row mb-4">
                    <label className="col-sm-2 col-form-label"></label>
                    <div className="col-sm-10">
                    <button className="btn btn-success" name="button">Submit</button>
                </div>
                </div>
                </form>
            </div>
        </div>
  );
}

export default Contact;

Saturday, March 26, 2022

ReactJS Add Remove Inputs Fields Dynamically


ReactJS Add Remove Inputs Fields Dynamically

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  ,
  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, { useState } from "react";

function Addmoreinput() {
  const [inputList, setinputList]= useState([{firstName:'', lastName:''}]);

  const handleinputchange=(e, index)=>{
    const {name, value}= e.target;
    const list= [...inputList];
    list[index][name]= value;
    setinputList(list);

  }
 
  const handleremove= index=>{
    const list=[...inputList];
    list.splice(index,1);
    setinputList(list);
  }

  const handleaddclick=()=>{ 
    setinputList([...inputList, { firstName:'', lastName:''}]);
  }
  return (
	<div className="container">
        <div className="row">
        <div className="col-sm-12">
         <h5 className="mt-3 mb-4 fw-bold">ReactJS Add Remove Inputs Fields Dynamically</h5>
           
            { 
            inputList.map( (x,i)=>{
              return(
              <div className="row mb-3">
                 <div class="form-group col-md-4">
                 <label >First Name</label>
                  <input type="text"  name="firstName" class="form-control"  placeholder="Enter First Name" onChange={ e=>handleinputchange(e,i)} />
               </div>
               <div class="form-group col-md-4">
               <label >Last Name</label>
                  <input type="text"  name="lastName" class="form-control"   placeholder="Enter Last Name" onChange={ e=>handleinputchange(e,i) }/>
               </div>
               <div class="form-group col-md-2 mt-4">
               {
                  inputList.length!==1 &&
                  <button  className="btn btn-danger mx-1" onClick={()=> handleremove(i)} style={{marginBottom: 10}}>Remove</button>
               }
               { inputList.length-1===i &&
               <button  className="btn btn-success" onClick={ handleaddclick}>Add More</button>
               }
               </div>
            </div>
              );
             } )} 

               
       </div>
     </div>
    </div>
  );
}
export default Addmoreinput;

ReactJS AutoComplete Textbox with PHP and Mysqli | Filter Search

ReactJS AutoComplete Textbox with PHP and Mysqli | Filter Search

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

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'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica');

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

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

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  ,
  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, { useState, useEffect } from "react";

function Search() {
  const [allcountry, setAllcountry] = useState([]);
  const [filterresult, setFilterresult] = useState([]);
  const [serachcountry, setSearchcountry] = useState("");

  const handlesearch = (event) => {
    const search = event.target.value;
    console.log(search);
    setSearchcountry(search);

    if (search !== "") {
      const filterdata = allcountry.filter((item) => {
        return Object.values(item)
          .join("")
          .toLowerCase()
          .includes(search.toLowerCase());
      });
      setFilterresult(filterdata);
    } else {
      setFilterresult(allcountry);
    }
  };

  useEffect(() => {
    const getcountry = async () => {
      const getres = await fetch("http://localhost/devtest/reactjs/country.php");
      const setcounty = await getres.json();
      console.log(setcounty);
      setAllcountry(await setcounty);
    };
    getcountry();
  }, []);

  return (
      <div className="container">
        <div className="row"><p><h3>ReactJS AutoComplete Textbox with PHP and Mysqli | Filter Search</h3></p>
          <div className="col-md-6 mb-3 mt-3">
            <input
              type="text"
              className="form-control"
              placeholder="Enter Keyword"
              onChange={(e) => {
                handlesearch(e);
              }}
            />
            <table className="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Country ID </th>
                  <th>Country Name</th>
                </tr>
              </thead>
              <tbody>
                {serachcountry.length > 1
                  ? filterresult.map((filtercountry, index) => (
                      <tr key={index}>
                        <td> {filtercountry.id} </td>
                        <td> {filtercountry.country} </td>
                      </tr>
                    ))
                  : allcountry.map((getcon, index) => (
                      <tr key={index}>
                        <td> {getcon.id} </td>
                        <td> {getcon.country} </td>
                      </tr>
                    ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
  );
}

export default Search;
http://localhost/devtest/reactjs/country.php

country.php
//country.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

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

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from country"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    echo ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();

ReactJS Dropdown List all Country with PHP Mysqli

ReactJS Dropdown List all Country with PHP Mysqli

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

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'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica');

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

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

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  ,
  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, { useState, useEffect } from "react";

function Country() {
  const [country, setCountry]= useState([]);

  useEffect( ()=>{
   const getcountry= async ()=>{
     const req= await fetch("http://localhost/devtest/reactjs/country.php");
     const getres= await req.json();
     console.log(getres);
     setCountry(await getres);

   }
   getcountry();


  },[]);

  const handlecountry=(event)=>{
    const getcoutryid= event.target.value;
    alert(getcoutryid)
    event.preventDefault();
  }

  return (
    <div className="container">
     <div className="row">
       <div className="col-sm-12">
         <h5 className="mt-4 mb-4 fw-bold">ReactJS Dropdown List all Country with PHP Mysqli </h5>
           
             <div className="row mb-3">
                 <div className="form-group col-md-4">
                 <label className="mb-2">Country</label>
                 <select name="country" className="form-select" onChange={(e)=>handlecountry(e)}>
                   <option>--Select Country--</option>
                   {
                     country.map( (getcon)=>(
                   <option key={getcon.id} value={getcon.id }> { getcon.country}</option>
                     ))
					}
                 
                 </select>
               </div>
            </div>
               
       </div>
     </div>
    </div>
  );
}
export default Country;
country.php
//country.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

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

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from country"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    echo ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();

Friday, March 25, 2022

Python Django Inserting Data Using Jquery Ajax

Python Django Inserting Data Using Jquery Ajax

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js


testdev/urls.py
 
//testdev/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
	path('', views.index, name='index'),
	path('insert', views.insert, name='insert'),
    path('admin/', admin.site.urls),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect
from .models import Member

# Create your views here.
def index(request):
    members = Member.objects.all()
    return render(request, 'insertajax/index.html', {'members': members})

def insert(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], address=request.POST['address'])
    member.save()
    return redirect('/')
myapp/models.py
 
//myapp/models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    address = models.CharField(max_length=50)

    def __str__(self):
        return self.firstname + " " + self.lastname
myapp/templates/insertajax/index.html
 
//myapp/templates/insertajax/index.html
{% extends 'insertajax/base.html' %}
{% block body %}
    <form method="POST">
        {% csrf_token %}
        <div class="mb-3">
            <label>Firstname</label>
               <input type="text" id="firstname" class="form-control"/>
        </div>        
		<div class="mb-3">
            <label>Lastname</label>
            <input type="text" id="lastname" class="form-control"/>
        </div>
        <div class="mb-3">
            <label>Address</label>
            <input type="text" id="address" class="form-control"/>
        </div>
        <div class="mb-3">
            <button type="button" class="btn btn-primary form-control" id="submit" style="width:300px;">Submit</button>
        </div>
    </form>
    <hr style="border-top:1px solid #000; clear:both;"/>
    <table class="table table-bordered">
        <thead class="alert-warning">
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
            {% for member in members %}
            <tr>
                <td>{{ member.firstname }}</td>
                <td>{{ member.lastname }}</td>
                <td>{{ member.address  }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}		
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
	<title>Python Django Inserting Data Using Jquery Ajax </title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<div class="container">
    <div class="row">
        <p><h3 class="text-primary">Python Django Inserting Data Using Jquery Ajax</h3></p>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</div>	
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</html>
myapp/static/js/script.js
 
//myapp/static/js/script.js
$(document).ready(function(){
    $('#submit').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
        $address = $('#address').val();

        if($firstname == "" || $lastname == "" || $address == ""){
            alert("Please complete field");
        }else{
            $.ajax({
                type: "POST",
                url: "insert",
                data:{
                    firstname: $firstname,
                    lastname: $lastname,
                    address: $address,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    alert('Save Data');
                    $('#firstname').val('');
                    $('#lastname').val('');
                    $('#address').val('');
                    window.location = "/";
                }
            });
        }
    });
});
Register App myapp
devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
	'myapp',
]

migration

C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate

Thursday, March 24, 2022

SwiftUI Highlight and Shake Invalid Username and Password with show password toggle

SwiftUI Highlight and Shake Invalid Username and Password with show password toggle

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var username = ""
    @State var password = ""
    @State var invalidpassword = 0
    @State var invalidusername = 0
    @State private var showText: Bool = false
    
    var body: some View {
        VStack {
            HStack{
                Image("logo")
                    .resizable()
                    .frame(width: 150, height: 130, alignment: .center)
            }
            
            HStack {
                Image(systemName: "person")
                    .foregroundColor(.gray)
                TextField("Username", text: $username)
            }
            .padding()
            .background(Color("Color"))
            .cornerRadius(8)
            .overlay(RoundedRectangle(cornerRadius: 8)
                .stroke(lineWidth: 1)
                .foregroundColor(invalidusername == 0 ? Color.clear : Color.red)
            )
            .padding(.bottom, 20)
            .modifier(ShakeEffect(animatableData: CGFloat(invalidusername)))
            
            HStack {
                Image(systemName: "lock")
                    .foregroundColor(.gray)
                if showText {
                    TextField("", text: $password)
                }else {
                    SecureField("Password", text: $password)
                }
                Button(action: {
                    showText.toggle()
                }, label: {
                    Image(systemName: showText ? "eye.slash.fill" : "eye.fill")
                        .foregroundColor(.gray)
                })
            }
            .padding()
            .background(Color("Color"))
            .cornerRadius(8)
            .overlay(RoundedRectangle(cornerRadius: 8)
                .stroke(lineWidth: 1)
                .foregroundColor(invalidpassword == 0 ? Color.clear : Color.red)
            )
            .padding(.bottom, 20)
            .modifier(ShakeEffect(animatableData: CGFloat(invalidpassword)))
            
            Button(action: {
            
            }, label: {
                Text("Forgot password").padding()
            })
            
            Button(action: {
                withAnimation(.default) {
                    loginUser()
                }
            }, label: {
                Text("Login")
                    .font(.headline).bold().foregroundColor(.white).padding()
                    .frame(width: 250, height: 50)
                    .background(Color.blue)
                    .cornerRadius(10)
            })
            
            HStack {
                Text("Don't have an account?")
                
                Button(action: {
                    
                }, label: {
                    Text("Sign Up")
                })
            }.padding()
            
        }.padding()
    }
    
    private func loginUser() {
        if username == "" {
            self.invalidusername += 1
            print("Username is required")
        } else if password == "" {
            self.invalidpassword += 1
            self.invalidusername = 0
            print("password is required")
        }else {
            self.invalidpassword = 0
            print("email : \(username) pass : \(password)")
        }
    }
}

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

struct ShakeEffect : GeometryEffect {
    var travelDistance : CGFloat = 6
    var numOfShake : CGFloat = 4
    var animatableData: CGFloat
    
    func effectValue(size: CGSize) -> ProjectionTransform {
        ProjectionTransform(CGAffineTransform(translationX: travelDistance * sin(animatableData * .pi * numOfShake), y: 0))
    }
}

Jquery Ajax Image Upload with PHP MySQLi

Jquery Ajax Image Upload with PHP MySQLi

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `tbluploadphoto` (
  `photoid` int(11) NOT NULL,
  `location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `tbluploadphoto`
  ADD PRIMARY KEY (`photoid`);


ALTER TABLE `tbluploadphoto`
  MODIFY `photoid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


index.php
//index.php
<!DOCTYPE html>
<html>
<head>
    <title>Jquery Ajax Image Upload with PHP MySQLi</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
  <div class="row">
      <form>
        <h2 align="center" style="color:blue">Jquery Ajax Image Upload with PHP MySQLi</h2>
        <label>Select Image:</label>
        <input type="file" name="file" id="file"><br>
        <button type="button" id="upload_button" class="btn btn-primary">Upload</button>
      </form>
  </div>
  <div style="width:80%; padding:auto; margin:auto;">
      <div id="imagelist"></div>
  </div>
</div>
<script>
$(document).ready(function(){

  showPhoto();

  $(document).on('click', '#upload_button', function(){
	  
    var name = document.getElementById("file").files[0].name;
    var form_data = new FormData();
    var ext = name.split('.').pop().toLowerCase();
    if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1){
      alert("Invalid Image File");
    }
	
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("file").files[0]);
    var f = document.getElementById("file").files[0];
    var fsize = f.size||f.fileSize;
	
    if(fsize > 2000000){
      alert("Image File Size is very big");
    }else{
		form_data.append("file", document.getElementById('file').files[0]);
		$.ajax({
		  url:"upload.php",
		  method:"POST",
		  data: form_data,
		  contentType: false,
		  cache: false,
		  processData: false,   
		  success:function(){
			showPhoto();
		  }
		});
    }
	
  });
});

function showPhoto(){
  $.ajax({
      url:"fetch_photo.php",
      method:"POST",
      data:{
        fetch:1,
      },
      success:function(data){
        $('#imagelist').html(data);
      }
    });
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch_photo.php
//fetch_photo.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		$inc=4;
		$query=mysqli_query($conn,"select * from tbluploadphoto");
		while($row=mysqli_fetch_array($query)){
		$inc = ($inc == 4) ? 1 : $inc+1; 
		if($inc == 1) echo '<div class="row">';  
 			?>
				<div class="col-lg-3"><img src="<?php echo $row['location']?>" style="height:200px; width:100%;"></div>
 
			<?php
		if($inc == 4) echo '</div>';
		}
		if($inc == 1) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div><div class="col-lg-3"></div></div>'; 
		if($inc == 2) echo '<div class="col-lg-3"></div><div class="col-lg-3"></div></div>'; 
		if($inc == 3) echo '<div class="col-lg-3"></div></div>'; 
	}
?>
uppload.php
//uppload.php
<?php
include('conn.php');
if($_FILES["file"]["name"] != '')
{
 	$newFilename = time() . "_" . $_FILES["file"]["name"];
 	$location = 'upload/' . $newFilename;  
	move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 	
 	mysqli_query($conn,"insert into tbluploadphoto (location) values ('$location')");
}
?>

Tuesday, March 22, 2022

PHP MySQLi Delete Multiple Rows using Checkbox

PHP MySQLi Delete Multiple Rows using Checkbox

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) 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');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP MySQLi Delete Multiple Rows using Checkbox</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
	<div class="row" style="margin-top:20px;margin-bottom:20px;">
	<span style="font-size:25px; color:blue"><center><strong>PHP MySQLi Delete Multiple Rows using Checkbox</strong></center></span>	
		<div style="height:20px;"></div>
		<table class="table table-striped table-bordered table-hover">
			<thead>
				<th></th>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
				
			</thead>
			<form method="POST" action="delete.php">
			<tbody>
			<?php
				include('conn.php');
				
				$query=mysqli_query($conn,"select * from members");
				while($row=mysqli_fetch_array($query)){
					?>
					<tr>
						<td align="center"><input type="checkbox" value="<?php echo $row['id']; ?>" name="userid[]"></td>
						<td><?php echo $row['firstname']; ?></td>
						<td><?php echo $row['lastname']; ?></td>
						<td><?php echo $row['address']; ?></td>		
					</tr>
					<?php
				}
			
			?>
			</tbody>
		</table>
			<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnew" style="width:200px;"> Add New</button> ||
			<button type="submit" class="btn btn-danger" style="width:200px;"> Delete</button>
			</form>
	</div>
	<?php include('modal.php'); ?>
</div>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
modal.php
//modal.php
<!-- Modal -->
<div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="addnew" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addnew">Add New</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
				<form method="POST" action="addnew.php">
					<div class="row">
						<div class="col-lg-2">
							<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-lg-10">
							<input type="text" class="form-control" name="firstname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-lg-2">
							<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-lg-10">
							<input type="text" class="form-control" name="lastname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-lg-2">
							<label class="control-label" style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-lg-10">
							<input type="text" class="form-control" name="address">
						</div>
					</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save</button>
		</form>
      </div>
    </div>
  </div>
</div>
addnew.php
//addnew.php
<?php
	include('conn.php');
	
	$firstname=$_POST['firstname'];
	$lastname=$_POST['lastname'];
	$address=$_POST['address'];
	
	mysqli_query($conn,"insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	header('location:index.php');
?>
delete.php
//delete.php
<?php
	include('conn.php');
	
	if(isset($_POST['userid'])){
		foreach ($_POST['userid'] as $id):
			mysqli_query($conn,"delete from members where id='$id'");
		endforeach;
		
		header('location:index.php');
	}
	else{
		?>
		<script>
			window.alert('Please check user to Delete');
			window.location.href='index.php';
		</script>
		<?php
	}
?>

Thursday, March 17, 2022

SwiftUI Note App UserDefaults

SwiftUI Note App UserDefaults

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @StateObject var notes = Notes()
    @State private var sheetIsShowing = false
    
    var body: some View {
        NavigationView {
            VStack {
                NoteView()
                    .sheet(isPresented: $sheetIsShowing) {
                        AddNew()
                    }
            }
            .navigationTitle("Notes")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        withAnimation {
                            self.sheetIsShowing.toggle()
                        }
                    } label: {
                        Label("Add Note", systemImage: "plus.circle.fill")
                    }
                }
            }
        }
        .environmentObject(notes)
    }
    
}

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

import Foundation
import SwiftUI

struct Note : Codable, Identifiable {
    var id = UUID()
    var title: String
    var content: String
    var timeStamp: String
}

@MainActor class Notes : ObservableObject {
    private let NOTES_KEY = "cairocodersnoteskey"
    let date = Date()
    var notes: [Note] {
        didSet {
            saveData()
            objectWillChange.send()
        }
    }
    
    init() {
        // Load saved data
        if let data = UserDefaults.standard.data(forKey: NOTES_KEY) {
            if let decodedNotes = try? JSONDecoder().decode([Note].self, from: data) {
                notes = decodedNotes
                return
            }
        }
        // Tutorial Note
        notes = [Note(title: "Test Note", content: "Tap add button. You can delete any note by swiping to the left!", timeStamp: date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss"))]
    }
    
    func addNote(title: String, content: String) {
        let tempNote = Note(title: title, content: content, timeStamp: date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss"))
        notes.insert(tempNote, at: 0)
        saveData()
    }
    
    // Save data
    private func saveData() {
        if let encodedNotes = try? JSONEncoder().encode(notes) {
            UserDefaults.standard.set(encodedNotes, forKey: NOTES_KEY)
        }
    }
}

extension Date {
   func getFormattedDate(format: String) -> String {
        let dateformat = DateFormatter()
        dateformat.dateFormat = format
        return dateformat.string(from: self)
    }
}
NoteView.swift
 
//
//  NoteView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct NoteView: View {
    @EnvironmentObject var notes: Notes
    
    var body: some View {
        List {
            ForEach(notes.notes) { note in
                VStack(alignment: .leading) {
                    Text(note.title)
                        .foregroundColor(.blue)
                        .font(.headline)
                    Text(note.content)
                        .font(.body)
                        .padding(.vertical)
                
                    HStack {
                        Spacer()
                        Text("\(note.timeStamp)")
                            .foregroundColor(.gray)
                            .italic()
                    }
                }
            }
            .onDelete(perform: deleteNote)
        }
    }
    
    func deleteNote(at offsets: IndexSet) {
        notes.notes.remove(atOffsets: offsets)
    }
}

struct NoteView_Previews: PreviewProvider {
    static var previews: some View {
        NoteView()
            .environmentObject(Notes())
    }
}
AddNew.swift
 
//
//  AddNew.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct AddNew: View {
    @State private var title = ""
    @State private var content = ""
    @EnvironmentObject var notes: Notes
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        Form {
            Section {
                TextField("Give your note a title", text: $title)
                ZStack {
                    TextEditor(text: $content)
                        .frame(height: 200)
                    VStack {
                        Spacer()
                        HStack {
                            Spacer()
                            Text("\(content.count)/120")
                                .foregroundColor(.gray)
                                .padding()
                        }
                    }
                }
                HStack {
                    Spacer()
                    Button("Add note!") {
                        notes.addNote(title: title, content: content)
                        dismiss()
                    }
                    Spacer()
                }
            }
        }
    }
}

struct AddNew_Previews: PreviewProvider {
    static var previews: some View {
        AddNew()
            .environmentObject(Notes())
    }
}

Angular.js PHP OOP CRUD (Create Read Update and Delete)

Angular.js PHP OOP CRUD (Create Read Update and Delete)

https://angularjs.org/ version 1.8.2

CDN : https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

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

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

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


index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8"> 
	<title>Angular.js PHP OOP CRUD (Create Read Update and Delete)</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container">
	<h1 class="page-header">Angular.js PHP OOP CRUD (Create Read Update and Delete) </h1>
	<div class="row">
		<div ng-app="mem_app" ng-controller="controller" ng-init="showdata()">
			<div class="row">
				<form ng-submit="myFunc()">
					<h3>Member Form</h3>
					<hr>
					<div class="form-group">
				    	<label for="firstname">Firstname</label>
				    	<input type="text" class="form-control" id="firstname" name="firstname" ng-model="firstname" placeholder="Enter Firstname">
				  	</div>
				  	<div class="form-group">
				    	<label for="lastname">Lastname</label>
				    	<input type="text" class="form-control" id="lastname" name="lastname" ng-model="lastname" placeholder="Enter Lastname">
				  	</div>
					<div class="form-group">
				    	<label for="address">Address</label>
				    	<input type="text" class="form-control" id="address" name="address" ng-model="address" placeholder="Enter Address">
				  	</div>
				  	<hr>
					
				  	<button type="submit" class="{{btnClass}}" ng-click="insert()"><i class="{{icon}}"></i>  {{btnName}}</button>
				</form>
			</div>
			<div class="row">
				<h3>Member List</h3>
				<table class="table table-bordered table-striped">
					<thead>
						<th>Firstname</th>
						<th>Lastname</th>
						<th>Address</th>
						<th>Action</th>
					</thead>
					<tbody>
						<tr ng-repeat="mem in member">
							<input type="hidden" value="{{mem.id}}">
							<td>{{mem.firstname}}</td>
							<td>{{mem.lastname}}</td>
							<td>{{mem.address}}</td>
							<td>
								<button class="btn btn-success" ng-click="update(mem.id, mem.firstname, mem.lastname, mem.address)"><i class="bi bi-pencil"></i> Edit</button> || 
								<button class="btn btn-danger" ng-click="delete(mem.id)"><i class="bi bi-trash"></i> Delete</button>
							</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
var app = angular.module("mem_app", []);
app.controller("controller", function($scope, $http) {
    $scope.btnName = "Save";
    $scope.icon = "bi bi-save";
    $scope.btnClass = "btn btn-primary";
    $scope.insert = function() {
        if ($scope.firstname == null) {
            alert("Please input Firstname");
        } 
        else if ($scope.lastname == null) {
            alert("Please input Lastname");
        }  
        else {
			$http({
				method: 'POST',
				url: 'action.php',
				data: { firstname: $scope.firstname, lastname: $scope.lastname, address: $scope.address, btnName: $scope.btnName, id: $scope.id }
			}).then(function (data){
				console.log(data)  
                alert(data.data);
                $scope.firstname = null;
                $scope.lastname = null;
                $scope.address = null;
                $scope.btnName = "Save";
                $scope.icon = "bi bi-save";
                $scope.btnClass = "btn btn-primary";
                $scope.showdata();
			},function (error){
				console.log(error, 'can not get data.');
			});
        }
    }
    $scope.showdata = function() {
		$http({
            method: 'GET',
            url: 'fetch.php'
        }).then(function (data){
            console.log(data)  
            $scope.member = data.data;  
        },function (error){
            console.log(error, 'can not get data.');
        });
    }
    $scope.update = function(id, firstname, lastname, address) {
        $scope.id = id;
        $scope.firstname = firstname;
        $scope.lastname = lastname;
        $scope.address = address;
        $scope.icon = "bi bi-send-check";
        $scope.btnClass = "btn btn-success";
        $scope.btnName = "Update";
    }
    $scope.delete= function(id) { 
        if (confirm("Are you sure you want to delete member?")) {
			$http({
				method: 'POST',
				url: 'delete.php',
				data:{'id':id}
			}).then(function (data){
				console.log(data)  
				alert(data.data);
				$scope.showdata();
			},function (error){
				console.log(error, 'can not get data.');
			});
        } else {
            return false;
        }
    }
    $scope.enter = function(keyEvent) {
        if (keyEvent.which === 13){
            insert();
        }
    }
});
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	$output = array();
	$query = $conn->query("select * from tblmembers"); 
	if ($query->num_rows > 0) {
	    while ($row = $query->fetch_array()) {
	        $output[] = $row;
	    }
	    echo json_encode($output);
	}
?>
action.php
//action.php
<?php
    include('conn.php');
    $info = json_decode(file_get_contents("php://input"));
    $firstname = mysqli_real_escape_string($conn, $info->firstname);
    $lastname = mysqli_real_escape_string($conn, $info->lastname);
    $address = mysqli_real_escape_string($conn, $info->address);
    $btn_name = $info->btnName;
	$output = array(); 
	
    if ($btn_name == "Save") {
        if ($conn->query("insert into tblmembers (firstname, lastname, address) values ('$firstname', '$lastname', '$address')")) {
			$output[] = "Member Added Successfully";
        } else {
			$output[] = "Failed";
        }
    }
    if ($btn_name == "Update") {
        $id  = $info->id;
        if ($conn->query("update tblmembers set firstname='$firstname', lastname='$lastname', address='$address' where id='$id'")) {
			$output[] = "Member Updated Successfully";
        } else {
		   $output[] = "Failed";
        }
    }
echo json_encode($output);
?>
delete.php
//delete.php
<?php
	include('conn.php');
	$data = json_decode(file_get_contents("php://input"));

	$id = $data->id;
	if ($conn->query("delete from tblmembers where id='$id'")) {
	    echo 'Member Deleted Successfully';
	} else {
	    echo 'Failed';
	}
?>

Wednesday, March 16, 2022

SwiftUI Sliding Tabs | SlidingTab Package

SwiftUI Sliding Tabs | SlidingTab Package

https://github.com/QuynhNguyen/SlidingTabView

SlidingTabView is a simple Android-Like tab view that is built using the latest and greatest SwiftUI. Almost everything is customizable!



ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
import SlidingTabView

struct ContentView: View {
    @State private var tabIndex = 0
    
    var body: some View {
        VStack {
            SlidingTabView(selection: $tabIndex, tabs: ["Home", "Friends", "Settings"], animation: .easeInOut)
            Spacer()
            
            if tabIndex == 0 {
                TabAView()
            } else if tabIndex == 1 {
                TabBView()
            } else if tabIndex == 2 {
                TabCView()
            }
            Spacer()
        }
    }
}

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

struct TabAView: View {
    var body: some View {
        VStack {
            Image("1")
                .resizable()
            Text("Tab Home")
                .font(.title)
        }
    }
}

struct TabBView: View {
    var body: some View {
        VStack {
            Image("2")
                .resizable()
            Text("Tab Friends")
                .font(.title)
        }
    }
}

struct TabCView: View {
    var body: some View {
        VStack {
            Image("3")
                .resizable()
            Text("Tab Setting")
                .font(.title)
        }
    }
}

SwiftUI Alert - SPAlert Package

SwiftUI Alert - SPAlert Package

SPAlert https://github.com/ivanvorobei/SPAlert

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
import SPAlert

struct ContentView: View {
    @State var showAlert = false
    @State var showAlert2 = false
    
    
    var body: some View {
        VStack(spacing: 20) {
            Button("Show Alert") {
                showAlert.toggle()
            }
            .SPAlert(
                isPresent: $showAlert,
                message: "SwiftUI Alert - SPAlert Package",
                duration: 1.0)
            
            Button("Show Alert 2") {
                showAlert2.toggle()
            }
            .SPAlert(
                isPresent: $showAlert2,
                title: "SPAlert Package",
                message: "This tutorial has been completed",
                duration: 2.0,
                dismissOnTap: false,
                preset: .done,
                //preset: .custom(UIImage(systemName: "checkmark.seal.fill")!),
                haptic: .success,
                layout: .init(),
                completion: {
                    print("This is a completion log.")
                    showAlert.toggle()
                })
            .tint(.orange)
        }
    }
}

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

Tuesday, March 15, 2022

SwiftUI HalfASheet package | half sheet

SwiftUI HalfASheet package | half sheet

Half Sheet Package : https://github.com/franklynw/HalfASheet

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI
import HalfASheet

struct ContentView: View {
    @State private var isShowing = false
    @State private var amount = 0.0
    
    var body: some View {
        ZStack {
            Button("Show sheet") {
                isShowing.toggle()
            }
            HalfASheet(isPresented: $isShowing, title: "Rotation") {
                VStack(spacing: 20) {
                    Image(systemName: "airplane")
                        .font(.system(size: 80))
                        .foregroundColor(.blue)
                        .rotationEffect(Angle(degrees: amount))
                    
                    Slider(value: $amount, in: 0...90)
                    
                    Text("Degrees: \(Int(amount))")
                        .italic()
                }
                .padding()
            }
            // Customise by editing these.
            .height(.proportional(0.40))
            .closeButtonColor(UIColor.white)
            .backgroundColor(.white)
            .contentInsets(EdgeInsets(top: 30, leading: 10, bottom: 30, trailing: 10))
        }
        .ignoresSafeArea()
    }
}

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

Friday, March 11, 2022

Vuejs Vue CLI File Upload with Axios and PHP

Vuejs Vue CLI File Upload with Axios and PHP

Install vue-axios
npm install --save axios vue-axios
https://www.npmjs.com/package/vue-axios

C:\vuejs\myapp>npm install --save axios vue-axios
C:\vuejs\myapp>npm run serve
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'

import axios from 'axios' // C:\vuejs\myapp>npm install --save axios vue-axios

import VueAxios from 'vue-axios'


createApp(App).use(VueAxios, axios).mount('#app')
src/components/fileUpload.vue
//src/components/fileUpload.vue
<template>
  <div class="container">
    <div class="row">
      <h1>Vuejs Vue CLI File Upload with Axios and PHP</h1>
      <label>File
        <input type="file" id="file" ref="file"/>
      </label>
        <button v-on:click="uploadFile()">Upload</button>
    </div>
  </div>
</template>

<script>

  export default  {   
      data () {
      return {          
          file:''
      }    
    },
    methods: {     

            uploadFile: function(){

                 this.file = this.$refs.file.files[0];                  
                 let formData = new FormData();
                 formData.append('file', this.file);
                 this.$refs.file.value = '';
                this.axios.post('http://localhost/devtest/upload.php', formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(function (response) {

                    if(!response.data){
                        alert('File not uploaded.');
                    }else{
                        alert('File uploaded successfully.');                        

                    }

                })
                .catch(function (error) {
                    console.log(error);
                 });

            }
    },
    
}
</script>
src/App.vue
//src/App.vue
<template>
  <div id="app">
      <FileUpload/>
  </div>
</template>
<script>
import FileUpload from './components/fileUpload.vue'
 
      export default {
                 name: 'app',
                       components: {
                             FileUpload
                }
       }
</script>
upload.php
//upload.php
<?php  
    header('Access-Control-Allow-Origin: *');  
     $filename = $_FILES['file']['name'];
     $allowed_extensions = array('jpg','jpeg','png','pdf');
      $extension = pathinfo($filename, PATHINFO_EXTENSION);
       if(in_array(strtolower($extension),$allowed_extensions) ) {     
          if(move_uploaded_file($_FILES['file']['tmp_name'], "upload/".$filename)){
                echo 1;
          }else{
              echo 0;
          }
    }else{
        echo 0;
    } 
?>

Related Post