29 November 2023

How to create remove and add more inputs functionality with input type file and text in Laravel?

Create remove and add more inputs functionality with input type file and text in Laravel

Blade file code   

  <form action="{{ route('storeDocuments') }}" method="post" enctype="multipart/form-data">

        @csrf

        <div id="inputFields">

            @if(!empty($documents[0]))

            @php $counter = 1000; @endphp

                @foreach($documents as $document)

                    <input type="hidden" id="document_id" name="documents[{{$counter}}][document_id]" value="{{$document->id}}">

                    <div class="field">

                        <label for="title">Title:</label>

                        <input type="text" id="title" class="title_input" name="documents[{{$counter}}][title]" value="{{$document->title}}" required>

                        <label for="description">Description:</label>

                        <textarea id="description" class="description_input" name="documents[{{$counter}}][description]">{{$document->description}}</textarea>

                        <label for="file">File:</label>

                        @if(!empty($document->file_path))

                        <a href="{{$document->file_path}}" class="doc_file">Download</a>

                        @endif

                        <input type="file" id="file" class="file_input" name="documents[{{$counter}}][file]" required>

                        <button class="remove">Remove</button>

                    </div>

                    @php $counter++ @endphp

                @endforeach

            @endif

            <div class="field">

                <label for="title">Title:</label>

                <input type="text" id="title" class="title_input" name="documents[0][title]" required>

                <label for="description">Description:</label>

                <textarea id="description" class="description_input" name="documents[0][description]"></textarea>

                <label for="file">File:</label>

                <input type="file" id="file" class="file_input" name="documents[0][file]" required>

                <button class="remove">Remove</button>

            </div>

        </div>

        <button id="addButton">Add More</button>

        <div class="col-sm-12">

            <div class="form-group mt-3">

                <div class="form-group submit">

                    <div class="form-submit">

                        <input type="submit" value="Submit" class="btn btn-success btn-lg" />

                    </div>

                </div>

            </div>

        </div>

    </form>

  <script>

    $(document).ready(function() {

       function removeButton(){

            var removeButtons = $(".remove");

            if (removeButtons.length == 1) {

                removeButtons.hide();

            }

            else{

                removeButtons.show();

            }

            console.log(removeButtons.length);

        }


        removeButton();

        $(".field").find('.remove').click(function() {

          $(this).parent().remove();

          removeButton();

        });

        let documentIndex = 1; // Initialize the document index

        $('#addButton').click(function(e) {

            documentIndex++;

            e.preventDefault();

            var newField = $('.field:last').clone();

            newField.find('.title_input').attr('name', 'documents[' + documentIndex + '][title]');

            newField.find('.description_input').attr('name', 'documents[' + documentIndex + '][description]');

            newField.find('.file_input').attr('name', 'documents[' + documentIndex + '][file]');

            newField.find('input').val('');

            newField.find('textarea').val('');

            $('#inputFields').append(newField);

            removeButton();

            // Add event listener for remove button

            newField.find('.remove').click(function() {

            $(this).parent().remove();

            removeButton();

            });

        });

    });

  </script>


Controller file

    public function store(Request $request,BaseHttpResponse $response)

    {

        $customer = auth('customer')->user();

        if(!empty($request->documents)){

            $documents = $request->documents;

            $insert_data = [];

            foreach($documents as $document){

                if(empty($document["title"]) && empty($document["description"]) && empty($document["file"])){

                    continue;

                }


                if(!empty($document["file"])){

                    // Accessing uploaded file from the request

                    $uploadedFile = $document["file"];


                    // Check if a file was uploaded

                    if ($uploadedFile && $uploadedFile->isValid()) {

                        // Get the original file name

                        $originalFileName = $uploadedFile->getClientOriginalName();


                        // Generate a unique filename

                        $uniqueFileName = pathinfo($originalFileName, PATHINFO_FILENAME) . '_' . time() . '.' . $uploadedFile->getClientOriginalExtension();


                        // Store the file in the storage disk with a unique filename

                        $storagePath = "documents" . "/" . $uniqueFileName;

                        $filePath = Storage::disk('uploads')->putFileAs('documents', $uploadedFile, $uniqueFileName);

                        $insert_data["file_path"] = $storagePath;                    

                    }

                }


                if(!empty($document["title"])){

                    $insert_data["title"] = $document["title"];

                }

                if(!empty($document["description"])){

                    $insert_data["description"] = $document["description"];

                }

                if(!empty($document["document_id"])){

                    $document_id = $document["document_id"];

                    $document = Document::find($document_id)->update($insert_data);

                }

                else{

                    $document = Document::create($insert_data);

                }


            }

        }

        $message = '';

        if(!empty($document->id)){

            $message = 'Documents data has been uploaded successfully';

        }

        return $response

        ->setNextUrl(url()->previous())

        ->setMessage(__($message));

    }

26 September 2023

How to show shape file (.shp)(map) on map with shape file?

Show shape file (.shp)(map) on map with shape file

Include gasparesganga package in php code
https://gasparesganga.com/labs/php-shapefile/


<?php


// Register autoloader

require_once('vendor/gasparesganga/php-shapefile/src/Shapefile/ShapefileAutoloader.php');

Shapefile\ShapefileAutoloader::register();


// Import classes

use Shapefile\Shapefile;

use Shapefile\ShapefileException;

use Shapefile\ShapefileReader;

try {

    // Open Shapefile

    $Shapefile = new ShapefileReader('filepath/shapefile.shp');

    

   // $json_data = $Shapefile->fetchRecord()->getGeoJSON();

    $geoJsonArray = [];

    while ($Geometry = $Shapefile->fetchRecord()) {

        // Skip the record if marked as "deleted"

        if ($Geometry->isDeleted()) {

            continue;

        }

        

         // Print Geometry as an Array

/*         print_r($Geometry->getArray());

        

        // Print Geometry as WKT

        print_r($Geometry->getWKT());

        

        // Print Geometry as GeoJSON

        print_r($Geometry->getGeoJSON());

        

        // Print DBF data

        print_r($Geometry->getDataArray()); */

      $geoJsonArray[] = $Geometry->getGeoJSON();

    }


} catch (ShapefileException $e) {

    // Print detailed error information

    echo "Error Type: " . $e->getErrorType()

        . "\nMessage: " . $e->getMessage()

        . "\nDetails: " . $e->getDetails();

}


$geoJsonArray = json_encode($geoJsonArray);

?>



<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Map View</title>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />

</head>

<body>

    <div id="map" style="width: 100%; height: 500px;"></div>

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

    <script>

        var map = L.map('map').setView([42.383, -93.305], 13); // Adjust the initial view


        // Add a base layer (OpenStreetMap)

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {

            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'

        }).addTo(map);


        // GeoJSON data

        var geoJsonData = "<?php echo $geoJsonArray; ?>";


        // Iterate through the array of GeoJSON strings and add them to the map

        geoJsonData.forEach(function(geoJsonString) {

            var geoJson = JSON.parse(geoJsonString);

            L.geoJSON(geoJson).addTo(map);

        });

    </script>

</body>

</html>


20 September 2023

How to check date format in PHP?

Check date format in PHP


function isCorrectDateFromat($date){

    if(!empty($date)){

        $dateString = $date; // Replace this with your date string

        $format = "Y-m-d"; // Replace this with your expected date format

        $dateTime = DateTime::createFromFormat($format, $dateString);

        if ($dateTime === false) {

/*             echo "The date is not in the correct format."; */

        } else {

            $errors = DateTime::getLastErrors();

            if (empty($errors)) {

/*                 echo "The date is in the correct format."; */

                return true;

            } else {

/*                 echo "The date is not in the correct format."; */

            }

        }


    }

    return false;

How to delete previous image on update new image or delete record in laravel?

Delete previous image on update new image or delete record in laravel

Laravel Model

public function getProfileImageAttribute($profile_image)

    {

        if(!empty($profile_image))

        {

            return $filepath = URL::to('/') . '/public/upload/' . $profile_image;

        }

    }


    // Custom method to get the original unmodified URL

    public function getOriginalProfileImageAttribute()

    {

        return $this->attributes['profile_image'];

    }


    function deleteProfileImage(){

        $model = $this;

        // Check if the avatar attribute is changing

        if ($model->isDirty('profile_image')) {

            // Delete the previous profile image if it exists

            $previousFile = $model->getOriginal('original_profile_image');

            if (!empty($previousFile) && Storage::disk('uploads')->exists($previousFile)) {

                // Delete the file

                Storage::disk('uploads')->delete($previousFile);

            }

        }

    }


    protected static function boot()

    {

        parent::boot();


        static::updating(function ($model) {

            $model->deleteProfileImage();

        });

        static::deleting(function ($model) {

            // Delete the previous profile image if it exists

            $previousFile = $model->getOriginal('original_profile_image');

            if (!empty($previousFile) && Storage::disk('uploads')->exists($previousFile)) {

                // Delete the file

                Storage::disk('uploads')->delete($previousFile);

            }

        });

    } 

26 July 2023

How to integrate one signal push notification in website (Laravel)?

Integrate one signal push notification

    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
    <script>
    var OneSignal = window.OneSignal || [];
        var initConfig = {
            appId: "{{ env('OneSignalApp_ID') }}",
            notifyButton: {
                enable: true
            },
        };
        OneSignal.push(function () {
            OneSignal.init(initConfig);
            console.log(OneSignal);
        });
        OneSignal.push(function() {
/*             OneSignal.isPushNotificationsEnabled(function(isEnabled) {
                if (isEnabled)
                console.log("Push notifications are enabled!");
                else
                console.log("Push notifications are not enabled yet.");    
            }); */

            OneSignal.isPushNotificationsEnabled(function(isEnabled) {
            if (isEnabled) {
                // user has subscribed
                OneSignal.getUserId( function(userId) {
                    console.log('player_id of the subscribed user is : ' + userId);
                    if($("#one_signal_player_id").length > 0){
                        $("#one_signal_player_id").val(userId);
                    }
                    // Make a POST call to your server with the user ID        
                });
            }
            });
        });
        </script>

How to integrate pubnub chat in website?

Integrate pubnub chat

 
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.7.2.3.min.js"></script>

<style>

.user_pubnub_mgs {

    height: 450px;

    border: 1px solid #d0d0d0;

    padding: 10px 12px;

    overflow-y: auto;

}

.other_user_chat {

    background: #b4b4b4;

    margin-bottom: 10px;

    padding: 10px;

    width: fit-content;

    font-size: 14px;

    border-radius: 10px 0px 10px 10px;

    color: #fff;

    display: block;

    word-break: break-word;

}

.current_user_chat {

    background: #2695ee;

    margin-bottom: 10px;

    padding: 10px;

    width: fit-content;

    font-size: 14px;

    border-radius: 10px 0px 10px 10px;

    color: #fff;

    display: block;

    word-break: break-word;

    margin-left: auto;

}

#send_chat_bt {

    background: #2695ee;

}

#send_chat_bt[disabled] {

    background: #dadada !important;

}

</style>

<script>

const buttonClick = () => {

    var input = document.getElementById('message-input');

    publishMessage(input.value);

    input.value = '';

};


const delete_full_messages = () => {

    var channel_name = "hello_world";

    pubnub_delete_full_messages(channel_name);

};


const showMessage = (msg) => {

var message = '';

msg = msg;

if(msg !== null && msg !== ""){

    var currentUserId = {{ auth('customer')->user()->id }};

    console.log(msg);

    var user_class = '';

    if (currentUserId == msg.user_id) {

        user_class = "current_user_chat";

    }

    else{

        user_class = "other_user_chat";

    }

    console.log(user_class);

    message = "<div class='chat_messages " + user_class + "'>" + msg.chat_message     + "</div>"

    $('#messages').append(message);

    if(message){

         const divElement = $(".user_pubnub_mgs");

        const innerScrollHeight = divElement.prop("scrollHeight") - divElement.height();

        $(".user_pubnub_mgs").animate({

            scrollTop: $('.user_pubnub_mgs').offset().top + innerScrollHeight

        }, 0); 

    }  

}  

};



const appendMessageToWebPage = (message) => {

    myObj = message.entry.chat_message;

    if (myObj !== null && typeof myObj !== 'undefined') {

        showMessage(message.entry);

    }

}


let pubnub;

const setupPubNub = () => {

    // Update this block with your publish/subscribe keys

    pubnub = new PubNub({

        publishKey: "pub-c-52377dc0-a888-44a0-841f-825b319416b9",

        subscribeKey: "sub-c-c2a10f4c-394c-4b89-ba16-4de660c4f0b0",

        userId: "1"

    });


    // add listener

    const listener = {

        status: (statusEvent) => {

            if (statusEvent.category === "PNConnectedCategory") {

                console.log("Connected");

            }

        },

        message: (messageEvent) => {


            // handle message

            const channelName = messageEvent.channel;

            const channelGroup = messageEvent.subscription;

            const publishTimetoken = messageEvent.timetoken;

            const msg = messageEvent.message;

            const publisher = messageEvent.publisher;


            //show time

            const unixTimestamp = messageEvent.timetoken / 10000000;

            const gmtDate = new Date(unixTimestamp * 1000);

            const localeDateTime = gmtDate.toLocaleString();



            showMessage(messageEvent.message);


        },

        messageAction: function(ma) {

            // handle message actions

            console.log('messageAction');

        },

        presence: (presenceEvent) => {

            // handle presence

            console.log('working');

        }


    };

    pubnub.addListener(listener);


    // subscribe to a channel

    pubnub.subscribe({

        channels: ["hello_world"]

    });



    pubnub.history({

        channel: 'hello_world',


    }, function(status, response) {

/*         console.log(response.messages); */

        if (response.messages.length) {

            console.log(response.messages);

            response.messages.forEach(appendMessageToWebPage);

        }


    });


};


// run after page is loaded

window.onload = setupPubNub;

// publish message

const publishMessage = async (message) => {

    // With the right payload, you can publish a message, add a reaction to a message,

    // send a push notification, or send a small payload called a signal.

    var currentUserId = {{ auth('customer')->user()->id }};

    const publishPayload = {

        channel: "hello_world",

        message: {

            title: "User Chat",

            type: "user_chat",

            chat_message: message,

            user_id: currentUserId,

            read: 0,

        }

    };

    await pubnub.publish(publishPayload);

}

// Delete_messages message

const pubnub_delete_full_messages = async (channel_name) => {

    // With the right payload, you can publish a message, add a reaction to a message,

    // send a push notification, or send a small payload called a signal.

    try {

        const result = await pubnub.deleteMessages({

            channel: channel_name,

            //start: "15088506076921021",

            //end: "15088532035597390",

        });

    } catch (status) {

        console.log(status);

    }

}

</script>

<div class="ps-section__header">

    <h3>Messages</h3>


    <!-- <div class="float-right">

            <a class="add-address ps-btn ps-btn--sm ps-btn--small" href="{{ route('customer.address.create') }}">

                <span>{{ __('Add a new address') }}</span>

            </a>

        </div> -->

</div>

<div class="ps-section__content">

    <div>

<!--         <button onclick="delete_full_messages()">Delete messages</button> -->

        <div id="messages" class="user_pubnub_mgs"></div>

        <input id="message-input" type="text">

        <button onclick="buttonClick()" id="send_chat_bt">Send</button>

    </div>

</div>

<script>

$(document).ready(function(){

    $("body").on("click, keyup","#message-input", function(){

    var message_body =  $(this).val();

        if(message_body){

            $("#send_chat_bt").prop('disabled', false);

        }

        else{

            $("#send_chat_bt").prop('disabled', true);

        }

    });

    $(document).on('keyup','#message-input',function(e){

            if (e.code === "Enter") {  //checks whether the pressed key is "Enter"

                buttonClick();

            }

    });

});


</script>


How to create load more on scroll functionality in laravel?

Create load more on scroll functionality in laravel

Main listing file
<style>
.notifications_page_cover_ui {
    overflow: auto;
    max-height: 474px;
}
</style>
<div class="ps-section__right">
    <div class="section-header">
        <h3>Notifications</h3>
    </div>
    <div class="section-content">
       <div class="notifications_page_cover_ui" id="load-more-container">
        <?php echo $notification_list ?>
       </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    let lastNotificationID = {!! $lastNotificationID !!}; // Pass the last item ID from your controller or view
    let loading = false;
    function loadMoreData() {
        if (loading) {
            return; // If a request is already in progress, do nothing
        }
        loading = true; // Set the flag to indicate that a request is in progress
        $.ajax({
            url:  "{{route('customer.loadMoreNotifications')}}",
            method: 'GET',
            data: { lastNotificationID: lastNotificationID },
            success: function(response) {
                loading = false; // Reset the flag when the request is complete
                if (response["notification_list"].length > 0) {
                    let notification_list = '';
                    /* console.log();  */
                    $('#load-more-container').append(response["notification_list"]);
                    lastNotificationID = response["lastNotificationID"];
                } else {
                    // No more data to load
                }
            },
            error: function() {
                loading = false; // Reset the flag in case of an error
            }
        });
    }

    $('#load-more-container').on('scroll', function() {
        let scrollableDiv = $(this);
        let scrollableHeight = scrollableDiv.prop('scrollHeight');
        let visibleHeight = scrollableDiv.height();
        let scrollPosition = scrollableDiv.scrollTop();
        if (scrollPosition + visibleHeight >= scrollableHeight - 100) {
            // Scroll has reached the end of the div
            loadMoreData();
        } else {
            // Scroll is not at the end of the div
        }
    });
});
</script>


Controller function file

    public function getNotifications(Request $request, BaseHttpResponse $response)
    {   
        $currentUser = auth('customer')->user();
        $notifications = Notification::where("sent_to",$currentUser->id)->with(["SentTo"])->orderBy("id","DESC")->paginate(10);
        $lastNotificationID = $notifications->last();
        $lastNotificationID = $lastNotificationID->id;
        $notification_list_view = Theme::getThemeNamespace() . '::views.ecommerce.customers.notifications.notification-list';
        $notification_list = view($notification_list_view,compact("notifications"))->render();
        return Theme::scope('ecommerce.customers.notifications.all-notifications',compact("lastNotificationID","notification_list"))->render();
    }

    public function loadMoreNotifications(Request $request)
    {
        $currentUser = auth('customer')->user();
        $lastNotificationID = $request->input('lastNotificationID');
        // Fetch more data from your model using the lastItemID as an offset
        $notifications = Notification::where('id', '<', $lastNotificationID)->where("sent_to",$currentUser->id)->with(["SentTo"])->orderBy("id","ASC")->paginate(10);
        if(!empty($notifications[0])){
            $lastNotificationID = $notifications->last();
            $lastNotificationID = $lastNotificationID->id;
        }
        $notification_list_view = Theme::getThemeNamespace() . '::views.ecommerce.customers.notifications.notification-list';
        $notification_list = view($notification_list_view,compact("notifications"))->render();
        $data = ["notification_list"=>$notification_list,"lastNotificationID"=>$lastNotificationID];
        return response()->json($data);
    }

Data listing file (notification-list.blade.php)

@if(!empty($notifications[0]))
    @foreach($notifications as $notification)
    <div class="notofication_card_ui {{ ($notification->is_read == '0')? 'project_assigned_ui' : ''}}">
        <div class="user_card_box">
            <span class="user_avatar"><img src="{{$notification->SentTo->avatar_url}}"></span>
            <div class="user_message_description"><h5 class="user_name">{{$notification->id}}{{$notification->SentTo->name}}</h5><span class="message__sent_time">{{$notification->created_time_ago}}</span></div>
        </div>
        <div class="user_comment_box">
        <p>{{$notification->message}}</p>
        </div>
        <div class="view_notification_btn"><a href="{{route('customer.readNotifications', $notification->id)}}" class="view_more_notification_btn">View</a></div>
    </div>
    @endforeach
@endif

28 June 2023

How to use Mutators and Accessors in Laravel?

Mutators and Accessors in Laravel     


Set file path in model

public function getFilePathAttribute($file_path)

    {

        if(!empty($file_path))

        {

             return $filepath = URL::to('/') . '/upload/' . $file_path;

/*             return asset('/upoad/' . $file_path); */


        }

    }

Set created time ago in model

protected $appends = ["created_time_ago"];

public function getCreatedTimeAgoAttribute()

    {

        $created_at = $this->attributes['created_at'];

        // Convert the date/time to a Carbon instance

        $carbonCreatedAt = Carbon::parse($created_at);

        // Get the "time ago" format

        $timeAgo = $carbonCreatedAt->diffForHumans();

        // Set the modified value to the column

        return $timeAgo;

    }

Set created time ago in model

public function getRequestedTimeAttribute($requested_time)

    {

        if(!empty($requested_time))

        {

             return date_format($requested_time,"Y-m-d");

        }

    }

How to upload multi file by base64 url in laravel?

Multi file upload by base64 url in laravel

Function


function uploadBase64File($base64_url){

    $response = array();

    $base64Data = $base64_url;

    $pattern = '/data:(.*);base64,([^"]*)/';

    // Perform the regular expression match

    preg_match($pattern, $base64Data, $matches);

    if (!empty($matches[1])) {

        $mime = $matches[1];

        // Remove the data:image/jpeg;base64, part from the string

        $mimeToExt = [

            'image/jpeg' => 'jpg',

            'image/png' => 'png',

            'image/gif' => 'gif',

            'image/bmp' => 'bmp',

            'image/webp' => 'webp',

            'application/pdf' => 'pdf',

            'application/msword' => 'doc',

            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',

            // Add more mappings as needed

        ];

        // Check if the MIME type exists in the mapping

        if (isset($mimeToExt[$mime])) {

            $extension = $mimeToExt[$mime];

        }

        

        $base64Data = str_replace('data:' . $matches[1] . ';base64,', '', $base64Data);

        // Decode the base64 data into binary format

        $fileData = base64_decode($base64Data);

        $urlParts = parse_url($base64Data);

        $queryString = $urlParts['query'];

        parse_str($queryString, $queryParameters);

        $original_filename = uniqid() . "-" . $queryParameters['filename'];

        if(empty($queryParameters['filename'])){

        // Generate a unique file name for the uploaded file

        $original_filename = uniqid() . "." . $extension;

        }

        $response["file_name"] = $original_filename; 

        $response["file_extension"] = $extension; 

        $response["file_data"] = $fileData; 

        return $response;

    }

}




=====================================================

Add base 64 url

$base64url = "";

$Base64File = uploadBase64File($base64url);

if(!empty($Base64File["file_name"])){

$original_filename = $Base64File["file_name"];

$file_extension = $Base64File["file_extension"];

$file_data = $Base64File["file_data"];

$storagePath = "service-requests/location-images" . "/" . $original_filename;

$filePath = Storage::disk('uploads')->put($storagePath, $file_data);

$ServiceRequestsDocs = ServiceRequestsDocs::create([

'file_extensions' => $file_extension,

'file_name' => $original_filename,

'file_path' => $storagePath,

]

);

}


Add below code in config\filesystem.php file

        'uploads' => [

            'driver' => 'local',

            'root' => public_path() .'/upload',

            'visibility' => 'public',

       ]


Add in Model file   
 public function getFilePathAttribute($file_path)

    {

        if(!empty($file_path))

        {

             return $filepath = URL::to('/') . '/upload/' . $file_path;

/*             return asset('/upoad/' . $file_path); */


        }

    }

How to use autofill google place APi(google Map APi)?

 <html>

    <head>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBcRA4LijSY8e-FG4lN1sTYChasKAEsrGo&libraries=places"></script>
    </head>
    <body>
    <input type="text" id="autocomplete-input" placeholder="Enter a location">
    </body>
    <script>
    // Replace 'YOUR_API_KEY' with your actual API key
    const apiKey = 'AIzaSyBcRA4LijSY8e-FG4lN1sTYChasKAEsrGo';

    // Initialize the autocomplete object
    const autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete-input'), {
    types: ['geocode'],  // Restrict the results to geographical locations
    apiKey: apiKey       // Provide your API key
    });

    // Add an event listener for when a place is selected
    autocomplete.addListener('place_changed', onPlaceSelected);

    // Handle the selected place
    function onPlaceSelected() {
    const place = autocomplete.getPlace();
    console.log(place); // You can access the selected place object here
    }
    </script>
</html>

How to preview, add more and remove file before upload?

 <!DOCTYPE html>

<?php
function decode_base64($base64Data){
$extension = null;
$pattern = '/data:(.*);base64,([^"]*)/';
// Perform the regular expression match
preg_match($pattern, $base64Data, $matches);
if(!empty($matches[1])){
$mime = $matches[1];
// Map MIME type to extension
$mimeToExt = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/bmp' => 'bmp',
    'image/webp' => 'webp',
    'application/pdf' => 'pdf',
    'application/msword' => 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
    // Add more mappings as needed
];
// Check if the MIME type exists in the mapping
if (isset($mimeToExt[$mime])) {
    $extension = $mimeToExt[$mime];
}
/*     print_r($matches);
    die('here'); */

// Remove the data:image/jpeg;base64, part from the string
 $base64Data = str_replace('data:' . $matches[1] . ';base64,', '', $base64Data);
// $base64Data = str_replace('data:image/jpeg;base64,', '', $base64Data);
// Decode the base64 data into binary format
$image_data = base64_decode($base64Data);
$urlParts = parse_url($base64Data);
$queryString = $urlParts['query'];
parse_str($queryString, $queryParameters);
$original_filename = $queryParameters['filename'];
if(empty($original_filename)){
// Generate a unique file name for the uploaded file
$original_filename = uniqid() . "." . $extension;
}
// $filename = uniqid() . '.jpeg';
// Specify the file path where you want to save the uploaded file
$filepath = 'uploads/' . $original_filename;

// Write the decoded binary data to the file
if (file_put_contents($filepath, $image_data)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}
}
else{
/*     print_r($base64Data); */
}
}
if(isset($_POST['submit'])){
    echo 'starting';
    echo "<pre>";
    $files = $_POST["files"];
    foreach($files as $file){
        $data = decode_base64($file);
    }
    print_R($data);
    die();
}
?>
<html>
<head>
  <title>Multi-file Upload</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
  <style>
    .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>

</head>
<body>
<form action="" method="post" id="my_form" enctype="multipart/form-data">    
  <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>
  <input type="submit" name="submit" value="submit" id="submit_bt">
</form>
  <script>
    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);
  }
});

$(document).ready(function() {
  function jqueryValidations(){
    $("#my_form").validate({
      rules: {
        username: "required",
        },
      // In 'messages' user have to specify message as per rules
      messages: {
        username: "Username is required."
      }
    });
    return $("#my_form").valid();
  }

  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;
  }

  $('#submit_bt').click(function(e) {

      if (!jqueryValidations() || !dropFileValidation()) {
        dropFileValidation();
        event.preventDefault(); // Prevent form submission if any validation fails
      }
    });
});
</script>
</body>
</html>

How to add re-captcha v3 on all Elementor forms using coding?

 Add re-captcha v3 on all Elementor forms using coding add_action('wp_footer',function(){     ?> <script src="https://www...