Category: javascript
Category Added in a WPeMatico Campaign
getting error in updating apex chart, getting chart is not defined in javascript
Updating the bar chart in apexcharts.js is getting error, the code is given below
Initially a black chart is defined as can later the values to update,
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'assets/plugins/apexchart/apexcharts.min.js' %}"></script>
<script>
$(document).ready(function () {
let bar_graph = {
chart: { height: 350, type: "bar", toolbar: { show: true } },
plotOptions: { bar: { horizontal: true } },
dataLabels: { enabled: true },
series: [],
title: { text: "Ajax Example" },
noData: { text: "No Data.....!" }
};
let barChart = new ApexCharts(document.querySelector("#s-bar"), bar_graph);
barChart.render();
});
</script>
by the above method a plane chart is prepared with no values
In the above script blog only following code is written
# by changing the value in selected date various values are getting from backend by ajax call
$("#selectDate").change(function () {
getDataValues($(this).val());
});
function getDataValues(dateSelected) {
$.ajax({
url: "{% url 'get_report' %}",
method: "GET",
data: { date: dateSelected },
success: function (response) {
bar_head = Object.keys(response.reportData.barData);
bar_values = Object.values(response.reportData.barData);
barChart.updateSeries([
{
series: [{ data: bar_values }],
xaxis: { categories: bar_head }
}
]);
})
}
getting error as barChart is not defined
(index):571 Uncaught ReferenceError: barChart is not defined
at Object.success ((index):571:9)
at c (jquery-3.6.0.min.js:2:28327)
at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072)
at l (jquery-3.6.0.min.js:2:79901)
at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2:82355)
I am new to this methods pls can any one say the solution for this…
Thank You
It’s working diffently in react while using and not using braces in arrow function
this is another geek here. I am learning reactjs now. I found this in my code while I was tring to create a Button element for my app. My idea is to decide background color according to a prop called type. This is similar to a switch case. please go through the code to find problem.
const colors = {
primary: "#0d6efd",
secondary: "#adb5bd",
success: "#198754",
info: "#0dcaf0",
warning: "#ffc107",
danger: "#dc3545",
light: "#f8f9fa",
dark: "#212529",
};
let bg = ((cl) => {
colors[cl] || "#adb5bd";
})("primary");
let bg2 = ((cl) => colors[cl] || "#adb5bd")(type);
console.log(bg, bg2);
In console,
undefined '#adb5bd'
Did I miss something?
How to pass refs from parent component to child component? Without using Typescript?
Also can you mix with ?
I have an App.vue with the property “clicked” that I’m trying to pass to child components.
App.vue
<template>
<NavBar :clicked="clicked"/>
<BackDrop :clicked="clicked"/>
<SideDrawer :clicked="clicked" />
<router-view></router-view>
</template>
<script>
import { ref } from "vue";
import NavBar from "./components/Navbar/NavBar.vue";
import BackDrop from "./components/Backdrop/BackDrop.vue";
import SideDrawer from "./components/Sidedrawer/SideDrawer.vue";
export default {
name: "App",
components: { NavBar, BackDrop, SideDrawer },
setup() {
const clicked = ref(false);
return { clicked };
},
};
</script>
export default App;
so the child components can be rendered conditionally like:
SideDrawer.vue
<template v-if="clicked">
<div class="sidedrawer"></div>
</template>
<script setup>
</script>
Did I pass the “clicked” ref properly in the “App.vue”?
If I did, how do you access them in the child component? I’ve already googled and looked at a bunch of StackOverflow posts but the majority of them seem to use, “defineProps()”, like this code:
const props = defineProps({
msg: String,
user: Object,
});
// Destructuring props
let { name, lastname } = props.user;
</script>
but I’m not using Typescript so this won’t work for me.
What is the “non-typescript” way of passing props? Do you need to use Typescript to pass props?
everything works fine with no error messages but data is not sent to the mysql database
my first problem was I cant connect to my api/post but fixed it by finding the right port and now everything works fine success alert also pops up but my database is still empty
SERVER SIDE/FOLDER
Index.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql2");
const cors = require("cors");
const port = 5000;
const db = mysql.createPool({
user: "root",
password: "root",
database: "finals",
host: "localhost",
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post("/api/post", (req, res) => {
const { firstName, lastName, email, mobile, address, student, message } = req.body;
const sqlInsert = 'INSERT INTO users (fname, lname, email, mobile, address, old_student, reason) VALUES (?,?,?,?,?,?,?)';
db.query(sqlInsert, [firstName, lastName, email, mobile, address, student, message],
(error, results) => {
if (error) {
return res.send(error);
console.log(error);
} else {
return res.send('Form submitted successfully');
}
}
)
})
app.get("/", (req, res) => {
// const sqlInsert = 'INSERT INTO users (fname, lname, email, mobile, address, old_student, reason) VALUES ("haha","haha","haha","haha","haha","haha","haha")';
// db.query(sqlInsert, (error, result) => {
// console.log("error", error);
// console.log("result", result);
// res.send("hello");
// })
})
app.listen(port, () => {
console.log(`Server started on port ${port}`);
})
CLIENT SIDE/FOLDER
App.js
import {BrowserRouter, Routes, Route} from "react-router-dom";
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
import Home from "./pages/Home";
function App() {
return (
<BrowserRouter>
<div className="App">
<ToastContainer position="top-center"/>
<Routes>
<Route exact path="/" element = {<Home />}/>
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
Home.js
import React, {useState, useEffect} from "react";
import {useHistory, useParams, Link} from "react-router-dom";
// import "./Home.css";
import axios from "axios";
import { toast } from "react-toastify";
import styles from "./form.styles.css"
const initialState = {
firstname: "",
lastname: "",
email: "",
mobile: "",
address: "",
student: false,
reason: "",
}
const Home = () => {
const [state, setState] = useState(initialState);
const {firstname, lastname, email, mobile, address, student, reason} = state;
const handleSubmit = (e) => {
e.preventDefault();
if(!firstname || !lastname || !email || !mobile || !address || !reason) {
toast.error("Please fill all required fields!");
} else {
axios
.post("http://localhost:5000/api/post", {
firstname,
lastname,
email,
mobile,
address,
student,
reason
}).then(() => {
setState ({ firstname: "",
lastname: "",
email: "",
mobile: "",
address: "",
student: false,
reason: "", })
toast.success("Information Submitted!")
})
.catch((err) => toast.error(err.response.data));
}
}
const handleInputchange = (e) => {
const {name, value} = e.target;
setState({...state, [name]: value});
}
return(
<body>
<div className="wrapper" >
<div className="registration_form">
<div className="title">
TUP Registration Form
</div>
<form
onSubmit={handleSubmit}>
<div className="form_wrap">
<div className="input_grp">
<div className="input_wrap">
<label htmlFor="firstname">First Name</label>
<input
type="text"
id="firstname"
name="firstname"
placeholder="Your Name..."
value={firstname}
onChange={handleInputchange}
/>
</div>
<div className="input_wrap">
<label htmlFor="lastname">Last Name</label>
<input
type="text"
id="lastname"
name="lastname"
placeholder="Your Last Name..."
value={lastname}
onChange={handleInputchange}
/>
</div>
</div>
<div className="input_grp">
<div className="input_wrap">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="Your Email..."
value={email}
onChange={handleInputchange}
/>
</div>
<div className="input_wrap">
<label htmlFor="mobile">Mobile Number</label>
<input
type="number"
id="mobile"
name="mobile"
placeholder="Your Mobile Number..."
value={mobile}
onChange={handleInputchange}
/>
</div>
</div>
<div className="input_grp">
<div className="input_wrap">
<label htmlFor="address">Address</label>
<input
type="text"
id="address"
name="address"
placeholder="Your Address..."
value={address}
onChange={handleInputchange}
/>
</div>
<div className="input_wrap">
<br />
<label>
Old Student?:
<input
type="checkbox"
name="student"
checked={student}
onChange={handleInputchange}
className="input_radio"/>
<span>Yes</span>
</label>
</div>
</div>
<div className="input_wrap">
<label htmlFor="reason">Why TUP?</label>
<input
type="text"
id="reason"
name="reason"
placeholder="Your Reason..."
value={reason}
onChange={handleInputchange}
/>
</div>
<div className="input_wrap">
<input type="submit" value="Submit" class="submit_btn"/>
</div>
</div>
</form>
</div>
</div>
</body>
)
}
export default Home
I tried checking details of my mysql but everything seems right. I had problems connecting to api/post but i solved it and i cant find any problems anymore why data is not sending through
Is it possible to show some kind of warning if a prop value doesn’t match a Regex
Let’s say I want id to be a string that also matches a Regex, for example /^[A-Z]_[0-9]{4}$/.
interface MyComponentProps {
id: string
}
const MyComponent = ({ id }: MyComponentProps) => {
...
}
As far as I know Typescript doesn’t allow you to use a Regex as a type. One of the solutions I found was declaring the type as something like
id: `${string}_${number}`, but that’s not specific enough.
Is there any other way I could show some kind of warning if it does not match? Maybe using a linter or some other tool?
Difference between var vs let/const [duplicate]
Case 1:
var name = {
firstName: 'abc',
lastName: 'xyz',
printFullName: function () {
console.log(this.firstName + ' ' + this.lastName);
},
};
name.printFullName();
Case 2:
I changed var to let/const
Output fot Case 1: Uncaught TypeError: name.printFullName is not a function
at app.js:9:6.
Output for Case 2: abc xyz.
I fail to understand why there is difference in output. Can someone explain to me, why we are getting TypeError in Case 1
I cant seem to pass value from controller to view, Laravel 8
I can’t seem to parse data that i got from db on controller to view, i have tried multiple solutions that i got from similiar question but none seem to work.
i simply want to show my employee list on my admin page.
Here’s my login controller
The login function works just fine, its just doenst seem to parse the data i got from db to view
public function postLogin(Request $request){
$list = "";
$list = DB::table('users')->where('role','1')->get();
if(Auth::attempt($request -> only('username','password'))){
if (Auth::user()->role == '0') {
return view('admin',['daftar' => $list]);
}else if (Auth::user()->role == '1') {
return redirect('/EPage');
}
}
return redirect('/');
}
Here’s my admin blade view
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">name</th>
<th scope="col">email</th>
<th scope="col">phone</th>
</tr>
</thead>
<tbody>
<tr>
@foreach($list as $lists)
<th scope="row">1</th>
<td>{{ $lists->name }}</td>
<td>{{ $lists->email }}</td>
<td>{{ $lists->phone }}</td>
@endforeach
</tr>
</tbody>
Please help me understand my mistake, Thank you in advance.
i’m expecting the admin page with show user list with role equals to 1
How to create post meta data for woocommerce subtotal to use in future calculations?
I’m using AffiliateWP Pro plugin for WordPress and I’ve managed to make it calculate the referral amount with my custom formula. It happens in the exact time that the plugin has intended to happen: When the user successfully pays for the woocommerce order and the order status changes into “processing.”
Now here’s the problem: I want the formula to retrieve and use the value of customer’s subtotal in my custom equation. Right now, it doesn’t give me the value of $subtotal to be used in my calculation formula.
Keep in mind that only raw values can be calculated in the following equation: (so for example, the $subtotal can’t be $100 as it must be 100)
Also I’ve put every custom piece of code into my child theme’s functions.php file:
$referral_amount = ( $amount - ( $subtotal * ( 1 - ( $rate / 100 ) ) ) );
The problem is that $subtotal is not one of the built in objects of the AffiliateWP plugin. So I had to make a new post meta data for it. Here is the full code:
add_action( 'woocommerce_checkout_update_order_meta', 'save_order_subtotal_as_post_meta', 10, 2 );
function save_order_subtotal_as_post_meta( $order_id, $data ) {
$order = wc_get_order( $order_id );
update_post_meta( $order_id, '_order_subtotal', $order->get_subtotal(false) );
}
add_filter( 'affwp_calc_referral_amount', 'my_custom_referral_amount_calculation', 10, 6 );
function my_custom_referral_amount_calculation( $referral_amount, $affiliate_id, $amount, $reference, $product_id, $context ) {
$subtotal = get_post_meta( $reference, '_order_subtotal', true);
$rate = affwp_get_affiliate_rate( $affiliate_id, false, $reference );
$referral_amount = ( $amount - ( $subtotal * ( 1 - ( $rate / 100 ) ) ) );
return (string) $referral_amount;
}
As you can see, the first code snippet is supposed to get the subtotal and assign it to a meta data key. But I don’t really know what’s happening
chrome plugin how to access the main/index.js from content script
Here is my manifest.json
{
"manifest_version": 2,
"name": "test!",
"version": "0.1.0",
"permissions": ["tabs", "activeTab", "<all_urls>", "storage"],
"browser_action": {
"default_popup": "index.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery-1.12.4.min.js", "append.js"],
"run_at": "document_end"
}
]
}
here is the project structure
in index.js (i don’t know how to call this kind of js), i have some method to call remote api, i want to call these methods in append.js (content script) when page onLoad, or i can send message to index.js, so append.js can modify the page content for me.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body class="container">
<form class="form-data" autocomplete="on">
<div class="enter-country">
Enter API key:
</div>
<div>
<input type="text" class="country-name" />
</div>
<button class="search-btn">Search</button>
</form>
<div class="result">
<div class="loading">loading...</div>
<div class="errors"></div>
<div class="data"></div>
<div class="result-container">
</div>
</div>
<button class="show-btn">Show</button>
<script src="main.js"></script>
</body>
</html>
here is the testing function in index.js
chrome.runtime.onMessage.addEventListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting === "hello")
sendResponse({farewell: "goodbye"});
}
);
here is the testing function in append.js
(async () => {
const response = await chrome.runtime.sendMessage({greeting: "hello"});
// do something with response here, not outside the function
alert(response + 'abc');
console.log(response);
})();
Reply in ephemeral message to a user’s message
is it possible for a bot to reply to a user’s message and the reply would be in ephemeral? like, if user1 sends a message the bot will automatically respond in ephemeral. only asking if this is possible if the user didn’t do any sort of interaction with the bot
TypeScript Sanity syntax error screams unexpected token
In my localhost it screams that there is a syntax error in my utils folders where I am fetching skills, I have a few more fetch files setup the same way but this one screams in the local host as such 
Next I ran my build to see what he terminal tells me Module ‘”sanity”‘ has no exported member ‘defineConfig’. So I checked the version of sanity, tried updating it. error still occurred. Here is my sanity folder package.json 
how do python handle asynchronous task
I’ve strong background in a JS frameworks. Javascript is single threaded language and during the execution of code when it encounters any async task, the event loop plays the important role there.
Now I’ve been into Python/Django and things are going good but I’m very curious about how python handle any asynchronous tasks whenever I need to make a database query in django, I simple use the queryset method like
def func(id):
do_somthing()
user = User.objects.get(id=id)
do_somthing_with_user()
func()
another_func()
I’ve used the queryset method that fetch something from database and is a asynchronous function without await keyword. what will be the behaviour of python there, is it like block the execution below until the queryset response, is it continue the execution for the rest of code on another thread.
Also whenever we need to make an external request from python, we uses requests library method without await keyword,
r = request.get("https://api.jsonplaceholder.com/users")
# will the below code executes when the response of the request arrive?
do_somthing()
.
.
.
do_another_thing()
does python block the execution of code until the response arrives?
In JS the async task is handled by event loop while the rest of the code executes normally
console.log("first")
fetch("https://api.jsonplaceholder.com/users").then(() => console.log("third"))
console.log("second")
the logs in console will be
first
second
third
How Python Handles these type things under the hood?
How to check internet connectivity continuously in background while android application running (Java)
I want to check internet connectivity continuously in background while my android application running. I mean from starting of the application to the end of the application. How can i do it? What should be the approach?
Here is my project – https://tusfiles.com/0fm3wnegxnci
How to get and preview the http image url from DB in under the HTML file type
I did achieve the preview image function use js and then I tried to get the http image url from DB, but it doesn’t geted and showed that particular image in image tag
I did try the got dynamic images to preview under the HTML tag element, but the dynamic images get in the DB, but it doesn’t show in the preview area, So How do achieve this in this film?
Note that:::
In the geted image url prefix has http, that set attribute only allowed for https


