ZatackCoder https://zatackcoder.com/ Its All About Code Sat, 29 Oct 2022 13:19:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.0.3 https://zatackcoder.com/wp-content/uploads/2015/09/cropped-zatackcoderlogo-32x32.png ZatackCoder https://zatackcoder.com/ 32 32 Autocomplete Widget In Flutter https://zatackcoder.com/autocomplete-widget-in-flutter/ https://zatackcoder.com/autocomplete-widget-in-flutter/#respond Sat, 29 Oct 2022 13:19:40 +0000 https://zatackcoder.com/?p=3046 Hello Friends, Today we are going to learn how to use Autocomplete Widget in Flutter. Actually when I was working on Pincode to City conversion feature for my personal project using Indian Post API, that time there I was needed this feature too. So let’s start without wasting any time and if you want to...

The post Autocomplete Widget In Flutter appeared first on ZatackCoder.

]]>

Hello Friends, Today we are going to learn how to use Autocomplete Widget in Flutter. Actually when I was working on Pincode to City conversion feature for my personal project using Indian Post API, that time there I was needed this feature too. So let’s start without wasting any time and if you want to learn more about Autocomplete Widget please check https://api.flutter.dev/flutter/material/Autocomplete-class.html

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Autocomplete Widget Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Autocomplete Widget Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> suggestions = [
    "Apple",
    "Banana",
    "Cucumber",
    "Doctor",
    "Everywhere",
    "Fruits",
    "Guava",
    "Honey",
    "Ice-Cream"
        "Jack-fruit",
    "Kite"
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Padding(
        padding: EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Autocomplete<String>(
              optionsBuilder: (TextEditingValue textEditingValue) async {
                return suggestions
                    .where((String val) => val
                        .toLowerCase()
                        .contains(textEditingValue.text.toLowerCase()))
                    .toList();
              },
              fieldViewBuilder: (BuildContext context,
                  TextEditingController fieldTextEditingController,
                  FocusNode fieldFocusNode,
                  VoidCallback onFieldSubmitted) {
                return TextFormField(
                    key: GlobalKey<FormState>(),
                    controller: fieldTextEditingController,
                    focusNode: fieldFocusNode);
              },
              onSelected: (String selection) {
                print("${selection}");
              },
              optionsViewBuilder: (BuildContext context,
                  AutocompleteOnSelected<String> onSelected,
                  Iterable<String> options) {
                return Align(
                  alignment: Alignment.topLeft,
                  child: Material(
                    child: Container(
                      color: Colors.blue,
                      width: MediaQuery.of(context).size.width - 28,
                      child: ListView.builder(
                        padding: EdgeInsets.all(10.0),
                        itemCount: options.length,
                        itemBuilder: (BuildContext context, int index) {
                          final String option = options.elementAt(index);

                          return GestureDetector(
                            onTap: () {
                              onSelected(option);
                            },
                            child: ListTile(
                              title: Text("${option}",
                                  style: const TextStyle(color: Colors.white)),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Output

 

Source Code

https://github.com/rajeshkumarsahanee/autocomplete_widget_test

Thanks for visiting
If you find this helpful then please do share

The post Autocomplete Widget In Flutter appeared first on ZatackCoder.

]]>
https://zatackcoder.com/autocomplete-widget-in-flutter/feed/ 0
How to Get City and State Name from Pincode in Flutter https://zatackcoder.com/how-to-get-city-and-state-name-from-pincode-in-flutter/ https://zatackcoder.com/how-to-get-city-and-state-name-from-pincode-in-flutter/#respond Sun, 23 Oct 2022 08:21:56 +0000 https://zatackcoder.com/?p=3048 Hello Friends, Today we are going to learn how to get city and state name from Pincode in Flutter. And for this we are going to utilize Indian Post API. This feature was needed in one of my personal project and now I thought to share it for you guys. So let’s start without wasting...

The post How to Get City and State Name from Pincode in Flutter appeared first on ZatackCoder.

]]>

Hello Friends, Today we are going to learn how to get city and state name from Pincode in Flutter. And for this we are going to utilize Indian Post API. This feature was needed in one of my personal project and now I thought to share it for you guys. So let’s start without wasting any time.

pubspec.yaml

name: pincode_to_city
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.2 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

  #networking
  http: ^0.13.5

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

location.dart

class Location {
  String name;
  String district;
  String region;
  String state;

  Location(this.name, this.district, this.region, this.state);

  factory Location.fromJson(Map<String, dynamic> json) {
    return Location(
        json['Name'], json['District'], json['Region'], json['State']);
  }
}

main.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:pincode_to_city/location.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pincode to City',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Pincode to City'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Location> locations = [];
  String status = '';

  _getLocations(pincode) {
    setState(() {
      status = 'Please wait...';
    });
    final JsonDecoder _decoder = const JsonDecoder();
    http
        .get(Uri.parse("http://www.postalpincode.in/api/pincode/$pincode"))
        .then((http.Response response) {
      final String res = response.body;
      final int statusCode = response.statusCode;

      if (statusCode < 200 || statusCode > 400) {
        throw Exception("Error while fetching data");
      }

      setState(() {
        var json = _decoder.convert(res);
        var tmp = json['PostOffice'] as List;
        locations =
            tmp.map<Location>((json) => Location.fromJson(json)).toList();
        status = 'All Locations at Pincode ' + pincode;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              key: GlobalKey<FormState>(),
              decoration: InputDecoration(
                contentPadding:
                    EdgeInsets.symmetric(vertical: 6, horizontal: 12),
                labelText: "Pincode",
                floatingLabelBehavior: FloatingLabelBehavior.auto,
              ),
              onFieldSubmitted: (val) => _getLocations(val),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(status,
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            ),
            Expanded(
              child: ListView.builder(
                padding: EdgeInsets.all(10.0),
                itemCount: locations.length,
                itemBuilder: (BuildContext context, int index) {
                  final Location location = locations.elementAt(index);

                  return Card(
                    child: ListTile(
                      title: Text(location.name),
                      subtitle: Text('District: ' +
                          location.district +
                          '\nRegion: ' +
                          location.region +
                          '\nState: ' +
                          location.state),
                    ),
                  );
                },
              ),
            )
          ],
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Output

Source Code

https://github.com/rajeshkumarsahanee/pincode_to_city

Thanks for Stoping by
If you find this helpful then please do share

 

The post How to Get City and State Name from Pincode in Flutter appeared first on ZatackCoder.

]]>
https://zatackcoder.com/how-to-get-city-and-state-name-from-pincode-in-flutter/feed/ 0
Flutter Mobile OTP Verification using Firebase with Getx Package https://zatackcoder.com/flutter-mobile-otp-verification-using-firebase-with-getx-package/ https://zatackcoder.com/flutter-mobile-otp-verification-using-firebase-with-getx-package/#respond Wed, 19 Oct 2022 11:00:47 +0000 https://zatackcoder.com/?p=3043 Hello Friends, Today I am going to share how to do Mobile OTP Verification in Flutter using Firebase with Getx Package. GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, intelligent dependency injection, and route management quickly and practically. We will follow following steps to achieve Mobile OTP Verification:- 1....

The post Flutter Mobile OTP Verification using Firebase with Getx Package appeared first on ZatackCoder.

]]>

Hello Friends, Today I am going to share how to do Mobile OTP Verification in Flutter using Firebase with Getx Package. GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, intelligent dependency injection, and route management quickly and practically. We will follow following steps to achieve Mobile OTP Verification:-

1. Create Firebase Project
2. Create App in Firebase Project
3. Enable Mobile Authentication
4. Create Flutter App
5. Generate Certificate Fingerprint and Provide it Firebase

Let’s get started

1. Creating Firebase Project

Step-Wise screenshots Taken While Creating Project

2. Create App in Firebase Project

Step-Wise screenshots Taken While Creating App in Project

3. Enable Mobile Authentication

Step-Wise screenshots Taken While Enabling Mobile Authentication

4. Create Flutter App

Paste google-services.json in App level directory which we have downloaded while creating App (see third screenshot of Create App in Firebase Project)

Now let’s start coding

build.gradle (Project Level)

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        classpath "com.google.gms:google-services:4.3.13"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle (Module Level)

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.zatackcoder.otp_login_app"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion 19
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation platform('com.google.firebase:firebase-bom:30.4.1')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-auth'
}

pubspec.yaml

name: otp_login_app
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.2 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

  #architecture
  get: ^4.6.5

  #auth
  firebase_core: ^1.24.0
  firebase_auth: ^3.11.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:otp_login_app/views/home.dart';
import 'package:otp_login_app/views/login.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'OTP Login App',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          appBarTheme: const AppBarTheme(
              backgroundColor: Colors.white,
              iconTheme: IconThemeData(color: Colors.black))),
      getPages: [
        GetPage(name: "/login", page: () => LoginPage()),
        GetPage(name: "/home", page: () => HomePage()),
      ],
      initialRoute: "/login",
    );
  }
}

views/login.dart

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:otp_login_app/controllers/auth_controller.dart';

class LoginPage extends StatelessWidget {
  final authController = Get.put(AuthController());
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      body: Stack(children: [
        Obx(() => authController.isOtpSent.value
            ? _buildVerifyOtpForm()
            : _buildGetOtpForm())
      ]),
    );
  }

  Widget _buildGetOtpForm() {
    return SafeArea(
      child: Form(
        key: _formKey,
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 24, horizontal: 32),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Let's Sign in",
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Obx(() => Column(
                      children: [
                        TextFormField(
                          keyboardType: TextInputType.number,
                          maxLength: 10,
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                          onChanged: (val) {
                            authController.phoneNo.value = val;
                            authController.showPrefix.value = val.length > 0;
                          },
                          onSaved: (val) => authController.phoneNo.value = val!,
                          validator: (val) => (val!.isEmpty || val!.length < 10)
                              ? "Enter valid number"
                              : null,
                          decoration: InputDecoration(
                            hintText: "Mobile Number",
                            labelText: "Mobile Number",
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.black12),
                                borderRadius: BorderRadius.circular(10)),
                            focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.black12),
                                borderRadius: BorderRadius.circular(10)),
                            prefix: authController.showPrefix.value
                                ? Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 8),
                                    child: Text(
                                      '(+91)',
                                      style: TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  )
                                : null,
                            suffixIcon: _buildSuffixIcon(),
                          ),
                        ),
                        SizedBox(
                          height: 22,
                        ),
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: () {
                              final form = _formKey.currentState;
                              if (form!.validate()) {
                                form.save();
                                authController.getOtp();
                              }
                            },
                            style: ElevatedButton.styleFrom(
                              foregroundColor: Colors.white,
                              // backgroundColor: kPrimaryColor,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(24.0),
                              ),
                            ),
                            child: Padding(
                              padding: EdgeInsets.all(14.0),
                              child: Text(
                                'Get OTP',
                                style: TextStyle(fontSize: 16),
                              ),
                            ),
                          ),
                        )
                      ],
                    )),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildVerifyOtpForm() {
    List<TextEditingController> otpFieldsControler = [
      TextEditingController(),
      TextEditingController(),
      TextEditingController(),
      TextEditingController(),
      TextEditingController(),
      TextEditingController()
    ];

    return SafeArea(
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 24, horizontal: 0),
        child: Column(
          children: [
            Align(
              alignment: Alignment.topLeft,
              child: GestureDetector(
                onTap: () {
                  authController.isOtpSent.value = false;
                  Get.back();
                },
                child: Icon(
                  Icons.arrow_back,
                  size: 32,
                  color: Colors.black54,
                ),
              ),
            ),
            SizedBox(
              height: 180,
            ),
            Text(
              'Verification',
              style: TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Enter your OTP code number",
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: Colors.black38,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(
              height: 28,
            ),
            Container(
              padding: EdgeInsets.all(28),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _textFieldOTP(
                          first: true,
                          last: false,
                          controller: otpFieldsControler[0]),
                      _textFieldOTP(
                          first: false,
                          last: false,
                          controller: otpFieldsControler[1]),
                      _textFieldOTP(
                          first: false,
                          last: false,
                          controller: otpFieldsControler[2]),
                      _textFieldOTP(
                          first: false,
                          last: false,
                          controller: otpFieldsControler[3]),
                      _textFieldOTP(
                          first: false,
                          last: false,
                          controller: otpFieldsControler[4]),
                      _textFieldOTP(
                          first: false,
                          last: true,
                          controller: otpFieldsControler[5]),
                    ],
                  ),
                  Text(
                    authController.statusMessage.value,
                    style: TextStyle(
                        color: authController.statusMessageColor.value,
                        fontWeight: FontWeight.bold),
                  ),
                  SizedBox(
                    height: 22,
                  ),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () {
                        authController.otp.value = "";
                        otpFieldsControler.forEach((controller) {
                          authController.otp.value += controller.text;
                        });
                        authController.verifyOTP();
                      },
                      style: ButtonStyle(
                        foregroundColor:
                            MaterialStateProperty.all<Color>(Colors.white),
                        // backgroundColor:
                        //     MaterialStateProperty.all<Color>(kPrimaryColor),
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(24.0),
                          ),
                        ),
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(14.0),
                        child: Text(
                          'Verify',
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(
              height: 18,
            ),
            Text(
              "Didn't receive any code?",
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: Colors.black38,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(
              height: 18,
            ),
            Obx(
              () => TextButton(
                onPressed: () => authController.resendOTP.value
                    ? authController.resendOtp()
                    : null,
                child: Text(
                  authController.resendOTP.value
                      ? "Resend New Code"
                      : "Wait ${authController.resendAfter} seconds",
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.purple,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSuffixIcon() {
    return AnimatedOpacity(
        opacity: authController.phoneNo?.value.length == 10 ? 1.0 : 0.0,
        duration: const Duration(milliseconds: 250),
        child: Icon(Icons.check_circle, color: Colors.green, size: 32));
  }

  Widget _textFieldOTP({bool first = true, last, controller}) {
    var height = (Get.width - 82) / 6;
    return Container(
      height: height,
      child: AspectRatio(
        aspectRatio: 1,
        child: TextField(
          autofocus: true,
          controller: controller,
          onChanged: (value) {
            if (value.length == 1 && last == false) {
              Get.focusScope?.nextFocus();
            }
            if (value.length == 0 && first == false) {
              Get.focusScope?.previousFocus();
            }
          },
          showCursor: false,
          readOnly: false,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: height / 2, fontWeight: FontWeight.bold),
          keyboardType: TextInputType.number,
          maxLength: 1,
          decoration: InputDecoration(
            isDense: true,
            contentPadding: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
            counter: Offstage(),
            enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(width: 2, color: Colors.black12),
                borderRadius: BorderRadius.circular(12)),
            focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(width: 2, color: Colors.purple),
                borderRadius: BorderRadius.circular(12)),
          ),
        ),
      ),
    );
  }
}

views/home.dart

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home", style: TextStyle(color: Colors.black)),
      ),
      body: Center(
        child: Text("Home Page after Otp Verification"),
      ),
    );
  }
}

controllers/auth_controller.dart

import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:otp_login_app/views/home.dart';

class AuthController extends GetxController
    with GetSingleTickerProviderStateMixin {
  var showPrefix = false.obs;
  var isLogin = true;
  var phoneNo = "".obs;
  var otp = "".obs;
  var isOtpSent = false.obs;
  var resendAfter = 30.obs;
  var resendOTP = false.obs;
  var firebaseVerificationId = "";
  var statusMessage = "".obs;
  var statusMessageColor = Colors.black.obs;

  var timer;

  AuthController() {}

  @override
  onInit() async {
    super.onInit();
  }

  getOtp() async {
    FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: '+91' + phoneNo.value,
      verificationCompleted: (PhoneAuthCredential credential) {},
      verificationFailed: (FirebaseAuthException e) {},
      codeSent: (String verificationId, int? resendToken) {
        firebaseVerificationId = verificationId;
        isOtpSent.value = true;
        statusMessage.value = "OTP sent to +91" + phoneNo.value;
        startResendOtpTimer();
      },
      codeAutoRetrievalTimeout: (String verificationId) {},
    );
  }

  resendOtp() async {
    resendOTP.value = false;
    FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: '+91' + phoneNo.value,
      verificationCompleted: (PhoneAuthCredential credential) {},
      verificationFailed: (FirebaseAuthException e) {},
      codeSent: (String verificationId, int? resendToken) {
        firebaseVerificationId = verificationId;
        isOtpSent.value = true;
        statusMessage.value = "OTP re-sent to +91" + phoneNo.value;
        startResendOtpTimer();
      },
      codeAutoRetrievalTimeout: (String verificationId) {},
    );
  }

  verifyOTP() async {
    FirebaseAuth auth = FirebaseAuth.instance;
    try {
      statusMessage.value = "Verifying... " + otp.value;
      // Create a PhoneAuthCredential with the code
      PhoneAuthCredential credential = PhoneAuthProvider.credential(
          verificationId: firebaseVerificationId, smsCode: otp.value);
      // Sign the user in (or link) with the credential
      await auth.signInWithCredential(credential);
      Get.off(HomePage());
    } catch (e) {
      statusMessage.value = "Invalid  OTP";
      statusMessageColor = Colors.red.obs;
    }
  }

  startResendOtpTimer() {
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (resendAfter.value != 0) {
        resendAfter.value--;
      } else {
        resendAfter.value = 30;
        resendOTP.value = true;
        timer.cancel();
      }
      update();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }
}

5. Generate Certificate Fingerprint and Provide it to Firebase

Run below command after going to android folder and copy SHA1 and SHA-256 and provide it to Firebase App by going to Project Settings see below screenshots for help

./gradlew signingReport

Output

Source Code

https://github.com/rajeshkumarsahanee/otp_login_app

Notes

1. Please make sure package name should match with your flutter app’s package name while creating App in Firebase Project

 

Thanks for Stoping by
If you find this helpful then please do share

The post Flutter Mobile OTP Verification using Firebase with Getx Package appeared first on ZatackCoder.

]]>
https://zatackcoder.com/flutter-mobile-otp-verification-using-firebase-with-getx-package/feed/ 0
Reading Html from Any Url in PHP https://zatackcoder.com/reading-html-from-any-url-in-php/ https://zatackcoder.com/reading-html-from-any-url-in-php/#respond Sun, 11 Sep 2022 04:33:07 +0000 http://zatackcoder.com/?p=304 Hello Friends, Today I am going to share very short and simple code which we can use to read html from any url in PHP. I am going to share two methods to achieve this, so let’s start without wasting time. Method 1 (Using file_get_contents) [crayon-635d2d8cc156d613480867/] Method 2 (Using Curl) [crayon-635d2d8cc1570296975527/]   Thanks friends Your...

The post Reading Html from Any Url in PHP appeared first on ZatackCoder.

]]>

Hello Friends, Today I am going to share very short and simple code which we can use to read html from any url in PHP. I am going to share two methods to achieve this, so let’s start without wasting time.

Method 1 (Using file_get_contents)

<?php 
$htmlData = file_get_contents("https://www.lipsum.com/");
echo $htmlData;
?>

Method 2 (Using Curl)

<?php 
$url = "https://www.lipsum.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$output = curl_exec($ch);
echo $output;
?>

 

Thanks friends
Your queries & suggestions are welcome in comments section
Please don’t forget to share if you find this helpful

The post Reading Html from Any Url in PHP appeared first on ZatackCoder.

]]>
https://zatackcoder.com/reading-html-from-any-url-in-php/feed/ 0
DataTable with Ajax Data Source https://zatackcoder.com/datatable-with-ajax-data-source/ https://zatackcoder.com/datatable-with-ajax-data-source/#respond Wed, 07 Sep 2022 05:04:40 +0000 https://zatackcoder.com/?p=2983 Hello Friends, Hope you are doing well today I am going to share how to use DataTable with Ajax Data Source or you can say how to perform server side processing in DataTable. Actually I was working on one of my personal project where I was needed this  feature and After implementing on my project...

The post DataTable with Ajax Data Source appeared first on ZatackCoder.

]]>

Hello Friends, Hope you are doing well today I am going to share how to use DataTable with Ajax Data Source or you can say how to perform server side processing in DataTable.

Actually I was working on one of my personal project where I was needed this  feature and After implementing on my project I thought to share it with you guys. If you don’t know what DataTable is then let me tell you it is nothing but a plug-in for the jQuery Javascript library to work with Html Tables. It comes with various features like searching, sorting, pagination. Let’s start

We will do this coding in three steps:-

  1. Html & Javascript
  2. Table Structure
  3. PHP Script

Html & Javascript

<!DOCTYPE html>
<html>

<head>
    <title>DataTable with Ajax Data Source</title>
    <!-- Datatable CSS -->
    <link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <h1>DataTable with Ajax Data Source Example</h1>
    <!-- Table -->
    <table id="employeeTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start Date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <!-- jQuery Library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Datatable JS -->
    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

    <script>
        $('#employeeTable').dataTable({
            'processing': true,
            'serverSide': true,
            'serverMethod': 'post',
            "ajax": {
                "url": "get-data.php",
            },
            'columns': [{
                    data: 'name'
                },
                {
                    data: 'position'
                },
                {
                    data: 'office'
                },
                {
                    data: 'age'
                },
                {
                    data: 'start_date'
                },
                {
                    data: 'salary'
                },
            ],
            destroy: true,
        });
    </script>
</body>

</html>

Table Structure

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(256) NOT NULL,
  `position` varchar(256) NOT NULL,
  `office` varchar(256) NOT NULL,
  `age` int(11) NOT NULL,
  `start_date` date NOT NULL,
  `salary` varchar(56) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for table `employee`
--
ALTER TABLE `employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `employee`
--
ALTER TABLE `employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58;
COMMIT;

PHP Scripts

<?php
date_default_timezone_set("Asia/Kolkata");

define("DATABASE_NAME", "datatables_db");

function getConnection()
{
    $servername = "localhost";
    $username = "root";
    $password = "";

    // Create connection
    $conn = new mysqli($servername, $username, $password, DATABASE_NAME);
    // Check connection
    if (mysqli_connect_error()) {
        die("Database connection failed: " . mysqli_connect_error());
    } else {
        return $conn;
    }
}

<?php
// Database Connection
include_once 'config.php';

$conn = getConnection();

$draw = $_REQUEST['draw'];
$offset = $_REQUEST['start'];
$limit = $_REQUEST['length']; // Rows display per page
$columnIndex = $_REQUEST['order'][0]['column']; // Column index
$order_by = $_REQUEST['columns'][$columnIndex]['data']; // Column name
$order = $_REQUEST['order'][0]['dir']; // asc or desc

$searchValue = mysqli_real_escape_string($conn, $_REQUEST['search']['value']); // Search value

// Search Query
$searchQuery = " ";
if ($searchValue != '') {
    $searchQuery = " AND (name LIKE '%$searchValue%' OR 
        position LIKE '%$searchValue%' OR 
        office LIKE '%$searchValue%' OR 
        age LIKE '%$searchValue%' OR 
        start_date LIKE '%$searchValue%' OR 
        salary LIKE '%$searchValue%') ";
}

// Total entries before filter
$results = $conn->query("SELECT COUNT(id) as total FROM employee");
$record = $results->fetch_assoc();
$totalRecords = $record['total'];

// Total entries after filter
$results = $conn->query("SELECT COUNT(id) as total FROM employee WHERE 1 " . $searchQuery);
$record = $results->fetch_assoc();
$totalRecordwithFilter = $record['total'];

// Entries with filter, order & limit
$results = $conn->query("SELECT * FROM employee WHERE 1 " . $searchQuery . " ORDER BY " . $order_by . " " . $order . " LIMIT " . $offset . "," . $limit);
$data = array();

while ($row = $results->fetch_assoc()) {
    $data[] = $row;
}

// Response
$response = array(
    "draw" => intval($draw),
    "iTotalRecords" => $totalRecords,
    "iTotalDisplayRecords" => $totalRecordwithFilter,
    "aaData" => $data
);

header("Content-Type:application/json");
echo json_encode($response);
exit();

Output

Script Download

 

Note:

Please make sure that AJAX response data field names should match with columns data defined during DataTable initialization otherwise field value not be read.

Thanks friends
Your queries & suggestions are welcome in comments section
Please don’t forget to share if you find this helpful

The post DataTable with Ajax Data Source appeared first on ZatackCoder.

]]>
https://zatackcoder.com/datatable-with-ajax-data-source/feed/ 0
Converting Timestamp to Time Ago in PHP https://zatackcoder.com/converting-timestamp-to-time-ago-in-php/ https://zatackcoder.com/converting-timestamp-to-time-ago-in-php/#respond Fri, 02 Sep 2022 05:30:21 +0000 https://zatackcoder.com/?p=2985 Hello Friends, Its being very long time I haven’t posted anything due to busy life schedule but today I have some free time to write a post and also a code which I had found over internet yesterday while working on a client’s project. In that project I had to show time in Ago format...

The post Converting Timestamp to Time Ago in PHP appeared first on ZatackCoder.

]]>

Hello Friends, Its being very long time I haven’t posted anything due to busy life schedule but today I have some free time to write a post and also a code which I had found over internet yesterday while working on a client’s project. In that project I had to show time in Ago format (i.e 1 month ago, 2 minutes ago, etc ) by converting Timestamp (YYYY-MM-DD HH:MM:SS) or Epoch timestamp. So Let’s start without wasting any time.

Here is the Function

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Usage Example

echo time_elapsed_string('2022-09-02 00:22:35');
echo time_elapsed_string('@1662093103'); # epoch timestamp input
echo time_elapsed_string('2022-09-02 00:22:35', true);

Output

10 hours ago
10 hours ago
10 hours, 3 minutes, 58 seconds ago

Script Download

 

Thanks friends
Your queries & suggestions are welcome in comments section
Please don’t forget to share if you find this helpful

The post Converting Timestamp to Time Ago in PHP appeared first on ZatackCoder.

]]>
https://zatackcoder.com/converting-timestamp-to-time-ago-in-php/feed/ 0
Test API With Online Testing Tool without Sign Up & Get Code https://zatackcoder.com/test-api-with-online-testing-tool-without-sign-up-get-code/ Tue, 23 Nov 2021 12:24:52 +0000 https://zatackcoder.com/?p=2973 Friends, this post is for beginners who don’t know to deal with API’s and most API providers don’t provide complete code, instead, they provide basic documentation where shows URLs & parameters only. If you are a beginner you might face issues integrating with your code. Online REST & SOUP API Testing Tool I also faced...

The post Test API With Online Testing Tool without Sign Up & Get Code appeared first on ZatackCoder.

]]>

Friends, this post is for beginners who don’t know to deal with API’s and most API providers don’t provide complete code, instead, they provide basic documentation where shows URLs & parameters only. If you are a beginner you might face issues integrating with your code.

Online REST & SOUP API Testing Tool

I also faced similar issues in earlier days so I thought I should create a post for this. Today I am here with a solution with an online tool named Reqbin. It’s a very easy tool you can directly test your APIs without signup & Generate Code.

Here you can test any API & Get Code in Any Programming Language

Code Sample:-

<?php

$url = "https://www.facebook.com";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);

?>

Hope this post is helpful to you guys. Please Like Share & comment

The post Test API With Online Testing Tool without Sign Up & Get Code appeared first on ZatackCoder.

]]>
Add webhooks WATI WhatsApp API Gateway in Php https://zatackcoder.com/add-webhooks-wati-whatsapp-api-gateway-in-php/ Mon, 22 Nov 2021 10:13:42 +0000 https://zatackcoder.com/?p=2968 Recently I was working on a project that needs to set up a webhook to fetch incoming messages. So I thought I should share the code & the procedure with you. So let’s get started. If you are going to setup WhatsApp API so I assume you are aware of the WATI Dashboard interface, so...

The post Add webhooks WATI WhatsApp API Gateway in Php appeared first on ZatackCoder.

]]>

Recently I was working on a project that needs to set up a webhook to fetch incoming messages. So I thought I should share the code & the procedure with you. So let’s get started.

If you are going to setup WhatsApp API so I assume you are aware of the WATI Dashboard interface, so I am not going to explain the dashboard features

  • To set up a callback URL where WATI pushes data on new messages. Navigate to 3 lines in the menu

  • Click on the Add webhook to push data onto your server and add the URL

<?php
// Fetch Data from Webhook
$data = file_get_contents("php://input");
//Decode from json
$events = json_decode($data, true);
//Store data into variables
$id = $events['id'];
$created = $events['created'];
$conversationId = $events['conversationId'];
$ticketId = $events['ticketId'];
$text = $events['text'];
$type = $events['type'];
$data = $events['data'];
$timestamp = $events['timestamp'];
$owner = $events['owner'];
$eventType = $events['eventType'];
$statusString = $events['statusString'];
$avatarUrl = $events['avatarUrl'];
$assignedId = $events['assignedId'];
$operatorName = $events['operatorName'];
$waId = $events['waId'] = '918802915988';
$messageConatct = $events['messageConatct'];
//Store to your databas
$sql = "INSERT INTO test (id,created,conversationId,ticketId,text,type,data,timestamp,owner,eventType,statusString,avatarUrl,assignedId,operatorName,waId,messageConatct)
        VALUES('$id','$created','$conversationId','$ticketId','$text','$type','$data','$timestamp','$owner','$eventType','$statusString','$avatarUrl','$assignedId','$operatorName','$waId','$messageConatct')";
$con->query($sql);

Please Like Share & Comment. Your support encourages us to post more helpful content.  Have a good day

The post Add webhooks WATI WhatsApp API Gateway in Php appeared first on ZatackCoder.

]]>
Check/Uncheck all checkbox using jQuery https://zatackcoder.com/check-uncheck-all-checkbox-using-jquery/ Thu, 18 Nov 2021 06:40:11 +0000 https://zatackcoder.com/?p=2961 Hi Guys, In this post let’s learn using jquery how to check all checkboxes if not checked and if they all checked it will uncheck Let’s Begin:- HTML [crayon-635d2d8cc1af3282266049/] Before Code for jquery don’t forget to add the CDN link. [crayon-635d2d8cc1af5628504144/] Jquery Code:- [crayon-635d2d8cc1af6184598358/] Another code:- [crayon-635d2d8cc1af7097482046/] SOURCE Hope it will be useful for you....

The post Check/Uncheck all checkbox using jQuery appeared first on ZatackCoder.

]]>

Hi Guys, In this post let’s learn using jquery how to check all checkboxes if not checked and if they all checked it will uncheck Let’s Begin:-

HTML

<html>
<input type="checkbox" id="checkAll">Check All
<hr />
<input type="checkbox" id="checkItem">Item 1
<input type="checkbox" id="checkItem">Item 2
<input type="checkbox" id="checkItem">Item3
</html>

Before Code for jquery don’t forget to add the CDN link.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Jquery Code:-

<script> 
$("#checkAll").click(function () {
     $('input:checkbox').not(this).prop('checked', this.checked);
 });
</script>

Another code:-

<script>
    $(document).ready(function() {
        $("#checkAll").click(function() {
            $("#checkItem").prop('checked', $(this).prop('checked'));
        });
    });
</script>

SOURCE

Hope it will be useful for you. Do like & share with your developer’s community. It motivates us to keep posting valuable content.

The post Check/Uncheck all checkbox using jQuery appeared first on ZatackCoder.

]]>
Cron Job Hack : Use cURL in a Cron Job https://zatackcoder.com/cron-job-hack-use-curl-in-a-cron-job/ Thu, 18 Nov 2021 05:42:27 +0000 https://zatackcoder.com/?p=2955 Hi Friends, Hope you guys are doing well. It’s been a long time I haven’t share anything but today I am going to share how to use cURL in a cron job. It is useful when sometimes your server’s cron job is not acting as per your expectations or it has some restrictions. In this...

The post Cron Job Hack : Use cURL in a Cron Job appeared first on ZatackCoder.

]]>

Hi Friends, Hope you guys are doing well. It’s been a long time I haven’t share anything but today I am going to share how to use cURL in a cron job. It is useful when sometimes your server’s cron job is not acting as per your expectations or it has some restrictions.

In this condition, you can take help from another server using this command.

curl https://www.yourdomain.com/cron.php

If you don’t want to get a notification email every time when cron job executes so you can use it.

>/dev/null 2>&1

So the complete command will look like it.

https://www.yourdomain.com/cronjob.php >/dev/null 2>&1

You can get help to set timings for execution for cron job

Here are 3 examples of cron jobs

The first cron job is executed every 5 minutes

In the 2nd example, the cron job executes every 23 hours

In the 3rd example, Cron Job executes every Saturday 05:33. A cron job week start from Monday. so Saturday will be the 6th day of the week.

 

I hope with the above examples you have learned of the functioning of CRON JOB using cURL. Please do like & share. It motivates us to keep working to post useful content.

The post Cron Job Hack : Use cURL in a Cron Job appeared first on ZatackCoder.

]]>