article

Tuesday, August 10, 2021

SwiftUI Pie Chart

SwiftUI Pie Chart
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct PieChartCell: Shape {
    let startAngle: Angle
    let endAngle: Angle
   func path(in rect: CGRect) -> Path {
        let center = CGPoint.init(x: (rect.origin.x + rect.width)/2, y: (rect.origin.y + rect.height)/2)
    let radii = min(center.x, center.y)
        let path = Path { p in
            p.addArc(center: center,
                     radius: radii,
                     startAngle: startAngle,
                     endAngle: endAngle,
                     clockwise: true)
            p.addLine(to: center)
        }
        return path
   }
}

struct PieChart: View {
    @State private var selectedCell: UUID = UUID()
    
    let dataModel: ChartDataModel
    let onTap: (ChartCellModel?) -> ()
    var body: some View {
            ZStack {
                ForEach(dataModel.chartCellModel) { dataSet in
                    PieChartCell(startAngle: self.dataModel.angle(for: dataSet.value), endAngle: self.dataModel.startingAngle)
                        .foregroundColor(dataSet.color)
                       .onTapGesture {
                         withAnimation {
                            if self.selectedCell == dataSet.id {
                                self.onTap(nil)
                                self.selectedCell = UUID()
                            } else {
                                self.selectedCell = dataSet.id
                                self.onTap(dataSet)
                            }
                        }
                    }.scaleEffect((self.selectedCell == dataSet.id) ? 1.05 : 1.0)
                }
            }
    }
}


struct ContentView: View {
    @State var selectedPie: String = ""
    @State var selectedDonut: String = ""
    
    var body: some View {
            ScrollView {
                VStack {
                    HStack(spacing: 20) {
                        PieChart(dataModel: ChartDataModel.init(dataModel: sample), onTap: {
                            dataModel in
                            if let dataModel = dataModel {
                                self.selectedPie = "Programming Language: \(dataModel.name)\nPercent: \(dataModel.value)"
                            } else {
                                self.selectedPie = ""
                            }
                        })
                            .frame(width: 150, height: 150, alignment: .center)
                            .padding()
                        Text(selectedPie)
                        .font(.footnote)
                        .multilineTextAlignment(.leading)
                        Spacer()
                        
                    }
                    Spacer()
                    HStack {
                        ForEach(sample) { dataSet in
                            VStack {
                                Circle().foregroundColor(dataSet.color)
                                Text(dataSet.name).font(.footnote)
                            }
                        }
                    }
                }
            }
    }
}

struct ChartCellModel: Identifiable {
    let id = UUID()
    let color: Color
    let value: CGFloat
    let name: String
}

final class ChartDataModel: ObservableObject {
    var chartCellModel: [ChartCellModel]
    var startingAngle = Angle(degrees: 0)
    private var lastBarEndAngle = Angle(degrees: 0)
    
        
    init(dataModel: [ChartCellModel]) {
        chartCellModel = dataModel
    }
    
    var totalValue: CGFloat {
        chartCellModel.reduce(CGFloat(0)) { (result, data) -> CGFloat in
            result + data.value
        }
    }
    
    func angle(for value: CGFloat) -> Angle {
        if startingAngle != lastBarEndAngle {
            startingAngle = lastBarEndAngle
        }
        lastBarEndAngle += Angle(degrees: Double(value / totalValue) * 360 )
        print(lastBarEndAngle.degrees)
        return lastBarEndAngle
    }
}

let sample = [ ChartCellModel(color: Color.red, value: 11, name: "Javascript"),
               ChartCellModel(color: Color.yellow, value: 10, name: "Swift"),
               ChartCellModel(color: Color.gray, value: 24, name: "Python"),
               ChartCellModel(color: Color.blue, value: 31, name: "Java"),
               ChartCellModel(color: Color.green, value: 12, name: "PHP")]

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

Monday, August 9, 2021

SwiftUI Simple Progress View

SwiftUI Simple Progress View

A progress view is a view that shows the progress towards completion of a task.
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State private var progress = 0.0
    
    var body: some View {
        
        VStack(spacing: 30) {
            HStack {
                VStack {
                    ProgressView("Progress", value: progress, total: 100)
                        .accentColor(Color.green)
                        .padding([.leading, .trailing], 10)
                        .scaleEffect(x: 1, y: 4, anchor: .center)
                    
                    Button("Increment Progress") {
                        if progress < 100 {
                            progress += 10
                        }
                    }
                    .padding(.top)
                    .padding()

                    Text("Current Progress: \(Int(progress))%")
                        .padding()
                    
                }
            }
            
            HStack {
                VStack {
                    ProgressView()
                        .scaleEffect(1.5, anchor: .center)
                        .progressViewStyle(CircularProgressViewStyle(tint: .blue))
                    
                }
            }
        }
        .padding(.all, 10)
        
    }
}

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

SwiftUI Simple Custom View Modifier

SwiftUI Simple Custom View Modifier
SwiftUI Views can be changed by using modifiers. To apply the same style to a particular view a custom view modifier can be used.
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        NavigationView {
             VStack {
                HStack {
                    Button("One") {
                        
                    }
                    .modifier(CustomButton())
                    
                    Button("Two") {

                    }
                    .modifier(CustomButton(buttonForegroundColor: Color.red))
                    
                    Button("Three") {
                        
                    }
                    .modifier(CustomButton(buttonForegroundColor: Color.yellow))
                    
                }
                Spacer()
            }
            .navigationTitle("Custom View Modifiers")
        }
    }
}

struct CustomButton: ViewModifier {
    var buttonForegroundColor = Color.blue
    
    func body(content: Content) -> some View {
        return content
            .font(.largeTitle)
            .background(Color.black)
            .foregroundColor(buttonForegroundColor)
            .cornerRadius(8.0)
            .padding(.top, 50.0)
    }
}

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

Sunday, August 8, 2021

SwiftUI MapKit Example

SwiftUI MapKit Example
SwiftUI a Map view can be displayed showing a map inside the main view.
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI
import MapKit

struct ContentView: View {
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 14.836620, longitude: 120.294113) , span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    
    var body: some View {
        Map(coordinateRegion: $region)
            .edgesIgnoringSafeArea(.all)
    }
}

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

Saturday, August 7, 2021

SwiftUI GroupBox Example

SwiftUI GroupBox Example

SwiftUI Group Boxes can be used to combine related views.
ContentView.swift
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var name = ""
    
    var body: some View {
        VStack {

            GroupBox(label: Label("Heart rate", systemImage: "heart.fill").font(.largeTitle).foregroundColor(.red)) {
                Text("69 BPM").font(.title)
            }

            GroupBox {
                Text("Enter your name").font(.title)
                TextField("name", text: $name)
            }
            Spacer()
        }.padding(.horizontal)
    }
}

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

Friday, August 6, 2021

SwiftUI Color Picker Example

SwiftUI Color Picker Example

Color Picker shows the currently selected color and allow users to select a new color. In this example a Rectangle is filled with the chosen color.
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var selectedColor = Color.red
    
    var body: some View {
        
        NavigationView {
            VStack(spacing: 20) {

                Rectangle()
                    .fill(selectedColor)
                    .frame(width: 100, height: 100)

                ColorPicker("Set the rectangle color", selection: $selectedColor)
                    .padding()
                
                Spacer()
            
            }.navigationTitle("Color picker")
        }
    }
}

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

Dynamically Add & Remove Items From List Using JavaScript

Dynamically Add & Remove Items From List Using JavaScript
index.html
//index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css">
  <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
  <title></title>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-12">
        <h1>Dynamically Add & Remove Items From List Using JavaScript</h1>
        <hr>
        <div class="input-group">
          <input type="text" class="form-control" id="candidate" required>
          <div class="input-group-append">
            <button onclick="addItem()" class="btn btn-add" type="button">Add Item</button>
            <button onclick="removeItem()" class="btn btn-remove" type="button">Remove Item</button>
          </div>
        </div>
        <ul id="dynamic-list">
        </ul>
      </div>
    </div>
  </div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script>
function addItem() {
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("candidate");
    var li = document.createElement("li");
    li.setAttribute('id', candidate.value);
    li.appendChild(document.createTextNode(candidate.value));
    ul.appendChild(li);
}
function removeItem() {
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("candidate");
    var item = document.getElementById(candidate.value);
    ul.removeChild(item);
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<style>
body {
    font-family: 'Poppins', sans-serif;
    
    background: rgb(107,186,222);
    background: -moz-linear-gradient(90deg, rgba(107,186,222,1) 0%, rgba(232,156,205,1) 100%);
    background: -webkit-linear-gradient(90deg, rgba(107,186,222,1) 0%, rgba(232,156,205,1) 100%);
    background: linear-gradient(90deg, rgba(107,186,222,1) 0%, rgba(232,156,205,1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#d9d900",endColorstr="#73ff96",GradientType=1); 
}
h1{
    color: rgb(49, 49, 49);
    margin-top: 40px;
    text-align: center;
    font-size: 32px;
}
.input-group{
    
    margin: 50px 0px;
}
.input-group input{
    height: 45px;
    
}
.btn-add{

    background-color: rgb(12, 187, 50);
    color: white;
    padding: 0px 63px;
}
.btn-remove{

    background-color: rgb(187, 12, 12);
    color: white;
    padding: 0px 50px;
}
ul{
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    padding-left: 0;
    margin-bottom: 0;
}
li{
    position: relative;
    display: block;
    padding: 10px 20px;
    margin-bottom: 10px;
    background-color:
    #fff;
    border: 1px solid
    rgba(0,0,0,.125);
    border-top-left-radius: .25rem;
    border-top-right-radius: .25rem;
    border-bottom-left-radius: .25rem;
    border-bottom-right-radius: .25rem;
    
}
</style>
</body>
</html>

SwiftUI 3D Rotation - rotation3DEffect

SwiftUI 3D Rotation - rotation3DEffect


The rotation3DEffect modifier rotates a view in 3D. The angle of the rotation can be set by the degrees parameter.

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var degrees = 0.0
    @State private var rotateX = true
    @State private var rotateY = true
    @State private var rotateZ = true
    
    var body: some View {
        
        VStack(spacing: 30) {
            Toggle("Rotate X-axis", isOn: $rotateX)
            Toggle("Rotate Y-axis", isOn: $rotateY)
            Toggle("Rotate Z-axis", isOn: $rotateZ)

            Button("3D Rotation - rotation3DEffect") {
                withAnimation(.easeIn(duration: 1)) {
                    self.degrees += 360
                }
            }
            .padding(20)
            .background(Color.green)
            .foregroundColor(Color.white)

            .rotation3DEffect(.degrees(degrees), axis: (x: rotateX ? 1 : 0, y: rotateY ? 1 : 0, z: rotateZ ? 1 : 0))
            
            Spacer()
        }
        .padding()
    }
}

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

Sunday, August 1, 2021

SwiftUI - Slider Example

SwiftUI - Slider Example

ContentView.swift
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State var scale: CGFloat = 1.0
    @State private var celsius: Double = 0
    @State var sliderValue: Double = 0
    @State private var value: Float = 0.0
    @State var progress: Float = 0.5
    
    var body: some View {
        VStack {
            HStack {
                VStack {
                    Slider(value: $scale, in: 1.0...10.0, step: 0.1)
                        .padding(.bottom, 100)
                        .frame(width: 200, height: 10, alignment: Alignment.center)

                    Text("Slider Value: \(scale)")
                        .font(.headline)
                        .foregroundColor(Color.red)
                        .multilineTextAlignment(TextAlignment.center)
                        .background(Color.yellow)
                }
            }
            .padding([.leading, .bottom])
            
            //Slide read values from it
            HStack {
                VStack {
                    Slider(value: $celsius, in: -100...100)
                    Text("\(celsius, specifier: "%.1f") Celsius is \(celsius * 9 / 5 + 32, specifier: "%.1f") Fahrenheit")
                }
            }
            .padding([.leading, .bottom])
            
            HStack {
                VStack {
                    HStack {
                        Image(systemName: "minus")
                        //Slider(value: $sliderValue, in: 0...20)
                        Slider(value: $sliderValue, in: 0...20, step: 1) //slider’s step (increment) value
                            .padding()
                            .accentColor(Color.green) //Change color of the slider
                            //.border(Color.green, width: 2) //border around the slider
                            //.overlay(
                            //    RoundedRectangle(cornerRadius: 15.0)
                            //        .stroke(lineWidth: 2.0)
                            //        .foregroundColor(Color.green)
                            //)
                        Image(systemName: "plus")
                    }
                    .foregroundColor(Color.green)
                    Text("Current slider value: \(sliderValue, specifier: "%.2f")")
                }
            }.padding()
            
            //call a function when a slider changes
            HStack {
                VStack {
                    Slider(value: Binding(
                        get: {
                            self.value
                        },
                        set: {(newValue) in
                              self.value = newValue
                              self.doSomething()
                        }
                    ))
                    
                    Slider(value: Binding(get: {
                        self.progress
                    }, set: { (newVal) in
                        self.progress = newVal
                        self.sliderChanged()
                    }))
                    .padding(.all)
                    Text(String(progress))
                }
            }
        }
    }
    
    func doSomething(){
        print("\(value)")
    }
    func sliderChanged() {
        print("Slider value changed to \(progress)")
    }
}

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

Thursday, July 29, 2021

SwiftUI Alerts, Action Sheets, Modals and Popovers

SwiftUI Alerts, Action Sheets, Modals and Popovers 

Alerts and Action Sheets
Both Alerts and Action Sheets use the similar two ways of presenting it to the user.

Modals
To present modals, SwiftUI provides the special view modifier called sheet.

Popovers
Using Popovers in SwiftUI is very similar to Alers and Action Sheets.

ContentView.swift
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI
import Combine

struct ContentView: View {
     
    @State private var showActionSheet = false
    @State private var isActionSheet = false
    @State private var message: Message? = nil
    @State private var showModal = false
    @State private var showPopover: Bool = false
    
    var body: some View {
        
        VStack {
            //Action Sheets
            HStack {
                Button("Show action sheet") {
                    self.showActionSheet = true
                }
            }
            .padding(.bottom)
            .actionSheet(isPresented: $showActionSheet) {
                ActionSheet(
                    title: Text("Actions"),
                    message: Text("Available actions"),
                    buttons: [
                        .cancel { print(self.showActionSheet) },
                        .default(Text("Action")),
                        .destructive(Text("Delete"))
                    ]
                )
            }
            //Action Sheets Example 2
            HStack {
                Button(action: {
                    self.isActionSheet = true
                }) {
                    Text("ActionSheet")
                    .foregroundColor(Color.white)
                }
                .padding()
                .background(Color.blue)
                .actionSheet(isPresented: $isActionSheet, content: {
                    ActionSheet(title: Text("iOSDevCairocoders"), message: Text("SubTitle"), buttons: [
                        .default(Text("Save"), action: {
                            print("Save")
                        }),
                        .default(Text("Delete"), action: {
                            print("Delete")
                        }),
                        .destructive(Text("Cancel"))
                        ])
                })
            }
            .padding(.bottom)
            
            //Alerts
            HStack {
                Button("Show alert") {
                    self.message = Message(text: "Hi!")
                }
            }
            .padding(.bottom)
            .alert(item: $message) { message in
                Alert(
                    title: Text(message.text),
                    dismissButton: .cancel()
                )
            }
            //Modals
            HStack {
                Button("Show modal") {
                    self.showModal = true
                }
            }
            .padding(.bottom)
            .sheet(isPresented: $showModal, onDismiss: {
                print(self.showModal)
            }) {
                ModalView(message: "This is Modal view")
            }
            
            //Popovers
            HStack {
                Button("Show popover") {
                    self.showPopover = true
                }.popover(
                    isPresented: self.$showPopover,
                    arrowEdge: .bottom
                ) { Text("Popover") }
            }
        }
    }
}

struct Message: Identifiable {
    let id = UUID()
    let text: String
}

struct ModalView: View {
    @Environment(\.presentationMode) var presentation
    let message: String

    var body: some View {
        VStack {
            Text(message)
            Button("Dismiss") {
                self.presentation.wrappedValue.dismiss()
            }
        }
    }
}

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

Wednesday, July 28, 2021

SwiftUI Simple Quiz

SwiftUI Simple Quiz

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    //var for the score
    @State var score = 0
    
    var body: some View {
        NavigationView{
            VStack(spacing: 20){
                
                Text("Welcome to the quiz game")
                
                //button to start the quiz
                NavigationLink(destination: Quiz1()) {
                    Text("START QUIZ")
                }
                HStack{
                    //display your score
                    Text("last score : \(self.score) / \(myQuiz1.count)")
                        .onAppear(){ //refresh score
                            self.score = LoadScore(quiz: "myQuiz1")
                    }
                }
            }
            .navigationBarTitle("Quiz example",displayMode: .inline)
        }
    }
}

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

import Foundation

struct QuizModel  {
    var img : String?
    var text : String?
    var answer : [String]
    //specify what is the correct answer
    var correct : Int?
}

//final quiz is an array of quizmodel
var myQuiz1 : [QuizModel] = [

    QuizModel(img: "flag1",
    text: "Celebrities like Beyoncé Knowles and her sister Solange have been seen wearing the colourful and highly fashionable material called Kente cloth made in this West African country. The colours are very symbolic: the red represents the country's struggle for freedom, the yellow is for the country's wealth in minerals like gold and the green shows its lush forestry.",
    answer: ["South Africa","Madagascar","Georgia","Ghana"],
    correct: 3),
    
    QuizModel(img: "flag2",
    text: "Located in the centre of the continent of Europe, this country is surrounded by Austria, Slovakia and Romania. It is known for being the birthplace of many world famous pianists, orchestra conductors and opera singers. The red in this country's flag symbolizes strength, the green represents hope and the white is for faithfulness.",
    answer: ["Italy","Hungary","Mexico","Libya"],
    correct: 1),
    
    QuizModel(img: "flag3",
    text: "On this flag, the green is for the beautiful fields and forests and the yellow is for the gold that can be found in this soccer crazy South American country! Also known for its samba music and world famous carnival, the country is divided into 27 districts and they are represented by the same number of stars on the flag.",
    answer: ["Mexico","Cuba","Ecuador","Brazil"],
    correct: 3),
    
    QuizModel(img: "flag4",
    text: "The people in this country, located between Afghanistan and India, might greet you by saying either Salam (hi!) or Khush Aamdeed (Welcome!). The colours green and white together mean peace and success. The crescent moon is for progress and the star represents knowledge.",
    answer: ["Iraq","Turkey","Pakistan","Nepal"],
    correct: 2),
    
    QuizModel(img: "flag5",
    text: "This island country located in Southeast Asia is a neighbour to Taiwan, Vietnam and Indonesia. If you are there, expect to be treated to music played on the mandolin, guitar, ukulele and other stringed instruments in a band known as a rondalla. The white triangle on the flag represents peace, the red is for bravery and the blue is for patriotism (loyalty and love for your country). The three gold stars and the sun are symbols of the three main areas that the country is divided into.",
    answer: ["Australia","The Philippines","Malaysia","South Korea"],
    correct: 1),

]

func SaveScore(quiz : String , score : Int){
    UserDefaults.standard.set(score, forKey: quiz)
}

func LoadScore (quiz : String) -> Int{
    return UserDefaults.standard.integer(forKey: quiz)
}
QuizView.swift
 
//
//  QuizView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

//view for the quiz game
struct Quiz1 : View {
    
    //number of question
    @State var i : Int = 0
    
    //var for the score
    @State var score = 0
    @State private var showActionSheet = false
    
    var body: some View {
        VStack(alignment: .leading,spacing: 15){
            
            //if i < of questions --> play question
            if(self.i < myQuiz1.count){
                
                
                //image of the question
                Image(myQuiz1[self.i].img!)
                    .resizable()
                    .scaledToFit()
                    .padding(.horizontal)
                
                //text of the question
                Text(myQuiz1[self.i].text!)
                
                
                //answer 0
                Button(action:{
                    self.showActionSheet = true
                    self.buttonAction(n: 0)
                },label: {
                    Text(myQuiz1[self.i].answer[0])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }
                
                //answer 1
                Button(action:{
                    self.buttonAction(n: 1)
                    self.showActionSheet = true
                },label: {
                    Text(myQuiz1[self.i].answer[1])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }
                
                //answer 2
                Button(action:{
                    self.buttonAction(n: 2)
                    self.showActionSheet = true
                },label: {
                    Text(myQuiz1[self.i].answer[2])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }
                
                //answer 3
                Button(action:{
                    self.buttonAction(n: 3)
                    self.showActionSheet = true
                },label: {
                    Text(myQuiz1[self.i].answer[3])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }

            }
                
            //after last question --> show final view with score
            else{
                FinalView(score : self.score)
            }
            
            
        }
        .padding(.horizontal)
    }
    
    
    //action of the buttons
    //n = answer [0,1,2,3]
    func buttonAction( n : Int){
        //if answer is correct increment score
        if(myQuiz1[self.i].correct == n){
            self.score = self.score + 1
        }
        //GO TO NEXT QUESTION
        self.i = self.i + 1
        
    }
    
    
}

struct Quiz1_reviews: PreviewProvider {
    static var previews: some View {
        Quiz1()
    }
}
FinalView.swift
//
//  FinalView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct FinalView : View {
    var score : Int
    var body: some View {
        VStack{
            Text("Final Score : \(score)")
            .onAppear(){
                SaveScore(quiz: "myQuiz1", score: self.score)
            }
        }
    }
}
struct FinalView_Previews: PreviewProvider {
    static var previews: some View {
        FinalView(score: 1)
    }
}

Sunday, July 25, 2021

Dynamic Select Box and Sign Up using Python Flask PostgreSQL jsonify and javascript

Dynamic Select Box and Sign Up using Python Flask PostgreSQL jsonify and javascript

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(171, 'Philippines'),
(227, 'United States of America');

CREATE TABLE state (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL,
country_id INT NOT NULL
);

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

CREATE TABLE city (
id serial PRIMARY KEY,
state VARCHAR ( 60 ) NOT NULL,
name VARCHAR ( 60 ) NOT NULL,
stateid INT NOT NULL
);

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

CREATE TABLE userflask (
id serial PRIMARY KEY,
fullname VARCHAR ( 150 ) NOT NULL,
email VARCHAR ( 150 ) NOT NULL,
countryid INT NOT NULL,
stateid INT NOT NULL,
cityid INT NOT NULL
);
app.py
#app.py
from flask import Flask, render_template, redirect, request, json, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
      
app = Flask(__name__)
      
app.secret_key = "caircocoders-ednalan"
      
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
          
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/', methods=['GET', 'POST'])
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    query = "select * from countries"
    cur.execute(query)
    country = cur.fetchall()
    message = ''    
    if request.method == 'POST':
        fullname = request.form['fullname']
        email = request.form['email']
        country = request.form['country']
        state = request.form['state']
        city = request.form['city']
        cur.execute("INSERT INTO userflask (fullname, email, countryid, stateid, cityid) VALUES (%s,%s,%s,%s,%s)",(fullname,email,country,state,city))
        conn.commit()
        cur.close()
        message = "Succesfully Register"
    return render_template('index.html', country=country, message=message)
  
@app.route('/state/<get_state>')
def statebycountry(get_state):
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM state WHERE country_id = %s", [get_state])
    state = cur.fetchall()  
    stateArray = []
    for row in state:
        stateObj = {
                'id': row['id'],
                'name': row['name']}
        stateArray.append(stateObj)
    return jsonify({'statecountry' : stateArray})
   
@app.route('/city/<get_city>')
def city(get_city):
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM city WHERE stateid = %s", [get_city])
    state = cur.fetchall()  
    cityArray = []
    for row in state:
        cityObj = {
                'id': row['id'],
                'name': row['name']}
        cityArray.append(cityObj)
    return jsonify({'citylist' : cityArray})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dynamic Select Box and Sign Up using Python Flask PostgreSQL jsonify and javascript</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
    <div class="col-md-12">
    <p><h2>Dynamic Select Box and Sign Up using Python Flask PostgreSQL jsonify and javascript</h2></p>
    {% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
    <form method="POST">
    <div class="form-group">
        <label for="email">Name:</label>
        <input type="text" class="form-control" name="fullname" id="fullname" placeholder="Your Name">
    </div> 
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" name="email" id="email" placeholder="Your Email">
    </div>    
    <div class="form-group">
        <label for="email">Country:</label>
        <select class="form-control" id="country" name="country">
            {% for row in country %}
            <option value="{{row.id}}">{{row.name}}</option>
            {% endfor %}
        </select>
    </div>
    <div class="form-group">
        <label for="email">State:</label>
        <select class="form-control" id="state" name="state"></select>
    </div>
    <div class="form-group">
        <label for="email">City:</label>
        <select class="form-control" id="city" name="city"></select>
    </div>
    <input type="submit" class="btn btn-success btn-lg">
  </form> 
   </div>
 </div>
</div> 
<script>
country_select = document.getElementById('country');
state_select = document.getElementById('state');
city_select = document.getElementById('city');
  
country_select.onchange = function(){
 country = country_select.value;
 alert(country);
 fetch('state/' + country).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (state of data.statecountry) {
    optionHTML += '<option value="' + state.id +'">' + state.name + '</option>'
   }
   state_select.innerHTML = optionHTML;
  });
 });
}
state_select.onchange = function(){
 city = state_select.value; 
 fetch('city/' + city).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (city_rs of data.citylist) {
    optionHTML += '<option value="' + city_rs.id +'">' + city_rs.name + '</option>'
   }
   city_select.innerHTML = optionHTML;
  });
 });
}
</script>
</body>
</html>

Saturday, July 24, 2021

Add Remove Input Fields Dynamically with Python Flask jQuery and PostgreSQL Database

Add Remove Input Fields Dynamically with Python Flask jQuery and PostgreSQL Database 

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE skills (
id serial PRIMARY KEY,
skillname VARCHAR ( 150 ) NOT NULL
);
app.py
#app.py
from flask import Flask, render_template, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
      
app = Flask(__name__)
      
app.secret_key = "caircocoders-ednalan"
      
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
          
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/', methods=['GET', 'POST'])
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    message = ''    
    if request.method == 'POST':
        skills = request.form.getlist('field[]')
        for value in skills:  
            cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[value])
            conn.commit()       
        cur.close()
        message = "Succesfully Register"
    return render_template('index.html', message=message)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
<head>  
<title>Add Remove Input Fields Dynamically with Python Flask jQuery and PostgreSQL Database</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
.input-wrapper div {
    margin-bottom: 10px;
}
.remove-input {
    margin-top: 10px;
    margin-left: 15px;
    vertical-align: text-bottom;
}
.add-input {
    margin-top: 10px;
    margin-left: 10px;
    vertical-align: text-bottom;
}
</style>
</head>  
<body>  
<div style="width:85%;padding:50px;">  
    <h2>Add Remove Input Fields Dynamically with Python Flask jQuery and PostgreSQL Database</h2>  
    {% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
    <form method="POST">
        <div class="input-wrapper">
            <div>Programming Language : <br/>
            <input type="text" name="field[]" value=""/>
            <a href="javascript:void(0);" class="add-input" title="Add input"><img src="/static/img/add.png"/></a>
            </div>
        </div>
        <input type="submit" name="cmdsubmit">
    </form>
</div>  
<script>
$(document).ready(function(){
    var max_input_fields = 10;
    var add_input = $('.add-input');
    var input_wrapper = $('.input-wrapper');
    var new_input = '<div><input type="text" name="field[]" value=""/><a href="javascript:void(0);" class="remove-input" title="Remove input"><img src="/static/img/remove.png"/></a></div>';
    var add_input_count = 1; 
    $(add_input).click(function(){
        if(add_input_count < max_input_fields){
            add_input_count++; 
            $(input_wrapper).append(new_input); 
        }
    });
    $(input_wrapper).on('click', '.remove-input', function(e){
        e.preventDefault();
        $(this).parent('div').remove();
        add_input_count--;
    });
});
</script>
</body>  
</html>  

Drag and Drop Reorder with Jquery Ajax Jquery-UI Python Flask and PostgreSQL Database

Drag and Drop Reorder with Jquery Ajax Jquery-UI Python Flask and PostgreSQL Database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE gallery (
id serial PRIMARY KEY,
photoname VARCHAR ( 150 ) NOT NULL,
display_order INT NOT NULL,
created TIMESTAMP,
modified TIMESTAMP
);


INSERT INTO
    gallery(photoname, display_order, created, modified)
VALUES
('01.jpg', '1', '2021-06-29', '2021-06-29'),
('02.jpg', '2', '2021-06-29', '2021-06-29'),
('03.jpg', '3', '2021-06-29', '2021-06-29'),
('04.jpg', '4', '2021-06-29', '2021-06-29');

https://jqueryui.com/
Sortable  https://jqueryui.com/sortable/
app.py
#app.py
from flask import Flask, render_template, jsonify, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
      
app = Flask(__name__)
      
app.secret_key = "caircocoders-ednalan"
      
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
          
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def main():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 
    cur.execute("SELECT * FROM gallery ORDER BY display_order")
    gallery = cur.fetchall()
    return render_template('index.html', gallery=gallery)
      
@app.route("/orderupdate",methods=["POST","GET"])
def orderupdate():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)    
    if request.method == 'POST':
        cur.execute("SELECT * FROM gallery")    
        number_of_rows = cur.rowcount   
        print(number_of_rows)    
        getorder = request.form['order']    
        order = getorder.split(",", number_of_rows)
        count=0    
        for value in order:
            count +=1
            #print(count)                       
            cur.execute("UPDATE gallery SET display_order = %s WHERE id = %s ", [count, value])
            conn.commit()       
        cur.close()
    return jsonify(order)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
<head>  
<title>Drag and Drop Reorder with Jquery Ajax Jquery-UI Python Flask and PostgreSQL Database</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
.gallery{ width:100%; float:left;}
.gallery ul{ margin:0; padding:0; list-style-type:none;}
.gallery ul li{ padding:7px; border:2px solid #ccc; float:left; margin:10px 7px; background:none; width:auto; height:auto;}
.gallery img{ width:250px;}
</style>
</head>  
<body> 
<div class="container">
    <h2>Drag and Drop Reorder with Jquery Ajax Jquery-UI Python Flask and PostgreSQL Database</h2>
    <div>     
        <div class="gallery">
            <ul class="reorder-gallery">
            {% for row in gallery %}
                <li id="{{row.id}}" class="ui-sortable-handle"><a href="javascript:void(0);"><img src="/static/images/{{row.photoname}}" alt=""></a></li>
            {% endfor %}
            </ul>
        </div>
    </div><div id="test"></div>
</div>
<script>
$(document).ready(function(){   
    $("ul.reorder-gallery").sortable({      
        update: function( event, ui ) {
            updateOrder();
        }
    });  
});
function updateOrder() {    
    var item_order = new Array();
    $('ul.reorder-gallery li').each(function() {
        item_order.push($(this).attr("id"));
    }); 
    var order_string = 'order='+item_order;
    $.ajax({
        method: "POST",
        url: "/orderupdate",
        data: order_string,
        cache: false,
        success: function(data){    
            $("#test").html(data);
        }
    });
}
</script> 
</body>  
</html> 

Friday, July 23, 2021

Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL

Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE uploads (
id serial PRIMARY KEY,
file_name VARCHAR ( 150 ) NOT NULL,
upload_time TIMESTAMP NOT NULL
);

DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews.

https://www.dropzonejs.com/
app.py
#app.py
from flask import Flask, render_template, jsonify, request
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
from datetime import datetime

import psycopg2 #pip install psycopg2 
import psycopg2.extras
      
app = Flask(__name__)
      
app.secret_key = "caircocoders-ednalan"
      
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
          
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
  
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def main():
    return render_template('index.html')
      
@app.route("/upload",methods=["POST","GET"])
def upload():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)   
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        now = datetime.now()
         
        if file and allowed_file(file.filename):
           file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
 
           cur.execute("INSERT INTO uploads (file_name, upload_time) VALUES (%s, %s)",[file.filename, now])
           conn.commit()
           cur.close()
           print('File successfully uploaded ' + file.filename + ' to the database!')
        else:
           print('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
        msg = 'Success Uplaod'     
    return jsonify(msg)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
 <head>  
  <title>Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/dropzone/dropzone.css" />
<script type="text/javascript" src="/static/dropzone/dropzone.js"></script>
 </head>  
 <body> 
<div class="container"> 
    <h2>Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL</h2>
    <div class="dropzone">
        <div class="dz-message needsclick">
            <h1>Drop files here or click to upload.</h1>
        </div>
    </div>
</div>
<script>
$(document).ready(function(){
    $(".dropzone").dropzone({
      url: '/upload',
      width: 300,
      height: 300, 
      progressBarWidth: '100%',
      maxFileSize: '5MB'
    })
});
</script> 
 </body>  
</html> 

Thursday, July 22, 2021

Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database

Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE checkbox (
id serial PRIMARY KEY,
name VARCHAR ( 150 ) NOT NULL
);
app.py
#app.py
from flask import Flask, render_template, jsonify, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
      
app = Flask(__name__)
      
app.secret_key = "caircocoders-ednalan"
      
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
          
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def main():
    return render_template('index.html')
 
@app.route("/insert",methods=["POST","GET"])
def insert():  
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        insert = request.form['checkboxvalue'] 
        cur.execute("INSERT INTO checkbox (name) VALUES (%s)",[insert])
        conn.commit()
        cur.close() 
        msg = 'Data Inserted Successfully!'
    else:
        msg = 'Invalid'
    return jsonify(msg)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Insert Checkbox values using Python Flask Jquery Ajax and PostgreSQL Database</h3>
    <label><input type="checkbox" class="get_value" value="Python"> Python</label>
    <br/>
    <label> <input type="checkbox" class="get_value" value="JavaScript"> JavaScript</label>
    <br/>
    <label><input type="checkbox" class="get_value" value="Java"> Java</label>
    <br/>
    <label><input type="checkbox" class="get_value" value="PHP"> PHP</label>
    <br/>
    <label><input type="checkbox" class="get_value" value="Swift"> Swift</label>
    <br/>
    <br/>
    <button type="button" name="submit" id="submit">Save</button>
    <br/>
    <h4 id="result"></h4>
    <script>
        $(document).ready(function() {
            $('#submit').click(function() {
                var insert = [];
                $('.get_value').each(function() {
                    if ($(this).is(":checked")) {
                        insert.push($(this).val());
                    }
                });
                insert = insert.toString();         
                var insert_string = 'checkboxvalue='+insert;            
                $.ajax({
                    method: "POST",
                    url: "/insert",
                    data: insert_string,
                    cache: false,
                    success: function(data){    
                        $("#result").html(data);
                    }
                });
            });
        });
    </script>
</body>
</html>

Dependent Dropdown with Search Box using Python Flask jQuery Ajax and PostgreSQL Database

Dependent Dropdown with Search Box using Python Flask jQuery Ajax and PostgreSQL Database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE carbrands (
brand_id serial PRIMARY KEY,
brand_name VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    carbrands(brand_name)
VALUES
('Toyota'),
('Honda'),
('Suzuki'),
('Mitsubishi'),
('Hyundai');

CREATE TABLE carmodels (
model_id serial PRIMARY KEY,
brand_id INT NOT NULL,
car_models VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    carmodels(brand_id,car_models)
VALUES
(1, 'Toyota Corolla'),
(2, 'Toyota Camry'),
(1, 'Toyota Yaris'),
(1, 'Toyota Sienna'),
(1, 'Toyota RAV4'),
(1, 'Toyota Highlander'),
(2, 'Honda HR-V'),
(2, 'Honda Odyssey'),
(3, 'Swift'),
(3, 'Celerio'),
(3, 'Ertiga'),
(3, 'Vitara'),
(4, 'Mirage'),
(4, 'Mirage G4'),
(4, 'Xpander Cross'),
(4, 'Montero Sport'),
(4, 'Strada Athlete'),
(5, 'Reina '),
(5, 'Accent'),
(5, 'Elantra'),
(5, 'Tucson');

bootstrap-select plugin https://developer.snapappointments.com/bootstrap-select/
app.py
#app.py
from flask import Flask, render_template, jsonify, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
     
app = Flask(__name__)
     
app.secret_key = "caircocoders-ednalan"
     
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
         
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def main():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM carbrands ORDER BY brand_id")
    carbrands = cur.fetchall()
    return render_template('index.html', carbrands=carbrands)
 
@app.route("/carbrand",methods=["POST","GET"])
def carbrand():  
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        category_id = request.form['category_id'] 
        print(category_id)  
        cur.execute("SELECT * FROM carmodels WHERE brand_id = %s ORDER BY car_models ASC", [category_id] )
        carmodel = cur.fetchall()  
        OutputArray = []
        for row in carmodel:
            outputObj = {
                'id': row['brand_id'],
                'name': row['car_models']}
            OutputArray.append(outputObj)
    return jsonify(OutputArray)

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Dependent Dropdown with Search Box using Python Flask jQuery Ajax and PostgreSQL Database</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" />
    </head>
    <body>
        <div class="container">
            <h1 align="center">Dependent Dropdown with Search Box using Python Flask jQuery Ajax and PostgreSQL Database</h1>       
            <div class="row">
                <div class="col-md-6">
                    <label>Select Car</label>
                    <select name="car_brand" data-live-search="true" id="car_brand" class="form-control" title="Select Car Brand"> 
                    {% for row in carbrands %}
                    <option value="{{row.brand_id}}">{{row.brand_name}}</option>
                    {% endfor %}
                    </select>
                </div>
                <div class="col-md-6">
                    <label>Select Brand</label>
                    <select name="car_models" data-live-search="true" id="car_models" class="form-control" title="Select Car Model"> </select>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#car_brand").selectpicker();
   
                $("#car_models").selectpicker();
   
                function load_data(type, category_id) {
                    $.ajax({
                        url: "/carbrand",
                        method: "POST",
                        data: { type: type, category_id: category_id },
                        dataType: "json",
                        success: function (data) { //alert(category_id)
                            var html = "";
                            for (var count = 0; count < data.length; count++) {
                                html += '<option value="' + data[count].id + '">' + data[count].name + "</option>";
                            }
                            if (type == "carData") {
                                $("#car_brand").html(html);
                                $("#car_brand").selectpicker("refresh");
                            } else {
                                $("#car_models").html(html);
                                $("#car_models").selectpicker("refresh");
                            }
                        },
                    });
                }
   
                $(document).on("change", "#car_brand", function () {
                    var category_id = $("#car_brand").val();
                    load_data("carModeldata", category_id);
                });
            });
        </script>
    </body>
</html>

Tuesday, July 13, 2021

Delete multiple records by selecting checkboxes using Python Flask with PostgreSQL

Delete multiple records by selecting checkboxes using Python Flask with PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE contacts (
id serial PRIMARY KEY,
fullname VARCHAR ( 150 ) NOT NULL,
position VARCHAR ( 150 ) NOT NULL,
office VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    contacts(fullname, position, office)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco'),
('cylde Ednalan', 'Software Engineer', 'Olongapo'),
('Rhona Davidson', 'Software Engineer', 'San Francisco'),
('Quinn Flynn', 'Integration Specialist', 'New York'),
('Tiger Nixon', 'Software Engineer', 'London'),
('Airi Satou', 'Pre-Sales Support', 'New York'),
('Angelica Ramos', 'Sales Assistant', 'New York'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo'),
('Bradley Greer', 'Regional Director', 'San Francisco'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo'),
('Bruno Nash', 'Customer Support', 'New York'),
('cairocoders', 'Sales Assistant', 'Sydney'),
('Zorita Serrano', 'Support Engineer', 'San Francisco'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo'),
('Serge Baldwin', 'Data Coordinator', 'Singapore'),
('Shad Decker', 'Regional Director', 'Tokyo');
app.py
 
#app.py
from flask import Flask, render_template, request, redirect, flash
import psycopg2 #pip install psycopg2 
import psycopg2.extras
    
app = Flask(__name__)
    
app.secret_key = "caircocoders-ednalan"
    
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
        
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
 
@app.route('/')
def main(): 
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    result = cur.execute("SELECT * FROM contacts ORDER BY id")
    contacts = cur.fetchall()   
    return render_template('index.html', contacts=contacts)
     
@app.route('/delete', methods=['GET', 'POST'])
def delete():   
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST': 
        for getid in request.form.getlist('mycheckbox'):
            print(getid)
            cur.execute('DELETE FROM contacts WHERE id = {0}'.format(getid))
            conn.commit()
        flash('Successfully Deleted!')
    return redirect('/')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Delete multiple records by selecting checkboxes using Python Flask with PostgreSQL</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Delete multiple records by selecting checkboxes using Python Flask with PostgreSQL</h3><br />
   <form method="POST" action="/delete">
   <div class="table-responsive">
    <div align="right" style="padding:10px;">
        {% with messages = get_flashed_messages() %}
          {% if messages %}
         {% for message in messages %}
         <div class="alert alert-danger" role="alert">{{ message }}</div>
         {% endfor %}
         {% endif %}
        {% endwith %}
       <input type="submit" value="Delete All Selected" class="btn btn-primary">  
      </div>
    <table class="table table-bordered">
     <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Delete</th>
     </tr>
     {% for row in contacts %}
     <tr id="{{row.id}}" >
      <td>{{row.fullname}}</td>
      <td>{{row.position}}</td>
      <td>{{row.office}}</td>
      <td><input type="checkbox" name="mycheckbox" value="{{row.id}}" /></td>
     </tr>
     {% endfor %}
    </table>
   </div>
   </form>  
 </body>
</html>

Monday, July 12, 2021

Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database

Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE tbl_user (
id serial PRIMARY KEY,
username VARCHAR ( 150 ) NOT NULL,
useremail VARCHAR ( 150 ) NOT NULL
);
app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
    
app = Flask(__name__)
    
app.secret_key = "caircocoders-ednalan"
    
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
        
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
 
@app.route('/')
def index():
    return render_template('index.html')
  
@app.route("/ajaxprogressbar",methods=["POST","GET"])
def ajaxprogressbar():
    if request.method == 'POST':
        username = request.form['username']
        useremail = request.form['useremail']
        print(username)
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("INSERT INTO tbl_user (username, useremail) VALUES (%s, %s)",[username, useremail])
        conn.commit()
        cur.close()
        msg = 'New record created successfully'    
    return jsonify(msg)
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database</title>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
    $('#sample_form').on('submit', function(event){
        event.preventDefault();
        var count_error = 0;
        if($('#username').val() == '') {
            $('#first_name_error').text('User Name is required');
            count_error++;
        }else
        {
            $('#first_name_error').text('');
        }
  
        if($('#useremail').val() == '') {
            $('#last_name_error').text('Email is required');
            count_error++;
        }else {
            $('#last_name_error').text('');
        }
  
        if(count_error == 0)
        {
            $.ajax({
                url:"/ajaxprogressbar",
                method:"POST",
                data:$(this).serialize(),
                beforeSend:function()
                {
                    $('#save').attr('disabled', 'disabled');
                    $('#process').css('display', 'block');
                },
                success:function(data)
                { 
                    var percentage = 0;
                    var timer = setInterval(function(){
                    percentage = percentage + 20;
                    progress_bar_process(percentage, timer,data);
                    }, 1000);
                }
            })
        }else{
            return false;
        }
  });
    
  function progress_bar_process(percentage, timer,data)
  {
    $('.progress-bar').css('width', percentage + '%');
    if(percentage > 100)
    {
        clearInterval(timer);
        $('#sample_form')[0].reset();
        $('#process').css('display', 'none');
        $('.progress-bar').css('width', '0%');
        $('#save').attr('disabled', false);
        $('#success_message').html(data);
        setTimeout(function(){
        $('#success_message').html('');
        }, 5000);
    }
  }
    
 });
</script>
</head>
<body><br /><br />
<div class="container">
   <h1 align="center">Progress Bar Data Insert using Python Flask Jquery Ajax Bootstrap and PostgreSQL database</h1>
   <br />
   <div class="panel panel-default">
        <div class="panel-heading">
        <h3 class="panel-title">Registration</h3>
        </div>
        <div class="panel-body">
            <span id="success_message"></span>
            <form method="post" id="sample_form">
                <div class="form-group">
                    <label>User Name</label>
                    <input type="text" name="username" id="username" class="form-control" />
                    <span id="first_name_error" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="text" name="useremail" id="useremail" class="form-control" />
                    <span id="last_name_error" class="text-danger"></span>
                </div>
                <div class="form-group" align="center">
                    <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
                </div>
            </form>
            <div class="form-group" id="process" style="display:none;">
                <div class="progress">
                    <div class="progress-bar progress-bar-striped active bg-success" role="progressbar" aria-valuemin="0" aria-valuemax="100" style=""></div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Add Remove Input Fields Dynamically with JQuery Ajax Python Flask and PostgreSQL

Add Remove Input Fields Dynamically with JQuery Ajax Python Flask and PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE skills (
id serial PRIMARY KEY,
skillname VARCHAR ( 150 ) NOT NULL
);
app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
    
app = Flask(__name__)
    
app.secret_key = "caircocoders-ednalan"
    
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
        
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
 
@app.route('/')
def index():
    return render_template('index.html')
 
@app.route("/postskill",methods=["POST","GET"])
def postskill():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        skills = request.form.getlist('skill[]')
        for value in skills:  
            cur.execute("INSERT INTO skills (skillname) VALUES (%s)",[value])
            conn.commit()       
        cur.close()
        msg = 'New record created successfully'    
    return jsonify(msg)
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Remove Input Fields Dynamically with JQuery Ajax Python Flask and PostgreSQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>    
</head>
<body>
 <script>
$(document).ready(function() {
  
var MaxInputs       = 8; //maximum input boxes allowed
var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton       = $("#AddMoreFileBox"); //Add button ID
  
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
  
$(AddButton).click(function (e)  //on add input button click
{
    if(x <= MaxInputs) //max input box allowed
    {
        FieldCount++; //text box added increment
        //add input box
        $(InputsWrapper).append('<div class="row"><p class="col-xs-6"><input type="text" placeholder="Enter your skill" class="form-control skill_list" name="skill[]" id="field_'+ FieldCount +'" value="Enter your skill '+ FieldCount +'"/></p><a href="#" class="btn btn-danger removeclass">×</a></div>');
        x++; //text box increment
    }
    return false;
});
  
$("body").on("click",".removeclass", function(e){ //user click on remove text
    if( x > 1 ) {
        $(this).parent('div').remove(); //remove text box
         x--; //decrement textbox
    }
    return false;
})

 $('#submit').click(function(){            
    $.ajax({  
        url:"/postskill",  
        method:"POST",  
        data:$('#add_skills').serialize(),  
        success:function(data)  
        {  alert(data)
            $('#resultbox').html(data);  
            $('#add_skills')[0].reset();  
        }  
    });  
}); 

});
</script>
<style>
.row {padding:10px;}
</style>
<div class="container"><br /> <br />  
    <h2 align="center">Add Remove Input Fields Dynamically with JQuery Ajax Python Flask and PostgreSQL</h2><div id="resultbox"></div>  
    <div class="form-group">  
        <form name="add_skills" id="add_skills">  
        <div id="InputsWrapper">
            <div class="row">
                <div class="col-xs-6"><input type="text" name="skill[]" placeholder="Enter your skill" class="form-control name_list" /></div>
                <div class="col-xs-6"><button type="button" name="add" id="AddMoreFileBox" class="btn btn-success">Add More</button></div>
            </div>
        </div>
        <br/>
        <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
        </form>  
    </div>  
</div>  
</body>
</html>

Related Post