28 June 2023

How to use form validations(Jquery validations) in step form?

<!DOCTYPE html>
<html>
<head>
<title>Multi-file Upload</title>
<style>
fieldset {
  display: none;
}

fieldset:first-child {
  display: block;
}

button {
  margin-top: 10px;
}

.prev {
  margin-right: 10px;
}
.drop-zone {
  border: 2px dashed #ccc;
  width: 300px;
  height: 200px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
}
.file-preview {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}
.file-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
  margin-bottom: 10px;
}
.file-item img {
  width: 50px;
  height: 50px;
  margin-right: 5px;
}
.remove-btn {
  cursor: pointer;
  color: red;
  font-weight: bold;
}
.file_preview_error{
  color:red;
}
.error{
  color:red;
  display:block;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
  // Initialize validation for the form
  $('#stepForm').validate({
    rules: {
      name: 'required',
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 6
      },
      confirmPassword: {
        required: true,
        equalTo: '#password'
      },
      username: 'required',
      address: 'required',
      city: 'required'
    },
    messages: {
      // Customize error messages for each field if needed
    },
    errorPlacement: function(error, element) {
      // Customize error placement if needed
      error.insertAfter(element);
    }
  });
  function thirdStepJqueryValidations(){
    $("#stepForm").validate({
      rules: {
        username: "required",
        },
      // In 'messages' user have to specify message as per rules
      messages: {
        username: "Username is required."
      }
    });
    return $("#stepForm").valid();
  }
  // Step navigation
  var currentStep = 0;
  var fieldsets = $('#stepForm fieldset');
  var stepsCount = fieldsets.length;

  function navigateTo(step) {
    // Hide all fieldsets
    fieldsets.hide();
    // Show the selected step
    $(fieldsets[step]).fadeIn('slow');
    // Disable previous button if on the first step
    $('.prev').prop('disabled', step === 0);
    // Change the text of the next button on the last step
    if (step === stepsCount - 1) {
      $('.next').text('Submit');
    } else {
      $('.next').text('Next');
    }
  }
  function dropFileValidation(){
    var dropZone = $('#file_preview');
    $(".file_preview_error").text("");
    if (dropZone.is(':empty')) {
        // The drop zone is empty
        // Perform your validation logic here or take appropriate actions
  /*       console.log("The drop zone is empty."); */
        $(".file_preview_error").text("This field is required.");
        return false;
      }
    return true;
  }
  $('.next').click(function() {
      console.log(currentStep);
      if(currentStep == 2){
        if(!thirdStepJqueryValidations() || !dropFileValidation()) {
          dropFileValidation();
          return false;
        }
      }
    if ($('#stepForm').valid()) {
        currentStep++;
        navigateTo(currentStep);
    }
  });
  $('.prev').click(function() {
    currentStep--;
    navigateTo(currentStep);
  });
});

window.addEventListener("DOMContentLoaded", () => {
  const dropZone = document.getElementById("dropzone");
  const filePreview = document.getElementById("file_preview");
  // Handle file drop
  dropZone.addEventListener("drop", (e) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    handleFiles(files);
  });
  // Handle file drag over
  dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
  });
  // Handle file input change
  dropZone.addEventListener("click", () => {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.multiple = true;
    fileInput.accept = "image/*";
    fileInput.addEventListener("change", (e) => {
      $(".file_preview_error").text("");
      const files = e.target.files;
      handleFiles(files);
    });
    fileInput.click();
  });
  // Handle file removal
  filePreview.addEventListener("click", (e) => {
    if (e.target.classList.contains("remove-btn")) {
      const fileItem = e.target.parentElement;
      const fileName = fileItem.getAttribute("data-file-name");
      fileItem.remove();
    }
  });
  function handleFiles(files) {
    for (const file of files) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const fileContent = e.target.result;
        displayFile(file, fileContent);
      };
      reader.readAsDataURL(file);
    }
  }
  function displayFile(file, fileContent) {
    const fileItem = document.createElement("div");
    fileItem.classList.add("file-item");
    fileItem.setAttribute("data-file-name", file.name);
    const image = document.createElement("img");
    image.src = fileContent;
    // Create the input element
    const inputElement = document.createElement("input");
    // Set the input type and value attributes
    inputElement.setAttribute("type", "hidden");
    inputElement.setAttribute("name", "files[]");
    inputElement.setAttribute("value", fileContent + "?filename=" + file.name);
    const fileName = document.createElement("span");
    fileName.innerText = file.name;
    const removeBtn = document.createElement("span");
    removeBtn.classList.add("remove-btn");
    removeBtn.innerText = "Remove";
    fileItem.appendChild(image);
    fileItem.appendChild(inputElement);
    fileItem.appendChild(fileName);
    fileItem.appendChild(removeBtn);
    filePreview.appendChild(fileItem);
  }
});
</script>
</head>
<body>
<form id="stepForm" method="post">
  <fieldset>
    <h2>Step 1</h2>
    <input type="text" name="name" id="name" placeholder="Name">
    <input type="email" name="email" id="email" placeholder="Email">
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Step 2</h2>
    <input type="password" name="password" id="password" placeholder="Password">
    <input type="password" name="confirmPassword" id="confirmPassword" placeholder="Confirm Password">
    <button type="button" class="prev">Previous</button>
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Uploader</h2>
    <input type="text" name="username" >
    <div class="drop-zone" id="dropzone">
    <span>Drag and drop files here</span>
  </div>
  <div class="file-preview" id="file_preview"></div>
  <div class="file_preview_error"></div>

    <button type="button" class="prev">Previous</button>
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Step 3</h2>
    <input type="text" name="address" id="address" placeholder="Address">
    <input type="text" name="city" id="city" placeholder="City">
    <button type="button" class="prev">Previous</button>
    <button type="submit">Submit</button>
  </fieldset>
</form>
</body>
</html>

 

How to use sweet alert (Trash Sweet Alert) before redirect link?

 <button type="btn" class="btn_cancel deleteOnElement" type="button" data-route="{{ route('cancel-order', $order_id) }}">Cancel</button>


<!-- sweet alert -->

 <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>


<script type="text/javascript">

//end application user type

$(document).on('click','.deleteOnElement', function(event)

{

      var route  = $(this).data('route');

      //alert(route);

      swal({

        title: "Confirm Trash",

        text: "Are you sure you want to cancel this request? ",

        icon: "warning",

        buttons: true,

        dangerMode: true,

      })

      .then((willDelete) => {

        if (willDelete) {

          window.location.replace(route);

        } else {

          swal("Your data is safe!");

        }

      });          

});

</script>

23 June 2023

How to copy commits from one Git repository to another repository (GitHub)?

https://stackoverflow.com/questions/37471740/how-to-copy-commits-from-one-git-repo-to-another
 

# add the old repo as a remote repository 

git remote add oldrepo https://github.com/path/to/oldrepo

# get the old repo commits
git remote update

# examine the whole tree
git log --all --oneline --graph --decorate

# copy (cherry-pick) the commits from the old repo into your new local one
git cherry-pick sha-of-commit-one
git cherry-pick sha-of-commit-two
git cherry-pick sha-of-commit-three

# check your local repo is correct
git log

# send your new tree (repo state) to github
git push origin master

# remove the now-unneeded reference to oldrepo
git remote remove oldrepo

22 March 2023

How to get day week day names by rangs of week day names in PHP?

Get day week day names by rangs of week day names in PHP

<!DOCTYPE html>

<html>

<body>

<?php

function getWeekdaysInRange($start, $end) {

    $weekdays = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

    $start_index = array_search($start, $weekdays);

    $end_index = array_search($end, $weekdays);

    $result = array();

    if ($start_index === false || $end_index === false) {

        return $result;

    }

    $current_index = $start_index;

    while ($current_index !== $end_index) {

        $result[] = $weekdays[$current_index];

        $current_index = ($current_index + 1) % 7;

    }

    $result[] = $weekdays[$end_index];

    return $result;

}

$weekdays = getWeekdaysInRange('Saturday', 'Friday');

print_r($weekdays);

?>

</body>

</html>

 

 

How to print rataing stars in PHP?

Print rataing stars in PHP?


<?php

        $average_reviews = round($post->average_reviews);

        if(!empty($average_reviews)){

            $i = 1;

            while($i <= 5){

                if($i <= $average_reviews){

                ?>

                <img style="" src="<?php echo theme_url();?>/assets/img/organic.png">

                <?php

                }

                else{

                    ?>

                    <img style="" src="<?php echo theme_url();?>/assets/img/2017-10-10.png">

                    <?php

                }

                $i++;

            }

            echo "(" . $average_reviews . ")"; 

        }  

?>


How to get XML data from URL in PHP?

Get XML data from URL in PHP

function get_xml_from_url($url){

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

  $xmlstr = curl_exec($ch);

  curl_close($ch);

  return $xmlstr;

27 February 2023

How to use datatable in laravel 8 ?

Use datatable in laravel 8


<?php


/* =====In Controller file===== */

use DataTables;   


   public function ajax_get_blogs(Request $request)

    {

        if ($request->ajax()) {

            $data = Blog::select('*');

            return Datatables::of($data)

                    ->addIndexColumn()

                    ->addColumn('featured_image', function($row){


                        if($row->featured_image == ''){ $featured_image = asset("upload/image-not-found.jpg"); } else {  $featured_image =  asset("upload/" . $row->featured_image); }


                        $featured_image_view = '<img src="'. $featured_image .'">';

 

                         return $featured_image_view;

                         })


                    ->addColumn('action', function($row){


                           $btn = '<a href="javascript:void(0)" data-blog_id = ' . $row->id . ' class="edit btn btn-primary btn-sm">View</a>';

    

                            return $btn;

                    })

                    ->rawColumns(['action','featured_image'])

                    ->make(true);

        }

        

        return view('admin.blogs.blogs-list');

    }

/* =====In Blade file===== */

?>

<html>

    <head>

        <style>

            img {

                border: 1px solid red;

                width: 200px;

                height: 150px;

                object-fit: cover;

            }

            img[src=""] {

                background:url("http://localhost/laravel-testing/upload/images/blogs/build.jpg");

                object-fit: cover;

            }

        </style>

        <meta name="csrf-token" content="{{ csrf_token() }}">  

    </head>

    <body>

    <table id="blog_post_table">

        <thead>

            <tr>

                <th>No</th>

                <th>Title</th>

                <th>Description</th>

                <th>Image</th>

                <th width="100px">Action</th>

            </tr>

        </thead>

        <tbody>            

        </tbody>

    </table>

<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.css">

<script>

    jQuery(document).ready(function($){

        $(function () {

            var table = $('#blog_post_table').DataTable({

            processing: true,

            serverSide: true,

            ajax: "{{ route('blogs.AjaxGetBlogs') }}",

            columns: [

                {data: 'id', name: 'id'},

                {data: 'title', name: 'title'},

                {data: 'description', name: 'description'},

                {data: 'featured_image', name: 'featured_image', orderable: false, searchable: false},

                {data: 'action', name: 'action', orderable: false, searchable: false},

            ]

        });


        });

    });

</script>

</body>

</html>

How to fetch instagram posts data?

Fetch Instagram posts data by pasting this code in browser console. (() => { /* ====================================================...