TypeError : MyFunction is not a function at HTMLButtonElement.onclick

I have to code a website, I have my homepage and I want to add an input in my HTML and to add in my JavaScript a function who check if the word is the same in Javascript. I don’t know if this clear so there is my HTML:

<div class="secretword" id="english">         
<p>Clues have been placed on the different pages to form a word, find it! <input id="secret" autocomplete="off"><button onclick="secret()">Done</button></p>         
</div>

and my function:

function secret() {
    var secretInput = document.getElementById("secret").value; 
    var mot = "nsi"; 
    console.log("secretInput");
    if (secretInput === mot) {
        var bravo = document.getElementById('bravo');
        bravo.innerHTML = "right";
    }
}

It just need to check if the input is “nsi”, and then return “right”.
This website is just for me, in local. So i don’t need php, sql or other language.

Any better way to resolve Issues storing value from dropdown menu?

I have been trying to figure out why I couldn’t log the value of requestData to the console successfully. Somehow it’s not storing the value of selectedCategory in category as expected. Please help

// formInputComponent

import React, { useState } from 'react';
import DropdownContent from './NicheDropdown';
import { useSession } from "next-auth/react";

const CommChat = () => {
    const [message, setMessage] = useState('');
    const [response, setResponse] = useState('');
    const { data: session } = useSession();

    const email = session?.user?.email;
    const [selectedCategory, setSelectedCategory] = useState('');

    const blogCategories = [
        { name: "Books and Literature", href: "#", icon: "booksIcon" },
        { name: "DIY and Crafts", href: "#", icon: "diyIcon" },
        { name: "Learning", href: "#", icon: "educationIcon" },
       
    ];

    const handleCategorySelect = (category) => {
        console.log("Selected category:", category);
        setSelectedCategory(category.name);
    };

    const handleSubmit = async (event) => {
        event.preventDefault();

        console.log("Request data:", requestData, selectedCategory);

          if (!selectedCategory) {
             console.error("Please select a category");
            return;
         }

        const requestData = {
            category: selectedCategory,
            message: message,
            email: email
        };

        console.log("Request data:", requestData);

        try {
            const response = await fetch('/api/chatContent', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            if (response.ok) {
                const responseData = await response.json();
                setResponse(responseData.message);
            } else {
                console.error('Failed to send message');
            }
        } catch (error) {
            console.error('Error:', error);
        }
    };

    return (
        <div className="w-11/12">
            <div className="relative w-full">
                <footer className="max-w-4xl mx-auto sticky top-0 p-3 sm:py-6">
                    <form onSubmit={handleSubmit}>
                        <DropdownContent
                            className="flex flex-col"
                            blogCategories={blogCategories}
                            onSelect={handleCategorySelect}
                        />
                        <textarea
                            className="p-4 pb-12 block w-full bg-gray-100 border-gray-200 rounded-lg text-sm focus:border-red-500 focus:ring-red-500 dark:bg-neutral-800 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder-neutral-500 dark:focus:ring-neutral-600"
                            placeholder="What's going on today..."
                            value={message}
                            onChange={(e) => setMessage(e.target.value)}
                        />
                        <button className='bg-slate-500 hover:bg-slate-600 text-white font-bold py-2 px-4 rounded-md my-4' type="submit">Send message</button>
                    </form>
                    {response && <p>{response}</p>}
                </footer>
            </div>
        </div>
    );
};

export default CommChat;

//Dropdown component

import React, { useState } from "react";
import { Dropdown, DropdownTrigger, DropdownMenu, DropdownItem, Button } from "@nextui-org/react";

const DropdownContent = ({ blogCategories }) => {
    const [selectedNiche, setSelectedNiche] = useState(null);

    const handleNicheSelect = (niche) => {
        setSelectedNiche(niche);
    };

    return (
        <Dropdown>
            <DropdownTrigger>
                <Button className="text-black font-thin h-7 rounded-none mb-1">
                    <img src="/images/niche.png" className="w-6 h-6" />
                    {selectedNiche ? selectedNiche.name : "Select a Niche"}
                </Button>
            </DropdownTrigger>
            <DropdownMenu aria-label="Dropdown blogCategories" className="dropdown-menu overflow-y-auto">
                {blogCategories && blogCategories.map((item) => (
                    <DropdownItem key={item.name} onClick={() => handleNicheSelect(item)} className="text-black font-thin">
                        {item.name}
                    </DropdownItem>
                ))}
            </DropdownMenu>
        </Dropdown>
    );
};

export default DropdownContent;

how do i make a form submission permanent in my django project?

in my django project
models.py =

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone


class User(AbstractUser):
    profile_pic = models.ImageField(upload_to='profile_pic/')
    bio = models.TextField(max_length=160, blank=True, null=True)
    cover = models.ImageField(upload_to='covers/', blank=True)
    whatsapp = models.CharField(max_length=25, blank=True, null=True)

    def __str__(self):
        return self.username

    def serialize(self):
        return {
            'id': self.id,
            "username": self.username,
            "profile_pic": self.profile_pic.url,
            "first_name": self.first_name,
            "last_name": self.last_name
        }

class Post(models.Model):
    creater = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
    date_created = models.DateTimeField(default=timezone.now)
    content_text = models.TextField(max_length=140, blank=True)
    content_image = models.ImageField(upload_to='posts/', blank=True)
    likers = models.ManyToManyField(User,blank=True , related_name='likes')
    savers = models.ManyToManyField(User,blank=True , related_name='saved')
    comment_count = models.IntegerField(default=0)

    def __str__(self):
        return f"Post ID: {self.id} (creater: {self.creater})"

    def img_url(self):
        return self.content_image.url

    def append(self, name, value):
        self.name = value

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    commenter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='commenters')
    comment_content = models.TextField(max_length=90)
    comment_time = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f"Post: {self.post} | Commenter: {self.commenter}"

    def serialize(self):
        return {
            "id": self.id,
            "commenter": self.commenter.serialize(),
            "body": self.comment_content,
            "timestamp": self.comment_time.strftime("%b %d %Y, %I:%M %p")
        }
    
class Follower(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers')
    followers = models.ManyToManyField(User, blank=True, related_name='following')

    def __str__(self):
        return f"User: {self.user}"
        

views.py =

from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
import json

from .models import *


def index(request):
    all_posts = Post.objects.all().order_by('-date_created')
    paginator = Paginator(all_posts, 10)
    page_number = request.GET.get('page')
    if page_number == None:
        page_number = 1
    posts = paginator.get_page(page_number)
    followings = []
    suggestions = []
    if request.user.is_authenticated:
        followings = Follower.objects.filter(followers=request.user).values_list('user', flat=True)
        suggestions = User.objects.exclude(pk__in=followings).exclude(username=request.user.username).order_by("?")[:6]
    return render(request, "network/index.html", {
        "posts": posts,
        "suggestions": suggestions,
        "page": "all_posts",
        'profile': False
    })


def login_view(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render(request, "network/login.html", {
                "message": "Invalid username and/or password."
            })
    else:
        return render(request, "network/login.html")


def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))


def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        fname = request.POST["firstname"]
        lname = request.POST["lastname"]
        profile = request.FILES.get("profile")
        print(f"--------------------------Profile: {profile}----------------------------")
        cover = request.FILES.get('cover')
        print(f"--------------------------Cover: {cover}----------------------------")

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "network/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            user = User.objects.create_user(username, email, password)
            user.first_name = fname
            user.last_name = lname
            if profile is not None:
                user.profile_pic = profile
            else:
                user.profile_pic = "profile_pic/no_pic.png"
            user.cover = cover           
            user.save()
            Follower.objects.create(user=user)
        except IntegrityError:
            return render(request, "network/register.html", {
                "message": "Username already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("index"))
    else:
        return render(request, "network/register.html")



def profile(request, username):
    user = User.objects.get(username=username)
    all_posts = Post.objects.filter(creater=user).order_by('-date_created')
    paginator = Paginator(all_posts, 10)
    page_number = request.GET.get('page')
    if page_number == None:
        page_number = 1
    posts = paginator.get_page(page_number)
    followings = []
    suggestions = []
    follower = False
    if request.user.is_authenticated:
        followings = Follower.objects.filter(followers=request.user).values_list('user', flat=True)
        suggestions = User.objects.exclude(pk__in=followings).exclude(username=request.user.username).order_by("?")[:6]

        if request.user in Follower.objects.get(user=user).followers.all():
            follower = True
    
    follower_count = Follower.objects.get(user=user).followers.all().count()
    following_count = Follower.objects.filter(followers=user).count()
    return render(request, 'network/profile.html', {
        "username": user,
        "posts": posts,
        "posts_count": all_posts.count(),
        "suggestions": suggestions,
        "page": "profile",
        "is_follower": follower,
        "follower_count": follower_count,
        "following_count": following_count,
        "email": user.email,
    })

def following(request):
    if request.user.is_authenticated:
        following_user = Follower.objects.filter(followers=request.user).values('user')
        all_posts = Post.objects.filter(creater__in=following_user).order_by('-date_created')
        paginator = Paginator(all_posts, 10)
        page_number = request.GET.get('page')
        if page_number == None:
            page_number = 1
        posts = paginator.get_page(page_number)
        followings = Follower.objects.filter(followers=request.user).values_list('user', flat=True)
        suggestions = User.objects.exclude(pk__in=followings).exclude(username=request.user.username).order_by("?")[:6]
        return render(request, "network/index.html", {
            "posts": posts,
            "suggestions": suggestions,
            "page": "following"
        })
    else:
        return HttpResponseRedirect(reverse('login'))

def saved(request):
    if request.user.is_authenticated:
        all_posts = Post.objects.filter(savers=request.user).order_by('-date_created')

        paginator = Paginator(all_posts, 10)
        page_number = request.GET.get('page')
        if page_number == None:
            page_number = 1
        posts = paginator.get_page(page_number)

        followings = Follower.objects.filter(followers=request.user).values_list('user', flat=True)
        suggestions = User.objects.exclude(pk__in=followings).exclude(username=request.user.username).order_by("?")[:6]
        return render(request, "network/index.html", {
            "posts": posts,
            "suggestions": suggestions,
            "page": "saved"
        })
    else:
        return HttpResponseRedirect(reverse('login'))
        


@login_required
def create_post(request):
    if request.method == 'POST':
        text = request.POST.get('text')
        pic = request.FILES.get('picture')
        try:
            post = Post.objects.create(creater=request.user, content_text=text, content_image=pic)
            return HttpResponseRedirect(reverse('index'))
        except Exception as e:
            return HttpResponse(e)
    else:
        return HttpResponse("Method must be 'POST'")

@login_required
@csrf_exempt
def edit_post(request, post_id):
    if request.method == 'POST':
        text = request.POST.get('text')
        pic = request.FILES.get('picture')
        img_chg = request.POST.get('img_change')
        post_id = request.POST.get('id')
        post = Post.objects.get(id=post_id)
        try:
            post.content_text = text
            if img_chg != 'false':
                post.content_image = pic
            post.save()
            
            if(post.content_text):
                post_text = post.content_text
            else:
                post_text = False
            if(post.content_image):
                post_image = post.img_url()
            else:
                post_image = False
            
            return JsonResponse({
                "success": True,
                "text": post_text,
                "picture": post_image
            })
        except Exception as e:
            print('-----------------------------------------------')
            print(e)
            print('-----------------------------------------------')
            return JsonResponse({
                "success": False
            })
    else:
            return HttpResponse("Method must be 'POST'")

@csrf_exempt
def like_post(request, id):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            post = Post.objects.get(pk=id)
            print(post)
            try:
                post.likers.add(request.user)
                post.save()
                return HttpResponse(status=204)
            except Exception as e:
                return HttpResponse(e)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))

@csrf_exempt
def unlike_post(request, id):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            post = Post.objects.get(pk=id)
            print(post)
            try:
                post.likers.remove(request.user)
                post.save()
                return HttpResponse(status=204)
            except Exception as e:
                return HttpResponse(e)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))

@csrf_exempt
def save_post(request, id):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            post = Post.objects.get(pk=id)
            print(post)
            try:
                post.savers.add(request.user)
                post.save()
                return HttpResponse(status=204)
            except Exception as e:
                return HttpResponse(e)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))

@csrf_exempt
def unsave_post(request, id):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            post = Post.objects.get(pk=id)
            print(post)
            try:
                post.savers.remove(request.user)
                post.save()
                return HttpResponse(status=204)
            except Exception as e:
                return HttpResponse(e)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))

@csrf_exempt
def follow(request, username):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            user = User.objects.get(username=username)
            print(f".....................User: {user}......................")
            print(f".....................Follower: {request.user}......................")
            try:
                (follower, create) = Follower.objects.get_or_create(user=user)
                follower.followers.add(request.user)
                follower.save()
                return HttpResponse(status=204)
            except Exception as e:
                return HttpResponse(e)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))

@csrf_exempt
def unfollow(request, username):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            user = User.objects.get(username=username)
            print(f".....................User: {user}......................")
            print(f".....................Unfollower: {request.user}......................")
            try:
                follower = Follower.objects.get(user=user)
                follower.followers.remove(request.user)
                follower.save()
                return HttpResponse(status=204)
            except Exception as e:
                return HttpResponse(e)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))


@csrf_exempt
def comment(request, post_id):
    if request.user.is_authenticated:
        if request.method == 'POST':
            data = json.loads(request.body)
            comment = data.get('comment_text')
            post = Post.objects.get(id=post_id)
            try:
                newcomment = Comment.objects.create(post=post,commenter=request.user,comment_content=comment)
                post.comment_count += 1
                post.save()
                print(newcomment.serialize())
                return JsonResponse([newcomment.serialize()], safe=False, status=201)
            except Exception as e:
                return HttpResponse(e)
    
        post = Post.objects.get(id=post_id)
        comments = Comment.objects.filter(post=post)
        comments = comments.order_by('-comment_time').all()
        return JsonResponse([comment.serialize() for comment in comments], safe=False)
    else:
        return HttpResponseRedirect(reverse('login'))

@csrf_exempt
def delete_post(request, post_id):
    if request.user.is_authenticated:
        if request.method == 'PUT':
            post = Post.objects.get(id=post_id)
            if request.user == post.creater:
                try:
                    delet = post.delete()
                    return HttpResponse(status=201)
                except Exception as e:
                    return HttpResponse(e)
            else:
                return HttpResponse(status=404)
        else:
            return HttpResponse("Method must be 'PUT'")
    else:
        return HttpResponseRedirect(reverse('login'))

urls.py =


from django.urls import path

from django.conf import settings
from django.conf.urls.static import static

from . import views

urlpatterns = [
    path("home", views.index, name="index"),
    path("n/login", views.login_view, name="login"),
    path("n/logout", views.logout_view, name="logout"),
    path("n/register", views.register, name="register"),
    path("<str:username>", views.profile, name='profile'),
    path("n/following", views.following, name='following'),
    path("n/saved", views.saved, name="saved"),
    path("n/createpost", views.create_post, name="createpost"),
    path("n/post/<int:id>/like", views.like_post, name="likepost"),
    path("n/post/<int:id>/unlike", views.unlike_post, name="unlikepost"),
    path("n/post/<int:id>/save", views.save_post, name="savepost"),
    path("n/post/<int:id>/unsave", views.unsave_post, name="unsavepost"),
    path("n/post/<int:post_id>/comments", views.comment, name="comments"),
    path("n/post/<int:post_id>/write_comment",views.comment, name="writecomment"),
    path("n/post/<int:post_id>/delete", views.delete_post, name="deletepost"),
    path("<str:username>/follow", views.follow, name="followuser"),
    path("<str:username>/unfollow", views.unfollow, name="unfollowuser"),
    path("n/post/<int:post_id>/edit", views.edit_post, name="editpost")
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


the html file is inside a folder named network which is inside the templates folder
profile.html=

{% extends 'network/index.html' %}

{% load static %}

{% block profile %}
    <div class="profile-view" data-user="{{username.username}}">
       
        <div class="mbs-pec" id="mbs-pec" >
          
            <form method="POST" class="mbs-pecc" style="display: block;" enctype="multipart/form-data">
               
                {% csrf_token %}
                <div id="mbs-ec" class="mbs-ec">
                    <div id="mbs-ecc" class="mbs-ecc1">
                        <p>cover image</p>
                        <div class="c-image" style="background-image: url(/media/{{username.cover}})"></div>
                        <input type="file" name="cover">
                    </div>
                    <div id="mbs-ecc" class="mbs-ecc2">
                        <p>profile image</p>
                        <div class="p-image" style="background-image: url(/media/{{username.profile_pic}})"></div>
                        <input type="file" name="profile_pic">
                    </div>
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>First Name</p>
                    <input type="text" name="first_name" value="{{username.first_name}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Last Name</p>
                    <input type="text" name="last_name" value="{{username.last_name}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Username</p>
                    <input type="text" name="username" value="{{username.username}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Bio</p>
                    <input type="text" name="bio" value="{{username.bio}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Email</p>
                    <input type="email" name="email a" value="{{username.email}}">
                </div>
                
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Whatsapp</p>
                    <input type="text" name="whatsapp" value="{{username.whatsapp}}">
                </div>
               
                <div id="mbs-pecb" class="mbs-pecb " >
                    <button class="mbs-done btn btn-outline-success" id="mbs-done">Done</button>
                    <button class="mbs-close btn btn-outline-success" id="mbs-close">Close</button>
                </div>
            </form>
            
        </div>
        
       
        <div class="cover-image" style="background-image: url(/media/{{username.cover}})"></div>
        <div class="profile-image" style="background-image: url(/media/{{username.profile_pic}})"></div>
        <div class="profile-details">
            <div>
                {% if user.username == username.username %}
                    <button class="btn btn-outline-success float-right" id="edit-profile-btn">Edit Profile</button>
                {% elif is_follower %}
                    <button class="btn btn-success float-right" onclick="unfollow_user(this,'{{username.username}}','edit_page')" id="following-btn">Following</button>
                {% else %}
                    <button class="btn btn-outline-success float-right" onclick="follow_user(this,'{{username.username}}','edit_page')" id="follow-btn">Follow</button>
                {% endif %}
            </div>
            <div class="details-data">
                <h5>{{username.first_name}} {{username.last_name}}</h5>
                <div class="grey">@{{username.username}}</div>
                <div class="whatsapp">
                    {% if username.whatsapp is not None %}
                        <a href="https://wa.me/{{username.whatsapp}}" target="_blank">Whatsapp</a>
                    {% endif %}
                </div>
                <div class="bio">
                    {% if username.bio is not None %}
                        {{username.bio}}
                    {% endif %}
                </div>
                <div class="grey" style="padding: 8px 0px;">
                    <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-calendar3" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                        <path fill-rule="evenodd" d="M14 0H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM1 3.857C1 3.384 1.448 3 2 3h12c.552 0 1 .384 1 .857v10.286c0 .473-.448.857-1 .857H2c-.552 0-1-.384-1-.857V3.857z"/>
                        <path fill-rule="evenodd" d="M6.5 7a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
                    </svg>
                    &nbsp;Joined {{username.date_joined | date:"F Y"}}
                </div>
                <div>
                    <strong>
                        {{posts_count}}
                    </strong>
                    &nbsp;<span class="grey">Posts</span>
                    &ensp;
                    <a href="#">
                        <strong id="following__count">{{following_count | default:0}}</strong>&nbsp;<span class="grey">Following</span>
                    </a>
                    &ensp;
                    <a href="#">
                        <strong id="follower__count">{{follower_count | default:0}}</strong>&nbsp;<span class="grey">Followers</span>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <div class="space"></div>
{% endblock %}

{% block emptyprofile %}
    <center>
        <br>
        <strong style="font-size: 1.2em;">@{{username}} hasn't posted</strong>
        <div class="grey" style="font-size: .9em;">When they do, their posts will show up here.</div>
    </center>
{% endblock %}

focus on this part of the code

<div class="mbs-pec" id="mbs-pec" >
          
            <form method="POST" class="mbs-pecc" style="display: block;" enctype="multipart/form-data">
               
                {% csrf_token %}
                <div id="mbs-ec" class="mbs-ec">
                    <div id="mbs-ecc" class="mbs-ecc1">
                        <p>cover image</p>
                        <div class="c-image" style="background-image: url(/media/{{username.cover}})"></div>
                        <input type="file" name="cover">
                    </div>
                    <div id="mbs-ecc" class="mbs-ecc2">
                        <p>profile image</p>
                        <div class="p-image" style="background-image: url(/media/{{username.profile_pic}})"></div>
                        <input type="file" name="profile_pic">
                    </div>
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>First Name</p>
                    <input type="text" name="first_name" value="{{username.first_name}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Last Name</p>
                    <input type="text" name="last_name" value="{{username.last_name}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Username</p>
                    <input type="text" name="username" value="{{username.username}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Bio</p>
                    <input type="text" name="bio" value="{{username.bio}}">
                </div>
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Email</p>
                    <input type="email" name="email a" value="{{username.email}}">
                </div>
                
                <div id="mbs-pecb" class="mbs-pecb a">
                    <p>Whatsapp</p>
                    <input type="text" name="whatsapp" value="{{username.whatsapp}}">
                </div>
               
                <div id="mbs-pecb" class="mbs-pecb " >
                    <button class="mbs-done btn btn-outline-success" id="mbs-done">Done</button>
                    <button class="mbs-close btn btn-outline-success" id="mbs-close">Close</button>
                </div>
            </form>
            
        </div>

here it is displaying the users first name in {{username.first_name}} last name in {{username.last_name}} user name in {{username.username}} bio in {{username.bio}} email in {{username.email}} whatsapp in {{username.whatsapp}} profile picture in <div class="p-image" style="background-image: url(/media/{{username.profile_pic}})"></div> and cover picture in <div class="c-image" style="background-image: url(/media/{{username.cover}})"></div> now what i want is that when i update the information in first name, last name, username, bio, email, whatsapp and click on the “Done” button Done it will change the information permanently.

ngx-image-viewer : Image not getting dragged properly. Dragging the image makes the application unresponsive

I’m using ngx-image-viewer in an Angular 15 application, where I’m showing single image.

The ngx-image-viewer plugin has a default drag feature.
In my case the image is getting dragged but the drag action is extremely slow and image stutters while dragging. Until this drag operation is not completed the application remains unresponsive.

Plugin
https://www.npmjs.com/package/ngx-image-viewer

MailerLite embedded form JS snippet not working in Next.js project

MailerLite provides a js snippet to embed a form. The snippet works fine in a <script> tag in an html file, but for some reason errors out in a jsx file

   (function(w,d,e,u,f,l,n){w[f] = w[f] || function () {
        (w[f].q = w[f].q || [])
        .push(arguments);
      }, l = d.createElement(e), l.async = 1, l.src = u,
        n = d.getElementsByTagName(e)[0], n.parentNode.insertBefore(l, n);})

Returns an error of '}' expected ?

Very confused

How to extract content correctly from all kind of rss feeds

I’m a well experienced developer, or almost this is what i was thinking before facing this problem. It look so easy to me but i cannot make it work the right way.

I have a list of feed rss, users can add their own feeds to their profile so i need to make something that works even with strange formats, because are all differents.

This is what i need to extract:

  1. title
  2. post date
  3. post description
  4. image, if there is one
  5. video, if there is one

This is what i tried:

First: search for the right rss tags containing those data

Next: for any not found data, check an html tag via regex that might contain it (link or videos, images, img tags in the whole post xml while reading it all as a string)

Well i can’t figure out a better solution. It is a short description but the code to do that is so long that i think there will be for sure a better way. because this way i still cannot get most of the fields i want or when i display something is all broken because the xml of the feeds contain HTML and so on.

Feed rss are really misunderstood because it should be a standard, seems like everyone put whatever they want inside their feed.

randomized radio button questions answers

i have google form that i should submit it for at least 100 times with various answers.
options are radio button
form:
https://docs.google.com/forms/d/e/1FAIpQLSeZQhwT69zXekxARG_mpzOzX-Jo3kY_PFoXt3OysAQhlKq8wQ/viewform

can anyone help pleaseeeee
this is urgent
this will be great if i can run a code in Tampermonkey.
thank you

i hope it will be random answers so the frequently distribution will be various

Encapsulation in JavaScript – Accessing Private Fields in Linked List Implementation

I’ve implemented a linked list in JavaScript, and the code is fully functional. However, I’m encountering a puzzling behavior related to JavaScript’s private fields.

Here’s the issue: Despite declaring the data and next fields as private within the Node class, I’m still able to assign values to the next field from within the LinkedList class.


class Node {
    #data;
    #next;

    constructor(data, next = null) {
        this.#data = data;
        this.#next = next;
    }

    getData() {
        return this.#data;
    }
}

class LinkedList {
    #head;
    #tail;
    #size;

    constructor() {
        this.#head = null;
        this.#tail = null;
        this.#size = 0;
    }

    addLast(data){
        const node = new Node(data);

        if(!this.#head) {
            this.#head = node;
            this.#tail = node;
        } else {
            this.#tail.next = node;
            this.#tail = node;
        }

        this.#size++;
    }

    remove(data){
        if(!this.#head) return false;
        if(this.#head.getData() === data) {
            this.#head = this.#head.next;
            if(!this.#head) {
                this.#tail = null;
            }

            this.#size--;
            return true;
        }

        let current = this.#head;
        while(current.next){
            if(current.next.getData() === data){
                current.next = current.next.next;
                if(!current.next) this.#tail = current;
                this.#size--;
                return true;
            }
            current = current.next;
        }

        return false;
    }

    reverse() {
        if (!this.#head ) {
            console.log('The list is empty');
            return;
        }
        let prevNode = null;
        let currentNode = this.#head;
        this.#tail = this.#head;

        while (currentNode) {
            const nextNode = currentNode.next;
            currentNode.next = prevNode;
            prevNode = currentNode;
            currentNode = nextNode;
        }

        this.#head = prevNode;
    }

    printList() {
        let current = this.#head;
        while(current) {
            console.log(current.getData());
            current = current.next;
        }
    }
}

const superList = new LinkedList();
superList.addLast(10);
superList.addLast(20);
superList.addLast(30);
superList.addLast(40);

console.log("BEFORE REVERSE: ")
superList.printList();
superList.reverse();
console.log("AFTER REVERSE: ")
superList.printList();

Specifically, how does this line of code execute without error?

this.#tail.next = node;

How can the LinkedList class access the private #next field of a Node instance?

Error: could not find react-redux context value; please ensure the component is wrapped in a in React native Expo App

I am getting this error while trying to run my react native app
I am trying to make a react native app which will have a BottomNavBar and Drawer Navigation. I am using Redux Toolkit for State Management.
I have followed the documentation and i get this error. Please help me with this, if you have ever encountered this issue.

Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

This error is located at:
    in App (at withDevTools.js:18)
    in withDevTools(App) (at renderApplication.js:57)
    in RCTView (at View.js:116)
    in View (at AppContainer.js:127)
    in RCTView (at View.js:116)
    in View (at AppContainer.js:155)
    in AppContainer (at renderApplication.js:50)
    in main(RootComponent) (at renderApplication.js:67), js engine: hermes

Below is my App.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { Provider, useDispatch, useSelector } from 'react-redux'; // Import Provider
import store from './store/store'; // Assuming your store is here
import { logout } from './store/authSlice'; // Assuming your logout action is here
import * as SecureStore from 'expo-secure-store';
import { Ionicons } from '@expo/vector-icons';

// Import your screen components (replace with your actual screens)
import HomeScreen from './screens/HomeScreen';
import SettingsScreen from './screens/SettingsScreen';
import ProfileScreen from './screens/ProfileScreen';
import FaqScreen from './screens/FaqScreen';
import LoginScreen from './screens/LoginScreen';
import LogoutScreen from './screens/LogoutScreen';
// ... (add other screens as needed)

const Tab = createBottomTabNavigator();
const Drawer = createDrawerNavigator();

const HomeIcon = ({ size, color }) => <Ionicons name="home-outline" size={size} color={color} />;
const ProfileIcon = ({ size, color }) => <Ionicons name="person-outline" size={size} color={color} />;
const SettingsIcon = ({ size, color }) => <Ionicons name="settings-outline" size={size} color={color} />;
const LoginIcon = ({ size, color }) => <Ionicons name="log-in-outline" size={size} color={color} />;

function MyTabs({ isLoggedIn }) {

  return (
    <Tab.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
    <Tab.Screen
        name="Home"
        component={HomeScreen}
        options={{
          tabBarIcon: ({ color, size }) => <HomeIcon size={size} color={color} />,
        }}
      />
      <Tab.Screen
        name="Settings"
        component={SettingsScreen}
        options={{
          tabBarIcon: ({ color, size }) => <SettingsIcon size={size} color={color} />,
        }}
      />
      {isLoggedIn ? (
        <Tab.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            tabBarIcon: ({ color, size }) => <ProfileIcon size={size} color={color} />,
          }}
        />
      ) : (
        <Tab.Screen
          name="Login"
          component={LoginScreen}
          options={{
            tabBarIcon: ({ color, size }) => <LoginIcon size={size} color={color} />,
          }}
        />
      )}
      
    </Tab.Navigator>
  );
}

function App() {
    const isLoggedIn = useSelector((state) => state.auth.isLoggedIn);
  return (
    <Provider store={store}>
    <NavigationContainer initialRouteName="Home">
      <Drawer.Navigator>
        <Drawer.Screen name="Shop" component={MyTabs} />
        <Drawer.Screen name="FAQ" component={FaqScreen} />
        {isLoggedIn ? <Drawer.Screen name="Logout" component={LogoutScreen} /> : null}
        {/* Add other drawer screens if needed */}
      </Drawer.Navigator>
    </NavigationContainer>
    </Provider>
  );
}

export default App;

Thank you for your response.

I want to make the each character in a word to be a different color.I am ready to use JS or just Pure CSS

I want to have EACH character in a word to have different color.
For example how the google logo looks with each character having different colors.

word.innerHTML.charAt(0).style.color = ‘red’

Error:
Uncaught TypeError: Cannot set properties of undefined (setting ‘color’)
at HTMLDocument.

//I tried to use this along with for loops but it didn’t work.

Not able to store in the localStorage using the chrome extension

I am trying to create a Chrome extension that bookmarks the parts of the YouTube video and stores the timestamp of the YouTube video in the localStorage. Below is the code I tried the following code, and I can see the array with all the timestamps but as soon as I refresh the page, the data is getting erased.

This is for checking if there are any timestamps for that video

// add listener to the message from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  const { message, url } = request;
  if (message === "newVideo") {
    currentVideoURL = url.split("https://www.youtube.com/watch?v=")[1];
  }

  // checking the local storage for the bookmarks
  chrome.storage.local.get([currentVideoURL]).then((result) => {
    if (result[currentVideoURL]) {
      bookmarksArray = JSON.parse(result[currentVideoURL]);
    } else {
      bookmarksArray = [];
    }
  });
  console.log(bookmarksArray);
// this function only creates the icon element to display on the youtube player
createBookmarkBtn(); 
});

Below is the convertTime function that converts the time according to the time shown on youtube player and also stores the timestamp of the video in the localStorage

function convertTime(seconds) {
  let hours = Math.floor(seconds / 3600);
  let minutes = Math.floor((seconds % 3600) / 60);
  let remainingSeconds = Math.floor(seconds % 60);
  let formattedHours = hours.toString().padStart(2, "0");
  let formattedMinutes = minutes.toString().padStart(2, "0");
  let formattedSeconds = remainingSeconds.toString().padStart(2, "0");
  let formattedTime = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;

  const newBookmark = {
    time: formattedTime,
    desc: "Bookmark at " + formattedTime,
  };
  if (bookmarksArray.length === 0) {
    bookmarksArray = [newBookmark];
  } else {
    bookmarksArray.unshift(newBookmark);
    chrome.storage.local
      .set({ currentVideoURL: JSON.stringify(bookmarksArray) })
      .then(() => {
        console.log("Data saved");
      });
  }

  return formattedTime;
}

Access new window api response data from parent window. but I don’t have access of the code of new window

Problem Statement:
You have two browser windows, Window 1 and Window 2. In Window 2, an API call is made, and when the API response is received, you need to access the response data from Window 1. However, you do not have access to the code of Window 2, meaning you cannot directly modify it to facilitate communication between the windows.

Constraints:

  1. No access to the code of Window 2: You cannot modify or add code to Window 2 to directly communicate with Window 1.

  2. Limited communication between windows: Standard browser security restrictions prevent direct communication between windows or frames loaded from different origins, making it challenging to access data across windows without explicit cooperation.

Find a solution that allows you to access the API response data from Window 2 in Window 1, despite not having access to the code of Window 2.

React material-ui InputLabel component not working accordingly

I want the label to be displayed properly and take width according to its value ,i.e, criteria(Roles,No. of Employees ,etc ) and dont want to give it a fixed width.

Whats happening is that the label is not fully displayed , i.e, not taking width properly , I dont want to give the FormControl fullWidth prop. Below is the code. (I will change the values for MenuItems later , I want to to fix this issue first)

function Filter() {
        const filterCritieria=[
            'Roles','No of Employees','Experience','Remote','Minimum Base Pay Salary'
        ]
      return (
       <>
       {filterCritieria.map((criteria,index)=>(
           <FormControl key={index} sx={{  margin: '10px' }} >
               <InputLabel  htmlFor={criteria} >{criteria}</InputLabel>
               <Select
                   value={12}
                   label={criteria}
                   id={criteria} 
                   
               >
                   <MenuItem value={10}>Ten</MenuItem>
                   <MenuItem value={20}>Twenty</MenuItem>
                   <MenuItem value={30}>Thirty</MenuItem>
               </Select>
           </FormControl>
       ))}
             
             
            
       </>
      )
    }

Thanks in advanced

Could not establish connection. Receiving end does not exist [duplicate]

I am trying to send a message from background script to content script in my chrome extension. But it looks like the message gets send before the content script is loaded?

This is the error I get when I am using my extension normally:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

This is my background script :

chrome.tabs.onActivated.addListener(activeInfo => {
    chrome.tabs.get(activeInfo.tabId, tab => {
        if (tab.url && tab.url.includes("americanexpress.com/us/credit-cards/card-application/apply/prospect/terms")) {
            console.log(tab.url);
            chrome.tabs.sendMessage(activeInfo.tabId, {
                type: "NEW",
                cardURL: tab.url
            });
        }
    });
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (tab.url && tab.url.includes("americanexpress.com/us/credit-cards/card-application/apply/prospect/terms")) {
        console.log(tab.url);
        chrome.tabs.sendMessage(tabId, {
            type: "NEW",
            cardURL: tab.url
        });
    }
});

This is my contentScript.js code:

chrome.runtime.onMessage.addListenerdd((obj,sender,response) =>{
        const {type,value,pageURL}=obj;
        if(type==="NEW"){
            
            scrapeAmexData(pageURL)
            
        }
        console.log(currentPage)
    })
async function scrapeAmexData(url) {
console.log(url)
}

This is manifest.json file:

{
    "name": "Card tnc Details",
    "version": "0.1.0",
    "description": "scrap all credit card benefits & terms on Chase, American Express, Capital One and Citi",
    "permissions": ["storage", "tabs"],
    "host_permissions": ["https://*.americanexpress.com/*"],
    "background": {
      "service_worker": "background.js"
    },
    "content_scripts": [
      {
        "matches": ["https://*.americanexpress.com/*"],
        "js": ["contentScript.js"]
      }
    ],
    "web_accessible_resources": [
      {
        "resources": [
          
        ],
        "matches": ["https://*.americanexpress.com/*"]
      }
    ],
    "action": {
      "default_icon": {
        "16": "assets/icon.png",
        "24": "assets/icon.png",
        "32": "assets/icon.png"
      },
      "default_title": "Card Tnc",
      "default_popup":"popup.html"
    },
    "manifest_version": 3
}

useObserver hook doesn’t work after re-render components

I have simple React app, that using two types of pagination: general by pages pagination and like twitter infinity pagination.
For infinity pagination I used “useObserver” hook, to find the div element in the end of the page and if I see that element I load the next part of data.
For general pagination I used general useState and general gooks. It doesn’t matter.
I want to dynamically switch between those two type of pagination by button click. I have two buttons: one button for pagination and second one for infinity pagination. When I clicked for the first one I render pages, when I pressed for the second one I re-render end of the page and remove pages and and div for infinity loading.
But after re-render infinity loading my “useObserver” hook doesn’t work.

My “useObserver” hook:

import { useEffect, useRef } from "react";

export const useObserver = (ref, canLoad, isLoading, callBack) => {

const observer = useRef();

useEffect(() => {
    if (isLoading) return;
    if (ref.current === undefined || ref.current === null) return;
    if (observer === null) return;
    if (observer.current) observer.current.disconnect();

    var callBackObserver = (entries) => {
        if (entries[0].isIntersecting && canLoad) {
            callBack();
        }
    };

    observer.current = new IntersectionObserver(callBackObserver);
    observer.current.observe(ref.current);
}, [isLoading]);
};

My pagination switcher component:

import React from 'react';
import PostList from './PostList';
import Loader from './UI/loader/Loader';
import Pagination from './UI/pagination/Pagination';

export default function PaginationType({ isPagination, isPostLoading, removePost,
 sortedAndSearchedPosts, title, page,
 changePage, totalPages, lastElement }) {

 if (isPagination) {
    return (
        <div>
            {isPostLoading
                ? <div style={{ display: 'flex', justifyContent: 'center', marginTop: 50 }}><Loader /></div>
                : <PostList
                    remove={removePost}
                    posts={sortedAndSearchedPosts}
                    title={title}
                />
            }

            <Pagination page={page}
                changePage={changePage}
                totalPages={totalPages}
            />
        </div>
    );
}
else {
    return (
        <div>
            {isPostLoading &&
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: 50 }}><Loader /></div>
            }

            <PostList
                remove={removePost}
                posts={sortedAndSearchedPosts}
                title={title}
            />
            <div ref={lastElement} style={{ height: 20, background: 'red' }} />
        </div>
    );
}
};

Code from component that calling pagination switcher:

function Posts() {

 const [isClassicPage, setClassicPage] = useState(true);
 const [page, setPage] = useState(1);
 const [posts, setPosts] = useState([]);
 const [totalPages, setTotalPages] = useState(0);

 const [fetchPosts, isPostLoading, postError] = useFetching(async (limit, page) => {
 const response = await PostService.getAll(limit, page);
 if (isClassicPage) {
   setPosts(response.data);
 }
 else {
   setPosts([...posts, ...response.data]);
 }
 const totalCount = response.headers['x-total-count'];
 setTotalPages(getPageCount(totalCount, limit));
 });

 const lastElement = useRef();  

 useObserver(lastElement, page < totalPages, isPostLoading, () => {
   setPage(page + 1);
 });

 return (
  <div className="App">

  <PaginationSwitcher setClassicPage={setClassicPage} />      

  {postError &&
    <h1>Load error, so sorry :C</h1>
  }

  <PaginationType
    isPagination={isClassicPage}
    isPostLoading={isPostLoading}
    removePost={removePost}
    sortedAndSearchedPosts={sortedAndSearchedPosts}
    title={"List of Posts 1"}
    page={page}
    changePage={changePage}
    totalPages={totalPages}
    lastElement={lastElement}
  />

</div>
);
}
export default Posts;

I expecting that after switching between two buttons and re-rendering components all will be work fine!