To print the modal content from the button outside the modal in another component in Vue 3

I have structture as follows

//main component
<button onClick="PrintModal()">Print</button>
<ModalComponent :active = active/>

//modal component
// All the modal headings and body

Now I want to print the modal contents from the button, the active is passed as a prop. And the modal is a form so all the values of the form are also passed as a prop while calling the modal component from the main component.

When I am using the window.print() it is printing the full screen not only the modal contents, but I want to print only the modal contents, I am not sure how to achieve this.

I have tried to do with the example in the example
But it does not work.

I’m receiving unknown/empty response from MS Graph (JS SDK) when trying to copy file

When trying to copy file from one location to another in sharepoint site, I’m receiving ReadableStream instead of URL to Location as in documentation. When trying to read that stream as Response, it seems to be empty anyways. Here is part of my code where I’m trying to do it:

    try {
      client
        .api(`/sites/${siteId}/drive/items/${fileTag}/copy`)
        .version('beta')
        .post({
          parentReference: {
            driveId: folderData.driveId,
            id: folderData.id,
          },
          '@microsoft.graph.conflictBehavior': 'replace',
        })
        .then((stream) => {
          console.log(stream);
          return new Response(stream);
        })
        .then((response) => console.log(response));
    } catch (error) {
      console.log(error);
      throw new HttpException(
        'There was an error whem trying to copy file.',
        HttpStatus.UNAUTHORIZED,
      );
    }

What’s important – file copying is working, at least for the first time. When I’m trying to copy again with rewrite policy, nothing is happening. I need to be able to copy file multiple times and overwrite it (so changes are visible in history).

Here is the response:

ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
Response {
  [Symbol(realm)]: { settingsObject: {} },
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: false,
    requestIncludesCredentials: false,
    type: 'default',
    status: 200,
    timingInfo: null,
    cacheState: '',
    statusText: '',
    headersList: HeadersList {
      cookies: null,
      [Symbol(headers map)]: Map(0) {},
      [Symbol(headers map sorted)]: null
    },
    urlList: [],
    body: { stream: undefined, source: null, length: null }
  },
  [Symbol(headers)]: HeadersList {
    cookies: null,
    [Symbol(headers map)]: Map(0) {},
    [Symbol(headers map sorted)]: null
  }
}

I was checking if removing beta would work (as it’s set here), but no difference. I haven’t found any other information about this error appearing in this endpoint.

Was checking type of stream (using .text(), .formData(), etc) but in all of them it seems to be empty.

Using front-end timout with jsTree

I have a web-application which is presenting data collected directly from an external API. To present the data, I’m using jsTree as the visual front-end plugin. The front-end element is defined like this:

("#dataTree").jstree({
  "core": {
    multiple: false,
    "themes": {
      "responsive": false
    },
    // so that create works
    "check_callback": true,
    "data": {
      "url": function (node) {
        return node.id === '#' ?
          "Some URL" :
          "Different URL";
      },      
      "data": function (node) {
        var sharePointId = '';
        if (node.original !== undefined) {
          sharePointId = node.original.rootElementId;
        }
        return {
          "parentId": node.id,
          "parentType": node.type,
          "childId": childId
        };
      }
    }
  },
  "types": {
    "default": {
      "icon": "fas fa-archive text-primary"
    },
    "Instance": {
      "icon": "fas fa-box text-primary"
    },
    "Folder": {
      "icon": "fa fa-folder  text-primary"
    },
    "Content": {
      "icon": "fas fa-list  text-primary"
    },
    "Child": {
      "icon": "fas fa-sitemap  text-primary"
    }
  },
  "state": {
    "key": "dataTree"
  },
  "plugins": ["dnd", "state", "types"]
});

The problem is that the external API is rather inconsistent regarding performance. At this moment this is unfortunatelly pretty much a given. Most of the time this works fine (performance ignored), but from time to time the performance is so bad, that the jsTree plugin cannot load the data anymore. The back-end can still be going, but the front-end (jsTree) is throwing a timeout.

I’m trying to figure out if I can declare the jsTree element so that it ignores the timeout, and letting the front-end be ‘loading’ as long as the back-end is fetching the data, but this is where the jsTree documentation falls short (or I can’t find it (a bit more probable)). Is this even possible, and if so, how is this achieved?

Encrypt/Decrypt data in cookie and hide decryption algorithm in JS file

I apologize if this is a duplicate. I looked quite a bit and didn’t find one that exactly answered this question.

I’m working on a Vanilla JS, Spring Boot application and am using Gmail Oauth to authenticate users. I need to send some login related data (like roles, username, email id) from the server to the browser. This data also needs to be shared across HTML pages.
After login, I’m redirecting the user to a HTML page and returning the above login data using a cookie. The JS code retrieves the data from the cookie.
I’m planning to encrypt the data in the cookie on the server side and decrypt it using JS on the client side. The issue is that the JS file can be viewed by the end user and the decryption algorithm will be visible to them. I don’t want the JS file to be visible. I researched this and found a couple of articles. Listing one here
https://dev.to/dhairyashah/how-to-hide-javascript-code-in-view-source-39kg/comments

This is a REST API project and no session state is allowed on the server.
If I don’t encrypt/decrypt, the end user can change the roles or the email id in the cookie. Changing the roles can cause undesirable behavior on the client side. Of course, I have spring security role based authorization set up on the server. So nothing untoward will happen on the server, but the UI behavior will be odd.

Here’s my question. I don’t see any point in encrypting/decrypting if I cannot successfully hide the JS file. Should I not do it since nothing bad can happen on the server side?

I have explained it above

Autocomplete dropdown list for 20’000+ choices

I am struggling to realize an autocomplete dropdown that can manage (rapidly) such a infinite amount of elements.

I am using Autocomplete by jQuery but it is ok for 100 elements, when it comes to be more (20k+) it becomes slow and useless.

My array list is as follows:

elenco_farmaci = [ { classe_farmaco: "A", nome_farmaco: "ABASAGLAR sc 5 cart 100 ui /ml 3 ml", principio_attivo: "INSULINA GLARGINE", nota_aifa : "", costo_euro : "60,69" },
...
20k+ lines
]

Whereas my calling function is as follows:

  $( function() {

  template.find("input[name^=nome_farmaco]").autocomplete({
      minLength: 0,
      source: elenco_farmaci,
      focus: function (event, ui) {
          console.log("Focus:" + ui.item.nome_farmaco)
          return false;
      },
      select: function (event, ui) {
          console.log("Select: " + ui.item.nome_farmaco)

          return false;
      }
  })
  .autocomplete("instance")._renderItem = function (ul, item) {
      console.log( "Aggiungo: " + item )

      return $("<li>")
          .append("<div>" + item.nome_farmaco + "<br>" + item.classe_farmaco + "</div>")
          .appendTo(ul);
  };
  } );

Any suggestion?

Using the data-list approach may work BUT it is not customizable and it comes, for very long drug names, to be small in width… Considering also that it is not dropping down from the input but it is shown on the side of the input.

The difficulty of the project is also made by the fact I am working with template that is dinamically added to the DOM when the previous line has been filled

template = $("template#prescrizione_box").contents().clone();
$("#myid").append(template.clone());

Node.js TCP server on Plesk not starting, “Server started on Port undefined” error

I’m trying to run a Node.js TCP server on a Plesk server, but I’m encountering issues. The server doesn’t start, and in the Passenger logs, I see the error backtrace:
in 'bool Passenger::SpawningKit::HandshakePerform::checkCurrentState()' (Perform.h:257)
in 'void Passenger::SpawningKit::HandshakePerform::waitUntilSpawningFinished(boost: :unique_lock<boost::mutex>&)' (Perform.h:213)
in 'Passenger::SpawningKit::Result Passenger::SpawningKit::HandshakePerform::execute()' (Perform.h:1752)
in 'Passenger::SpawningKit::Result Passenger::SpawningKit::DirectSpawner::internalSpawn(const AppPoolOptions&, Passenger::SpawningKit::Config&, Passenger::SpawningKit::HandshakeSession&, const Passenger::Json::Value&, Passenger::SpawningKit::JourneyStep&)' (DirectSpawner.h:211)
in 'virtual Passenger::SpawningKit::Result Passenger::SpawningKit::DirectSpawner::spawn(const AppPoolOptions&)' (DirectSpawner.h:261)
in 'void Passenger::ApplicationPool2::Group::spawnThreadRealMain(const SpawnerPtr&, const Passenger::ApplicationPool2::Options&, unsigned int)' (SpawningAndRestarting.cpp:95)

Stdout and stderr output:
Server started on Port undefined

The NodeJS code:

const net = require('net');

const serverPort = process.env.PORT;
const clients = {};

const server = net.createServer((client) => {
  console.log('New client connected');

  // Generate a random client ID
  const clientId = Math.random().toString(36).substring(7);
  clients[clientId] = client;

  // Greet the client with their ID
  client.write(`Welcome, your client ID is: ${clientId}rn`);

  client.on('data', (data) => {
    const request = data.toString().trim();
    console.log(`Message from ${clientId}: ${request}`);

    // Send the message to all other clients
    Object.keys(clients).forEach((otherClientId) => {
      if (otherClientId !== clientId) {
        clients[otherClientId].write(`nMessage from ${clientId}: ${request}n`);
      }
    });
  });

  client.on('end', () => {
    console.log(`Client ${clientId} disconnected`);
    // Remove the client from the list of connected clients
    delete clients[clientId];
  });

  client.on('error', (err) => {
    console.log(`Client ${clientId} caused an error: ${err.message}`);
    // Remove the client from the list of connected clients
    delete clients[clientId];
  });
});

server.listen(serverPort, () => {
  console.log(`Server started on port ${serverPort}`);
});

I suspect there might be a problem with setting the PORT environment variable in Plesk. I’ve tried setting it directly during script execution, but it doesn’t seem to work.
I can’t find an option in Plesk to set the environment variable, since NodeJS applications are processed via Passenger. How can I correctly configure the environment variable for a Node.js server on Plesk?
Everything works wonderfully in localhost. So I don’t think it’s the code.

Any help or insights into resolving this issue would be greatly appreciated!

Try:

  1. Set the serverPort variable directly to 3000 inside code
  2. Set the PORT variable to 3000 with plesk custom environment variables for this nodeJS project
  3. Tested the code in local network (worked)

Expecting:

  1. n clients can connect, e.g. via telnet
  2. Sent messages are forwarded to everyone except yourself
  3. If a client disconnects, it is removed from the clients array
  4. If a client has a error, it is removed from the clients array

Logon password show div localstorage

How to make it so that after logging in with the correct password, the div field shows and is stored in localstorage, and that the password fields and the login button hide after logging in with the correct password is successful

Jsfiddle example

(For reference although localStorage issues on Stack Snippets)

$(document).ready(function() {
  $('#foo').click(function() {
    $(this).siblings().toggle();
    //you need to pass string values, your variables display & block was not defined
    localStorage.setItem('display', $(this).siblings().is(':visible'));
  });
  var block = localStorage.getItem('display');
  if (block == 'true') {
    $('#bar').show()
  }
});

// Get references to the elements you'll be working with
var input = document.getElementById("password");
var div = document.getElementById("HIDDENDIV");
var btn = document.getElementById("button");

// Set up event handlers in JavaScript
button.addEventListener("click", validate);

function validate() {
  if (input.value == '123') {
    // No need to add a "show" class. Just remove the "hidden" class.
    div.classList.remove('hidden');
    // Or, add it:
    input.classList.add("hidden");
    $(this).siblings().toggle();
    //you need to pass string values, your variables display & block was not defined
    localStorage.setItem('display', $(this).siblings().is(':visible'));
    var block = localStorage.getItem('display');
    if (block == 'true') {
      $('#bar').show()
    }
    if ($("#bar:visible").length) {
      // it's visible
    } else {
      alert("Janela Acendeu!");
    }
  } else {
    password.focus(); // <-- If you don't do this first, your select code won't work
    password.setSelectionRange(0, password.value.length);
    alert('Senha Incorreta ! tente novamente...');
  }
}

input.addEventListener("keydown", function(event) {
  if (event.keyCode === 13) {
    // No reason to simulate a button click. Just call the code that needs to be run.
    validate();
  }
});
<input type="text" id="password">
<br>
<input id="button" type="button" value="Login">
<div id="HIDDENDIV" class="hidden">bla</div>

<div id="container">
  <a id="foo" href="javascript:void(0);">Click Me</a>
  <div class="conteudo1" id="bar">xxxxxx</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

the password for access in the example is 123

The idea would be, the content will be shown and keep showing after successful login.
Any ideas and help please?

increment value in JS object depending on key

I have a pretty simple setup like this:

var itemsPerAssignee = {}

My plan is to save the amount of items in this object, so I can later iterate over it and, depending on the key, output the specific value on how many items are left for that specific user.

In my for-loop I iterate like this, to fill the object:

query.forEach(function (task) {
    var assignee = task.getAssignee();
    itemsPerAssignee[assignee] = {count: 0}
}

this at least doesn’t yield an error, but my output doesn’t seem to update. So I basically would need to check, if there is a value already existing for that specific key. If so, I need to increment it by 1.

I know I could have a function to check that specific index of the object, read the value, adjust and write it. But that doesn’t seem clean. I’m pretty sure there is an easier way to do so, but I don’t know how.

I also fiddled around with something like:

itemsPerAssignee = {user: assignee, count: 0}

but I got stuck there and I don’t know if my approach was correct.

Also, right now, I have objects with the same key multiple times, which might be part of the problem. Can someone point me in the right direction?

var itemsPerAssignee = {};
var users = ["[email protected], [email protected]", "[email protected]"];

for(u in users) {
    itemsPerAssignee[u] = {count: 0};
}

for(i in itemsPerAssignee) {
    console.log(itemsPerAssignee[i].count);
}

web notification using firebase on allow notification getting error of import script

code using angular 13
firebase version “firebase”: “^10.2.0”,
“@angular/fire”: “^17.0.1”,
firebase-messaging-sw.js
importScripts(“https://www.gstatic.com/firebasejs/10.2.0/firebase-app.js”);
importScripts(“https://www.gstatic.com/firebasejs/10.2.0/firebase-messaging.js”);
firebase.initilizeApp({
apiKey: “AIzaSyDaLKSCmGU-OSyprlyF0TwLmwy3aFdssz4”,
authDomain: “webpushnotification-3277f.firebaseapp.com”,
projectId: “webpushnotification-3277f”,
storageBucket: “webpushnotification-3277f.appspot.com”,
messagingSenderId: “674274071608”,
appId: “1:674274071608:web:6a12b851a9bfaaf61942cd”
});

const messaging = firebase.messaging();
enter image description here
error:- firebase-messaging-sw.js:1 Uncaught DOMException: Failed to execute ‘importScripts’ on ‘WorkerGlobalScope’: The script at ‘https://www.gstatic.com/firebasejs/10.2.0/firebase-app.js’ failed to load.
at http://localhost:4200/firebase-messaging-sw.js:1:1

trying to get token id from firebase on allow notification

Error: Download manager failed to download from https://api.myapi/api/bulk-export. Status Code = 16, error while post request in Rn-fetch-blob

I would like download file on React-Native app. The problem is not about React-Native, but i don’t know how i can download the xlsx file using post request. when i go to download its show status code 16

const token = await AsyncStorage.getItem('accessToken');
      const {config, fs} = RNFetchBlob;
      let DOCUMENT_DIR = fs?.dirs?.DownloadDir;

      let date = new Date();
      let options = {
        fileCache: true,
        trusty: true,
        addAndroidDownloads: {
          useDownloadManager: true,
          notification: true,
          title: 'Downloading....',
          path:
            DOCUMENT_DIR +
            '/Download' +
            Math.floor(date.getTime() + date.getSeconds() / 2) +
            '.xlsx',
          description: 'Downloading..',
        },
      };

      const response = await config(options).fetch(
        'POST',
        `${BASE_URL}/auth/bulk-export`,
        {
          'Content-Type': 'application/octet-stream',
          Authorization: `Bearer ${token}`,
        },
        JSON.stringify(myData),
      );

      const status = response.info().status;

      if (status === 200) {
        Toast.show({
          title: 'Success',
          description: 'File downloaded successfully',
          bgColor: COLORS.secondary,
        });
      } else {
        console.error('Failed to download file. Status:', status);
      }
    } catch (error) {
      console.error('Error during file download:', error);
    }

i am using Rn-fetch-bolb to download using post request but error status code 16,
Anyone have already download file using post request or any one have solution ?

Thank you guys !

Changing the default browser zoom-center

It seems to me that the default zoom-center of modern browsers running on a pc is the top center of the browser’s rendering window.
Is there a way to change this via javascript?
Just like in mobile devices it’s possible to arbitrarily set the zoom-center with pinch-zooming.

Facing a php server side error on saving in a project [closed]

i have designed system whereby i use a form to input the service details into the service table and i have deployed the system on a live server after testing it on a localhost server and everything was working fine. but now once on the live server it is refusing to save the service details, giving an error occured error. i will give the server side and client side code and the database as they are and someone please help me. the following is the server side code for saving the service.

<?php
if(isset($_GET['id']) && $_GET['id'] > 0){
    $qry = $conn->query("SELECT * from `service` where id = '{$_GET['id']}' ");
    if($qry->num_rows > 0){
        foreach($qry->fetch_assoc() as $k => $v){
            $$k=stripslashes($v);
        }
    }
}
// Fetch vehicles data
$vehicles_query = $conn->query("SELECT license_plate, vehicle_code FROM vehicles");
$vehicles = [];
if($vehicles_query){
    while($row = $vehicles_query->fetch_assoc()){
        $vehicles[] = $row;
    }l
}

$issues_query = $conn->query("SELECT id, description FROM issues WHERE status = 1");
$issues = [];
if($issues_query){
    while($row = $issues_query->fetch_assoc()){
        $issues[] = $row;
    }
}
?>
<div class="card card-outline card-info">
    <div class="card-header">
        <h3 class="card-title"><?php echo isset($id) ? "Update ": "Create New " ?> Service</h3>
    </div>
    <div class="card-body">
        <form action="" id="service-form">
            <input type="hidden" name ="id" value="<?php echo isset($id) ? $id : '' ?>">
            
            <div class="form-group">
                <label for="date_created" class="control-label">Date Created</label>
                <input name="date_created" id="date_created" type="text" class="form-control rounded-0" value="<?php echo isset($date_created) ? $date_created : date('Y-m-d H:i:s'); ?>" readonly>
            </div>
                         <div class="form-group">
    <label for="license_plate_dropdown" class="control-label">License Plate</label>
    <select name="license_plate_dropdown" id="license_plate_dropdown" class="form-control rounded-0" required>
        <option value="">Select a License Plate</option>
        <?php foreach($vehicles as $vehicle): ?>
            <option value="<?php echo $vehicle['license_plate']; ?>" 
                data-vehicle-code="<?php echo $vehicle['vehicle_code']; ?>"
                <?php echo isset($license_plate) && $license_plate == $vehicle['license_plate'] ? 'selected' : ''; ?>>
                <?php echo $vehicle['license_plate']; ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>


            <div class="form-group">
                <label for="vehicle_code" class="control-label">Vehicle Code</label>
                <input name="vehicle_code" id="vehicle_code" type="text" class="form-control rounded-0" value="<?php echo isset($vehicle_code) ? $vehicle_code : ''; ?>">
            </div>
            <div class="form-group">
                <label for="last_odometer" class="control-label">Mileage(km)</label>
                <input name="last_odometer" id="last_odometer" type="text" class="form-control rounded-0" value="<?php echo isset($last_odometer) ? $last_odometer : ''; ?>" >
            </div>
            <div class="form-group">
                <label for="total_costs" class="control-label">Total Cost(MZN)</label>
                <input name="total_costs" id="total_costs" type="currency" class="form-control rounded-0" value="<?php echo isset($total_costs) ? $total_costs : ''; ?>" >
            </div>
           <div class="form-group">
                <label for="service_prov" class="control-label">Work Done</label>
                <textarea name="service_prov" id="" cols="30" rows="2" class="form-control form no-resize summernote"><?php echo isset($service_prov) ? html_entity_decode(stripslashes($service_prov)) : ''; ?></textarea>
            </div>
            <div class="form-group">
                <label for="contact" class="control-label">Comments</label>
                <input name="contact" id="contact" type="text" class="form-control rounded-0" value="<?php echo isset($contact) ? $contact : ''; ?>" >
             </div>   
            <div class="form-group">
                <label for="mileage" class="control-label">Job Number</label>
                <input name="mileage" id="mileage" type="text" class="form-control rounded-0" value="<?php echo isset($mileage) ? $mileage : ''; ?>" >
            </div>
            <div class="form-group">
                <label for="next_date" class="control-label">Next Date</label>
                <input name="next_date" id="next_date" type="date" class="form-control rounded-0" value="<?php echo isset($next_date) ? $next_date : ''; ?>" required>
            </div>

<select name="issue_id" id="issue_id" class="form-control rounded-0" required>
    <option value="" selected disabled>Select an Issue</option>
    <option value="null">None</option>
    <?php foreach($issues as $issue): ?>
        <option value="<?php echo $issue['id']; ?>">
            <?php echo $issue['description']; ?>
        </option>
    <?php endforeach; ?>
</select>


          
<label for="service_classes">Select Service Class:</label>
<select id="service_classes" name="service_classes[]" multiple>

    <option value="A">Class A</option>
    <option value="B">Class B</option>
    <option value="C">Class C</option>
    <option value="D">Class D</option>
</select>


<div id="checklistContainer">
    
</div>
            <div class="form-group">
                <label for="checked_by" class="control-label">Checked By</label>
                <input name="checked_by" id="checked_by" type="text" class="form-control rounded-0" value="<?php echo isset($checked_by) ? $checked_by : ''; ?>" required>
             </div>   
            <div class="form-group">
                <label for="driver_name" class="control-label">Driver's Name</label>
                <input name="driver_name" id="driver_name" type="text" class="form-control rounded-0" value="<?php echo isset($driver_name) ? $driver_name : ''; ?>" >
            </div>
           <div class="form-group">
                <label for="report" class="control-label">Description Of Issue</label>
                <textarea name="report" id="" cols="30" rows="2" class="form-control form no-resize summernote"><?php echo isset($report) ? html_entity_decode(stripslashes($report)) : ''; ?></textarea>
            </div>
            <div class="form-group">
    <label for="mechanic_name" class="control-label">Mechanic's Name</label>
    <select name="mechanic_name" id="mechanic_name" class="form-control rounded-0">
        <option value="">-- Select Mechanic --</option>
        <?php
        $mechanics = $conn->query("SELECT name FROM mechanics_list ORDER BY name ASC");
        while ($mechanic = $mechanics->fetch_assoc()) {
            $selected = (isset($mechanic_name) && $mechanic_name == $mechanic['name']) ? 'selected' : '';
            echo "<option value='" . $mechanic['name'] . "' $selected>" . $mechanic['name'] . "</option>";
        }
        ?>
    </select>
</div>
          
            <div class="form-group">
                <label for="status" class="control-label">Status</label>
                <select name="status" id="status" class="custom-select selevt">
                <option value="1" <?php echo isset($status) && $status == 1 ? 'selected' : '' ?>>Active</option>
                <option value="0" <?php echo isset($status) && $status == 0 ? 'selected' : '' ?>>In-Progress</option>
                </select>
            </div>
        </form>
    </div>
    <div class="card-footer">
        <button class="btn btn-flat btn-primary" form="service-form">Save</button>
        <a class="btn btn-flat btn-default" href="?page=service">Cancel</a>
    </div>
</div>

<script>
   
$(document).ready(function(){

    $('#license_plate_dropdown').change(function(){
        var vehicleCode = $('option:selected', this).data('vehicle-code');
        $('#vehicle_code').val(vehicleCode);
    });

    $('#service_classes').change(function() {
        updateChecklist();
    });

    $('#service-form').submit(function(e){
        var dateCreated = new Date($('#date_created').val());
        var nextDate = new Date($('#next_date').val());
        if(nextDate <= dateCreated) {
            alert('Next Date must be after the Date Created');
            e.preventDefault();
            return false;
        }
        e.preventDefault();
        var _this = $(this)
        $('.err-msg').remove();
        start_loader();
        $.ajax({
            url:_base_url_+"classes/Master.php?f=save_service",
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            dataType: 'json',
            error:err=>{
                console.log(err)
                alert_toast("An error occurred",'error');
                end_loader();
            },
            success:function(resp){
                if(typeof resp =='object' && resp.status == 'success'){
                    location.href = "./?page=service";
                }else if(resp.status == 'failed' && !!resp.msg){
                    var el = $('<div>')
                        el.addClass("alert alert-danger err-msg").text(resp.msg)
                        _this.prepend(el)
                        el.show('slow')
                        $("html, body").animate({ scrollTop: _this.closest('.card').offset().top }, "fast");
                        end_loader()
                }else{
                    alert_toast("An error occurred",'error');
                    end_loader();
                    console.log(resp)
                }
            }
        })
    });


    function populateSavedClasses() {
        let serviceId = $('#service_id').val();  
        $.ajax({
            url: _base_url_ + "classes/Master.php?f=fetch_saved_checklist&id=" + serviceId,
            method: 'GET',
            dataType: 'json',
            success: function(savedClasses) {
                // Pre-select the saved classes in the dropdown
                $('#service_classes').val(savedClasses);
                updateChecklist(savedClasses);
            },
            error: function(err) {
                console.error("Error fetching saved classes/checklist items: ", err);
            }
        });
    }

    function updateChecklist(savedClasses = []) {
        let selectedClasses = $('#service_classes').val().join(',');
        $.ajax({
            url: _base_url_ + "classes/Master.php?f=fetch_checklist&classes=" + selectedClasses,
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                let checklistHtml = "";
                data.forEach(item => {
                    let checkedAttr = (savedClasses.includes(item.id.toString())) ? 'checked' : ''; 
                    checklistHtml += `<input type="checkbox" name="checklist_items[]" value="${item.id}" ${checkedAttr}> ${item.point_description}<br>`;
                });
                $('#checklistContainer').html(checklistHtml);
            },
            error: function(err) {
                console.error("Error fetching checklist: ", err);
            }
        });
    }

   
    if($('#service_id').val()) {
        populateSavedClasses();
    }

    
    $('.summernote').summernote({
        height: 200,
        toolbar: [
            [ 'style', [ 'style' ] ],
            [ 'font', [ 'bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear'] ],
            [ 'fontname', [ 'fontname' ] ],
            [ 'fontsize', [ 'fontsize' ] ],
            [ 'color', [ 'color' ] ],
            [ 'para', [ 'ol', 'ul', 'paragraph', 'height' ] ],
            [ 'table', [ 'table' ] ],
            [ 'view', [ 'undo', 'redo', 'fullscreen', 'codeview', 'help' ] ]
        ]
    });
});



</script>





function save_service(){
    extract($_POST);

    // Convert 'null' string to actual null for issue_id
    $issue_id = ($issue_id === 'null') ? null : $issue_id;

    // Correctly assign license_plate from the license_plate_dropdown
    if (isset($license_plate_dropdown)) {
        $license_plate = $license_plate_dropdown;
    }

    $data = "";
    foreach ($_POST as $k => $v) {
        // Exclude 'id' and 'license_plate_dropdown' from the direct database insertion
        if (!in_array($k, array('id', 'license_plate_dropdown', 'issue_id'))) {
            // Escape string values only
            if (is_string($v)) {
                if (!empty($data)) $data .= ",";
                $data .= " `{$k}`='" . $this->conn->real_escape_string($v) . "' ";
            }
        }
    }

    // Include license_plate into the data to be saved
    if (isset($license_plate)) {
        if (!empty($data)) $data .= ",";
        $data .= " `license_plate`='" . $this->conn->real_escape_string($license_plate) . "' "; // Escape value
    }

    // Include issue_id into the data to be saved, if provided
    if (!empty($issue_id)) {
        if (!empty($data)) $data .= ",";
        $data .= " `issue_id`='{$issue_id}' ";
    }

    // Check for conflicts using the id
    $check = (!empty($id)) ? $this->conn->query("SELECT * FROM `service` where `id` = '{$id}' and id != {$id} ")->num_rows : 0;

    if ($this->capture_err()) {
        return $this->capture_err();
    }

    if ($check > 0) {
        $resp['status'] = 'failed';
        $resp['msg'] = "Service record already exists.";
        return json_encode($resp);
        exit;
    }

    if (empty($id)) {
        $sql = "INSERT INTO `service` SET {$data} ";
        $save = $this->conn->query($sql);
    } else {
        $sql = "UPDATE `service` SET {$data} WHERE id = '{$id}' ";
        $save = $this->conn->query($sql);
    }

    if ($save) {
        $resp['status'] = 'success';
        if (empty($id)) {
            $this->settings->set_flashdata('success', "New service record successfully saved.");
        } else {
            $this->settings->set_flashdata('success', "Service record successfully updated.");
        }
    } else {
        $resp['status'] = 'failed';
        $resp['err'] = $this->conn->error . "[{$sql}]";
    }

    return json_encode($resp);
}

so the first code block is the form input and the second is the server side save function

i tried changing the column names of the database table, tried recreating the table adding the issue_id as the foreign key from the issues table but still didn’t work

OpenLayers not rendering map TMS tiles on print in Angular

In my Angular app i want to create pdf document of map image and polylines on it. But map tiles are not getting rendered on canvas when i try to create a pdf document from html element.

My code is like this.
First i create a map my inserting tiles into html element (Standard way) and map works great.

<div id="map" (contextmenu)="openContextMenu($event); false"></div>

And then on a button click i call a generatePdf function

<p-button type="button" class="btn" icon="fas fa-print" (click)="generatePdf('test')" label="Print"></p-button>


    async generatePdf(title: string): Promise<void> {
        const docDefinition: TDocumentDefinitions = {
            content: [
                { text: title, style: 'header' },
                { text: 'Additional Information', style: 'subheader' },
                {
                    image: await this.getImageMapUrl(),
                    width: 500,
                },
            ],
            styles: {
                header: { fontSize: 18, bold: true },
                subheader: { fontSize: 14, bold: true, margin: [0, 10, 0, 5] },
            },
        };
        pdfMake.createPdf(docDefinition).open();
    }

    public async getImageMapUrl(): Promise<any> {
        this.map.getView().setCenter(fromLonLat([15, 46]))
        const element = document.getElementById('map');

        if (!element) {
            throw new Error(`Element with id not found.`);
        }
        const exportOptions: Partial<Options> = {
            useCORS: true,
            imageTimeout: 100
        };
        const canvas = await html2canvas(element, exportOptions);
        return canvas.toDataURL('image/png');
    }

The file that gets generated has polyline layers printed but not map tiles.
I tried with jsPDF, like in the docs, but its still not rendering tiles/canvas. Any ideas?
enter image description here

Implementing Conditional TypeScript Props Based on the Values of Another Prop

I have an interface FilterActionsProps in TypeScript that defines props for a component. Currently, it supports actions as an array of strings ([‘export’, ‘reset’, ‘submit’]). However, I need more accurate TypeScript IntelliSense support.

interface FilterActionsProps {
   onExport?: () => Promise<void>;
   onReset?: () => void;
   actions?: ('export' | 'reset' | 'submit')[];

}

Desired Behavior:

I want to enhance the type support so that when certain actions are specified in the array, only the corresponding props are suggested in TypeScript IntelliSense.

If actions include only ‘submit’, then only onSubmit prop should be suggested.

If actions include both ‘submit’ and ‘reset’, then both onSubmit and onReset props should be suggested.

If actions include both ‘submit’ and ‘export’, then both onSubmit and onExport props should be suggested.

If actions include all three ‘submit’, ‘reset’, and ‘export’, then all three onSubmit, onReset, and onExport props should be suggested.

Example Usage:

// Only onSubmit prop should be suggested
<Component actions={['submit']} />

// Both onSubmit and onReset props should be suggested
<Component actions={['submit', 'reset']} onReset={() => {}} />

// Both onSubmit and onExport props should be suggested
<Component actions={['submit', 'export']} onExport={() => {}} />

// All three onSubmit, onReset, and onExport props should be suggested
<Component actions={['submit', 'reset', 'export']} onReset={() => {}} onExport={() => {}} />

React not rendering component when changing routes

I have a page with products. My problem is that when I try to click on a product, the url is changing, but nothing renders on the screen. It still shows the component where all the products are rendered.

I tried couple of different things, but nothing seemed to work

<Route path="store" element={<Store />}>
  <Route path="protein" element={<Products />} />
  <Route path="protein/*" element={<SingleProduct />} />
</Route>

I also tried with:

<Route path="store" element={<Store />}>
  <Route path="protein" element={<Products />}>
    <Route path="*" element={<SingleProduct />} />
  </Route>
</Route>

Also with:

<Route path="/store/protein/*" element={<SingleProduct />} />

So that it is not a child route.

But that also didn’t work. Any ideas what I’m doing wrong?

Edit: That is my Store component :

import React from "react";
import SidePanel from "../components/storeComponents/SidePanel";
import Products from "../components/storeComponents/Products";
import "./Store.css";

const Store = () => {
  return (
    <div className="store-page">
      <SidePanel />
      <Products />
    </div>
  );
};

export default Store;