Skip to main content

Posts

Showing posts from June, 2021

How to clear Selectize value on Submit? [Cannot read proprety 'clear' of undefined]

I have to clear selectize input after submit, but it gives me this error message: Cannot read property 'clear' of undefined This is what I have so far: GET $_POST value, nothing is wrong with this. <?php $autoclear = "0"; if (isset($_POST['autoClear']))$autoclear = $_POST['autoClear']; ?> My HTML Form, also nothing wrong with this. <form method="post" action=""> <input type="checkbox" id="autoClear" name="autoClear" value="1" <?php if ($autoclear == '1') echo 'checked'; ?>> <select id="client" name="client" class="client selectize" > <option> ... ... </option> </select> <!-- OTHER INPUTS, IRRELEVANT --> <input type="submit" name="submitBtn" id="submitBtn" class="submitBtn btn-info" value="Submit...

React testing library snapshot testing cannot read store property

I'm trying to create a snapshot test for a component, however, my store keeps coming up as undefined and I cannot figure out why. What do I need to pass into my store to make this correct? I've done snapshot testing with other components that don't require mapStateToProps or withRouter with no issue before. WorkflowForm.jsx const mapStateToProps = (state, ownProps) => { return { ...ownProps, userID: state.data.userID, userObj: state.ui.userObj }; }; export default withRouter( connect(mapStateToProps, null)(WorkflowForm) ); WorkflowForm.test.jsx import React from 'react'; import renderer from 'react-test-renderer'; import { Provider } from 'react-redux'; import { BrowserRouter } from "react-router-dom"; import WorkflowForm from "../WorkflowForm"; import { cleanup } from '@testing-library/react'; import configureMockStore from 'redux-mock-store'; afterEach(cleanup); const mockStore = conf...

Reconstruct a deep nested array of object removing an unwanted object

I can't figure out how to remove and object inside a deep nest array of object pointing it by it's id value. Here is my code using reduce. I wanted to recreate the array on each itteration by its a big mess (and it's only going through the index 0). I would like to remove this whole piece by pointing the node id 35993. If the node get a children this would remove the children as well. const array = [ { node: { level: 0, id: 71, type: "block", style: { backgroundColor: "#548444", }, }, children: [ { node: { id: 85, type: "block", style: { backgroundColor: "#548444", fontSize: "19px", }, }, children: [ { node: { id: 955, type: "column", style: { backgroundColor: "#eee", ...

How to make addEventListener stream continuously on button submit

I am trying to stream a list of json objects from my servers endpoint to my frontend using javascript and html. Below is my code. Currently addEventListener works fine when I click my form button (HTML also added below for reference). Heres my problem: The list of objects my server endpoint returns is a single list which is continuously having objects appended to the list. So I want my front end to refresh automatically every second to show the latest version. And so I am finding a way for my addEventListener to rerun the function each time after clearing the HTML it is pushing. Currently, I have to click on my button to achieve that and the previously pushed HTML is not getting cleared either. So each time I click on the button, I am getting all the existing HTML displayed as many times as I have clicked the button (old versions) plus the latest version of my endpoint data. The solution I want to achieve is to be able to click on my start stream button once, and have the function ru...

Some questions about a H5P-tutorial

this is my first post on stackoverflow.com, I try to follow the posting guide lines. Sorry, that my english is not as good as I would like. 1. Summarize the Problem I'am trying to get started with H5P and javascript to create simple applications for my pupils in Moodle. I started with this tutorial . I managed to reproduce the code und create the greetingcard-H5P-application. It worked in my Moodle. I tried to understand the whole code in the file greetingcard.js, but I still have some problems. My goal is to understand the code, so that I can get a better understanding, how H5P works and create my own small H5P-applications. 2. Describe, what you have tried I did a few days of internet research to understand some syntax issues, that are unfamiliar for me. I also tried to make some adjustments on the code, to figure out, how it works. For example I tried to add a second text field. So far, I got a vague understanding how it works. The function in the file 'javascript.js...

Why I get error "Cannot read property 'state' of undefied in react-native? [duplicate]

I very need your help. I am trying to make a JSON object users in my state properties to check how my authentification works. But when I tried to get access I had received the error "Cannot read property 'state' of undefied" and error arrow pointed on this part of code const { users, textInputEmail, textInputPassword } = this.state . Also, when I tried to check users it also showed 'undefined'. What have I done wrong? import React, { Component } from 'react' import { View, TextInput } from 'react-native' import { MyButton, ErrorMessage } from '../uikit' import { FormStyle, InputStyle } from '../constants/styles' import { SIGN_IN, SUCCESS } from '../routes' export class LogIn extends Component { state = { users: { user: [ { name: 'john1303@ukr.net', password: '12345678' }, { ...

how to download a file from laravel

I'm trying to download files I have this method in my controller function DownloadLetter(Request $request) { $userId = Auth::id(); $permission = DB::table("user_permissions")->where('user_id', $userId)->first(); if ($permission->TL_E) { $id = $request->query('id'); $LettreName = DB::table('jobs')->where('id', $id)->first()->Lettre; if ($LettreName) { return Storage::download("public/Lettres/" . $LettreName); } } } as you can see I'm returning Storage::download("public/Lettres/" . $LettreName); and then in my javascript I have function DownloadLetter(id){ axios.get("/api/DownloadLetter?id="+id) .then(function (response) { console.log(response); }) } when I log the response I get the file as JSON, (It doesn't get downloaded) but when I change the javascript code to this it works var link = do...

"Uncaught (in promise) Error: The 'activeTab' permission is not in effect because this extension has not been in invoked." in Chrome Extension

I have the <all_urls> host permission and the activeTab permission but this error appears on chrome://extensions/ . Here is my manifest (with non-important detail removed): { "action": { "default_icon": {...}, "default_popup": "...", "default_title": "..." }, "author": "...", "background": { "service_worker": "./some-js-1.js" }, "content_scripts": [{ "matches": ["<all_urls>"], "js": ["./some-js-2.js"] }], "description": "...", "host_permissions": [ "<all_urls>" ], "icons": {...}, "manifest_version": 3, "name": "...", "options_page": "...", "permissions": [ "activeTab",...

Events on Google maps inner polygon

I am trying to create an utility where user will be able to create inner hole in a polgon. The piece of code is working fine. But I am not able to capture the events while streching or moving the vertices of inner ring. How to produce: Create a polygon using handler. Draw another polgon inside the polygon. You will see it as hole. Further select the polygon and strech the point. You will get the alert while streching the outer polygon. I want the same behaviour for the inner polygon (Mean to say trigger event on inner polygon too). What is wrong I am doing here. Please help. Piece of code below: var selectedShape; ///Function for selecting a shape function setSelection(shape) { clearSelection(); selectedShape = shape; shape.setEditable(true); } //Clear the selection of a polygon. function clearSelection() { if (selectedShape) { selectedShape.setEditable(false); selectedShape = null; } } //Check if Polygon is inside Polygon**** function isPolygonInsidePolygon(i...

Is it possible to edit Sequelize default log?

When ever a query is executing across a database sequelize is logging to the console like below Executing (default): SELECT "user_id", "user_email", "id", "email", "start_date", "end_date" FROM "users"; Is there a way that i can edit the word default to my dbname ? Like Executing (dbname): SELECT "user_id", "user_email", "id", "email", "start_date", "end_date" FROM "users"; I have multiple db connections running at same time and i want to see the dbname in the log. Thank you Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Convert ZPL (Base64) in image (PNG)

I need to convert a ZPL file into an image. I already use the labelary web service, but I need a solution that is less dependent on an external application. I am proceeding in the following way. I'm getting the base64 encoded part: eJzs281u4zYQAGAKLMCewmsPhfgaPWipPtIeVUC1GPiQYx6hr9FDgdL....rest of the code (Z64 encoded), which would be the image of the ZPL file, and I'm trying to convert this to a png image. I tried using the code below, but I get this error: Error: Could not find MIME for Buffer const fs = require('fs'); var base64Img = require('base64-img'); var Jimp = require('jimp'); try{ var data = fs.readFileSync('./test.zpl', 'base64') } catch (err) { console.log(err); } var buffer = Buffer.from(data, 'base64'); Jimp.read(buffer).then(res => { return res .quality(50) .rotate(90) .resize(250,250) .writeAsync('out.png'); }).catch(err => { console.log(err); }); I tried using ...

How to make select2 filter multiple matches (php/js)

Fiddle: https://jsfiddle.net/1ahygf6n/ using select2 and matcher i've built some filters (see filters button), i wanna combine multiple filters together. Example: Seperate filters work fine: Shows all items that meet my 'is:autorifle' filter: is:autorifle Shows all items that meet the 'energy:void' filter: energy:void what i wanna achieve is combined filters, so i want to enter is:autorifle energy:void And make that show me all items that meet both autorifle and void filters. Dropdown starts here: https://github.com/darkelement1987/rollfinder/blob/main/index.php#L53 JS starts here: https://github.com/darkelement1987/rollfinder/blob/main/index.php#L414 Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

JSPDF blob url react-native-webview

There is any way to show or open on browser the created PDF from JSPDF api? I have an application on react native using webview and it bugs when i tried to open/download the file. Using minor configurations on android for external download didnt worked... I am new to React native and cant find any help... Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to manage the open widow code in the single html file using javascript [closed]

I am trying to include the open new window page related functionalities in the parent Html page. I events how to call from child to parent pages. The sample below code I am trying to do achieve that but it is not able to come output as expected. What can I do to resolve this? <!DOCTYPE html> <html> <body> <p>Click the button to write some text in the new window and the source (parent) window.</p> <button onclick="myFunction1()">Try it</button> <script> function myFunction1() { var myWindow = window.open("", "myWindow", "width=200,height=100"); myWindow.document.write("<html oncontextmenu='return false;'><head> <meta name='viewport' content='width=device-width, initial-scale=1'> <style> </style></head><body onload='closeWindow()' onresize='myFunction()'><div style='width:1020px;hei...

Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\Website\classes\connect.php on line 29 [duplicate]

<?php class Database { private $host = "localhost"; private $username = "root"; private $password = "root"; private $db = "site_db"; function connect() { $connection = mysqli_connect($this->host,$this->username,$this->password,$this->db); return $connection; } function read($query) { $conn = $this->connect(); $result = mysqli_query($conn,$query); if(!$result) { return false; } else ( $data = false; while($row = mysqli_fetch_assoc($result)) { $data[] = $row; } return $data; ) } ...

How to make select2 filter multiple matches (php/js)

Fiddle: https://jsfiddle.net/1ahygf6n/ using select2 and matcher i've built some filters (see filters button), i wanna combine multiple filters together. Example: Seperate filters work fine: Shows all items that meet my 'is:autorifle' filter: is:autorifle Shows all items that meet the 'energy:void' filter: energy:void what i wanna achieve is combined filters, so i want to enter is:autorifle energy:void And make that show me all items that meet both autorifle and void filters. Dropdown starts here: https://github.com/darkelement1987/rollfinder/blob/main/index.php#L53 JS starts here: https://github.com/darkelement1987/rollfinder/blob/main/index.php#L414 source https://stackoverflow.com/questions/68200214/how-to-make-select2-filter-multiple-matches-php-js

websocket with php and apache reverse proxy

Currently running a socket web server by supervisor on my server. Apache is also active on the same server and using the following apache directives to reverse proxy web-socket which make it possible to access socket server through web (using domain): RewriteCond %{HTTP:Upgrade} =websocket [NC] RewriteRule .* ws://127.0.0.1:6001%{REQUEST_URI} [P,L] Some time ago, the connection of the web socket suddenly became problematic. when I try to connect to the socket server The connection starts and the upgrade headers are sent to the user's browser , but after that no message is sent to the user by the web-socket server. This only happens when communicating via Apache, and connecting directly to the ip / port of socket server (even throw web with ip and port of server) does not cause this problem and everything works fine. source https://stackoverflow.com/questions/68200145/websocket-with-php-and-apache-reverse-proxy

Fix POST https://localhost/someFile.php 405 error

I have a https server running on my windows 10 system for developing purpose... And it really is fine comparing to a real server for developing but I faced an annoying issue which I don't know if there is a solution for it at all; I have a function called Preload like this: function Preloading() { $.ajax({ type: 'POST', url: 'https://localhost/preload.php', data: {id: "testdata", directories: directories}, dataType: 'json', cache: false, success: function(result) { if(preloadFirstTime === false) return; preload(result); preloadFirstTime = false; }, }); } As you see I want to hit this URL to run the ajax call https://localhost/preload.php which I know is correct URL of the file because I can see other files in the same URL. But each time I get this error: POST https://localhost/preload.php 405 Here is the screen capture if I want to run the php f...

how to display three lines on chart

I create a chart using canvasjs. Values display in chart is from mysql database. All working but the problem is, it showing just 1 line on chart (sensors_pres) from table SensorData on chart not all three sensors_pres, sensors_temperature_data and sensors_humidity. Other problem is on range slider is not showing hour from 0 to 24, test it. Click in left-up on button all and in right-up you will see the number -1 to 96. How can i solve? I opened data.php file with browser and all values working correct. Here is my html&javascript code <!DOCTYPE HTML> <html> <head> <script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.stock.min.js"></script> <script type="text/javascript"> window.onload = function () { $.getJSON("data.php", function (res...

Dexie: how to query by date?

I'm trying to build a "logs" table (my goals its to know how much time the app is being used), so I created a function that detects if the user is inactive after a certain period of time. The table is like this: dblogs.version(1).stores({ aLogs: "++id, story_id, user_id, session_start, session_end, words_written" }); So when the user is active I create a new record on aLogs, example: 0, 1 , 19 , 2021/06/30 10:15:10 the user 19 started typing at 2021/06/30 10:15:10 (this goes in session_start) then if the user goes inactive I add the current datetime to session_end Example: 0, 1 , 19 , 2021/06/30 10:15:10, 2021/06/30 12:15:48 so basically the user estimated time is the difference between those 2 dates (in this case its 2h 0m 38s) my goal is to have several of these logs, then run a loop on it and story the amount of seconds the user spent "today" how do I query this on Dexie? I have tried await dblogs.aLogs.get({session_start : "2...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Can you review my website "Email Contact Form" that uses PHP and - g-recaptcha

Data entered via Email Contact Form using g-recaptcha v.3 to create hidden token which is passed to form.php is not being displayed within emails received from local server. Can you help? HTML Contact Form <!-- Contact Section --> <div class="w3-container w3-padding-32 w3-card w3-light-grey " id="contact"> <h3 class="w3-border-bottom w3-border-light-grey w3-padding-16">Contact</h3><hr> <p>Lets get in touch and talk about your next project.</p> <form action="form.php " method="post" target="_blank" > <input class="w3-input w3-border w3-text-red" type="text" placeholder="Enter Your First Name: ex. Mark (with no spaces, punctuations or symbols)" name="fname" maxlength="32" pattern="[A-Za-z]{1,32}" required...

Typescript index error: looping through keys of typed object

I have an interface that's created as an extension of a couple of other interfaces from an external library: interface LabeledProps extends TextProps, ComponentProps { id: string; count: number; ... } In another place in the code, I have an object of type LabeledProps and I would like to loop through all its properties: function myFunc(props: LabeledProps):void { for (let key in props) { const val = props[key]; // <-- ERROR IS HERE // do other stuff } } The line const val = props[key] throws a typescript error (though the compiled code actually runs just fine): Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LabeledProps'. What is the right way (or ways) to accomplish this? Thanks! ( Note : I know I could add [key: string]: any to the interface definition and that will remove the error message, but I would like an actual fix, not just a hiding-the-erro...

How to reuse function attribute?

I want to do something like the following: function StatusBox() { this.connectionStatus = $("#connectionStatus"); } StatusBox.nosupport = function(type) { StatusBox.connectionStatus.html('<span style="color: red;">' + NO_SUPPORT + '</span>'); }; StatusBox.error = function(type) { StatusBox.connectionStatus.html('<span style="color: red;">' + ERROR + '</span>'); }; But I get Uncaught TypeError: Cannot read property 'html' of undefined How do I reuse $("#connectionStatus") in the child functions? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

async function doesnt wait for await javascript [closed]

var res; const fetchques = async () => { await fetch('url') .then(function(response) { response.json().then(function(r) { res = r["results"] console.log(res) //let line 1 }) }).catch((err) => { console.log(err) }) } const getques = async () => { await fetchques() console.log(res) // let line 2 } //getques() is called after body loads, ie <body onload="getques()"> In my output, it is printing line 2 first then line 1. Isnt await supposed to wait for the called function to finish? What am I doing wrong? I do not want to use promises yet. I even tried await fetchques().then(function(el){console.log(res)}) for getques(), but in vain. Not even .then() waited. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to use Firefox's inbuilt json viewer in a web application that fetches content from a rest API and renders it below a search bar?

I have a simple search bar where I can search for text and get in return a json array as output from the backend server. The request is a simple get request. Now, I can directly query from the url parameters and see the whole json natively rendered by Firefox, but I really want to have a nice search box. I was wondering if it is possible to somehow have ALL the inbuilt functionality of Firefox's native json viewer (like filtering) as part of the web application itself below the search bar? I tried to search what js library Firefox uses to achieve this, but Google did not help at all. All I get are a bunch of extensions, which I do not want. Right now this is as far as I got - <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </h...

JQuery .each function not finding dynamically created table row

I'm dynamically creating a table row with several cells and then prepending it to a table. That all works fine. However, I have a handler that I call when I want to edit the contents of the row. That works too but when but when I use the .each iterator: $("#myTable > tbody > tr").each(function () {...} I get back all the rows EXCEPT the row that was dynamically inserted. Any ideas how to get the dynamically inserted to show up using the JQuery .each function? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Adding to a nested array in angular

I have a data object model like the following: export class JournalEntries { id?: number; year?: string; month: string; link?: string; months?: any; } A sample data would be: "journalentries": [ { "id": "2000001", "year": "2021", "months": [ { "year": "2021", "month": "January", "link": "Jan_Feb_2021" }, { "year": "2021", "month": "February", "link": "Jan_Feb_2021" }, ... { "year": "2021", "month": "December", "link": "" } ] }, { "id": "2000002", "year": "2020", "months": [ {...

Typescript convert plain string to Map

I have this string (called stats): active_total: 1087 cumulative: 1 trace_total: 10 which is not even in JSON format. This is the solution that I am trying: let keyValuePairs = stats .split(/\s*\n\s*/) //split with optional spaces around the comma .map(chunk => chunk.split(": ")); //split key=value const map = new Map(keyValuePairs); console.log(map.get("sessions_active_total")); console.log(map.get("cumulative")); But it is throwing compilation error at this line: const map = new Map(keyValuePairs); Error message: error TS2769: No overload matches this call. Overload 1 of 3, '(iterable: Iterable<readonly [unknown, unknown]>): Map<unknown, unknown>', gave the following error. Argument of type 'string[][]' is not assignable to parameter of type 'Iterable<readonly [unknown, unknown]>'. The types returned by '[Symbol.iterator]().next(...)' are incompatib...

create state with dynamic property

i use react js in my project.in my project i have two lvl menu and when mouse enter event occured sub menu showed and when mouse leave event occured sub menu disappear.my problem is when mouse enter event occure on a li all of sub menues appear.and thats because i have just one state.i don't know how can i create a dynamic state.i have mainMenu array that store all menu and sub menu in that and this is absolutely dynamic.(in my example length of my array is 2 but this can be changed) i have a boolean state (isMenuOpen).when it is true sub menu appear and when its false sub menu disappear.i want when mouse enter event occure on a li just appear submenu that related to that li. this is my App.js import "./index.css"; import './App.css'; import Sub from "./Sub"; import React, {useState} from "react"; export default function App() { const mainMenuArr = [ { id: "1", name: "All Products", ...

Uncaught ReferenceError: jQuery is not defined (Thymeleaf)

Hi so i have a school project due the day after tomorrow and i the only problem i have left is the "jquery not found" error. I've being struggling with it for 5 days now and i don't know how the heck to solve it. I'm using srping boot, thymeleaf, html/css/js and jquery for the first time for this project. The code is supposed to show a dynamic service chart and the user is supposed to fill it (you test the html to see it). Here's my code (i copy pasted it from github: https://github.com/caprica/jquery-orgchart ) : <!DOCTYPE html> <!--suppress ALL --> <html lang="en" xmlns:th="https://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Service Chart</title> <link href="/static/css/jquerysctipttop.css" th:href="@{/css/jquerysctipttop.css}" rel="stylesheet" type="text/css"> <link type=...

Convert Utc to custom timezone using moment

I wrote the the below function to convert a UTC time into custom timezone using momentjs function convert(time, timezone) { time = moment.utc(time, 'h:mm a').tz(timezone); return time } console.log(convert('06:21pm', 'America/New_York')) <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone.min.js" integrity="sha512-jkvef+BAlqJubZdUhcyvaE84uD9XOoLR3e5GGX7YW7y8ywt0rwcGmTQHoxSMRzrJA3+Jh2T8Uy6f8TLU3WQhpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> when I called that function like convert('06:21pm', 'America/New_York') I am get...

How to get this value made by javascript in a PHP-var? [duplicate]

I have this code <?php $test = 16010; ?> <button "onclick="myFunction('<?php echo $test; ?>')" data-toggle="modal" data-target="#myModal">Edit</button> <script> function myFunction(number) { document.getElementById("result").innerHTML = number;</script> <p id='result'></p> This code will show the result: 16010, but I don't know how to put that value in a php var. Please help! Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Toggle specific element when css class is used multiple times

I have developed my own dropdown module, which works fine so far. However, I have the problem that dropdowns that have the same trigger class open when clicked. How can I focus only on the element that was clicked. I also tried to focus the element using $(this).find , but unfortunately this does not work for me. What exactly am I doing wrong? $(document).ready(function(){ $('.trigger-dropdown').on('click', function(){ $('.filter-dropdown-wrapper').toggleClass('filter-dropdown-active'); return false; }); }); $(document).click(function(){ if($('.filter-dropdown-wrapper').hasClass('filter-dropdown-active')) { $('.filter-dropdown-wrapper').toggleClass('filter-dropdown-active'); } }); $('.filter-dropdown-wrapper').click(function(event){ event.stopPropagation(); }); /* Triggers Checkbox Icon for Dropdowns */ $(".dropdown-items").click(function() { $(this)....