Asp.Net cshtml Buttons onclick stopped working

This is a part of my code from cshtml view.
The buttons were working like 3 days ago and even loading backup doesn’t help…
Im running debug in IIS Express and microsoft edge.
After pressing button this is the debug info that i get:

Uncaught ReferenceError ReferenceError: addNewProduct is not defined
at onclick (localhost꞉44376/InvoiceView/InvoiceDetails/d7f21057-5519-4d99-af25-d6fe1bde8ecd꞉101:119:101:119

<div class="add-new-product">
        <button type="button" class="btn btn-success" onclick="addNewProduct('@ViewBag.Invoice.IdOfInvoice')">Add Product</button>
    </div>

    <script>
        function toggleMD(checkboxElement) {
            var row = $(checkboxElement).closest('tr');
            var defaultRateInput = row.find('.default-rate');
            var numberOfManDaysInput = row.find('.number-of-man-days');
            var priceNettoInput = row.find('.price-netto');

            if (checkboxElement.checked) {
                
                numberOfManDaysInput.prop('readonly', false);
                updatePriceNetto(checkboxElement);
            } else {
                
                numberOfManDaysInput.val(1).prop('readonly', true);
                updatePriceNetto(checkboxElement);
            }

        }

Js Script only targeting first gallery

i hope your well

Im having issue with some javascript (i very new to javascript)

I would like all my galleries to have functioning horizontal scrollbar and left/right buttons, NOT JUST THE FIRST.

im confused.

I have tried to change document.querySelector to document.querySelectorAll, but the same result happens, only the first gallery functions as intended.

Help?

website: [https://newtopia1.wpenginepowered.com/][1]

    const imageList = document.querySelectorAll(".slider-wrapper .image-list");
    const slideButtons = document.querySelectorAll(".slider-wrapper .slide-button");
    const sliderScrollbar = document.querySelectorAll(".container .slider-scrollbar");
    const scrollbarThumb = sliderScrollbar.querySelectorAll(".scrollbar-thumb");
    const maxScrollLeft = imageList.scrollWidth - imageList.clientWidth;
    
    // Handle scrollbar thumb drag
    scrollbarThumb.addEventListener("mousedown", (e) => {
        const startX = e.clientX;
        const thumbPosition = scrollbarThumb.offsetLeft;
        const maxThumbPosition = sliderScrollbar.getBoundingClientRect().width - scrollbarThumb.offsetWidth;
        
        // Update thumb position on mouse move
        const handleMouseMove = (e) => {
            const deltaX = e.clientX - startX;
            const newThumbPosition = thumbPosition + deltaX;

            // Ensure the scrollbar thumb stays within bounds
            const boundedPosition = Math.max(0, Math.min(maxThumbPosition, newThumbPosition));
            const scrollPosition = (boundedPosition / maxThumbPosition) * maxScrollLeft;
            
            scrollbarThumb.style.left = `${boundedPosition}px`;
            imageList.scrollLeft = scrollPosition;
        }

        // Remove event listeners on mouse up
        const handleMouseUp = () => {
            document.removeEventListener("mousemove", handleMouseMove);
            document.removeEventListener("mouseup", handleMouseUp);
        }

        // Add event listeners for drag interaction
        document.addEventListener("mousemove", handleMouseMove);
        document.addEventListener("mouseup", handleMouseUp);
    });

    // Slide images according to the slide button clicks
    slideButtons.forEach(button => {
        button.addEventListener("click", () => {
            const direction = button.id === "prev-slide" ? -1 : 1;
            const scrollAmount = imageList.clientWidth * direction;
            imageList.scrollBy({ left: scrollAmount, behavior: "smooth" });
        });
    });

     // Show or hide slide buttons based on scroll position
    const handleSlideButtons = () => {
        slideButtons[0].style.display = imageList.scrollLeft <= 0 ? "none" : "flex";
        slideButtons[1].style.display = imageList.scrollLeft >= maxScrollLeft ? "none" : "flex";
    }

    // Update scrollbar thumb position based on image scroll
    const updateScrollThumbPosition = () => {
        const scrollPosition = imageList.scrollLeft;
        const thumbPosition = (scrollPosition / maxScrollLeft) * (sliderScrollbar.clientWidth - scrollbarThumb.offsetWidth);
        scrollbarThumb.style.left = `${thumbPosition}px`;
    }

    // Call these two functions when image list scrolls
    imageList.addEventListener("scroll", () => {
        updateScrollThumbPosition();
        handleSlideButtons();
    });
}

window.addEventListener("resize", initSlider);
window.addEventListener("load", initSlider);```


  [1]: https://newtopia1.wpenginepowered.com/

Angular Popup Issue: Exceeding Screen Boundaries

I’m currently facing an issue in my Angular application where the popup extends beyond the screen boundaries, partially hiding its content. This code should work as follows: It should initially open centered in the position where the mouse passes over the button (x,y), however, if the popup opens in width and length in its extension beyond the screen, its central point must adjust so that it fits without protruding outside of it. Below is the relevant code snippet from the component and the popup directive that I’m using. I’ve tried a few approaches to adjust the popup position, but haven’t been able to completely resolve the issue.

Some images of the problem:

Works in this case -in the center:
enter image description here

Hidded in the left:
enter image description here

Hidded in the bottom:
enter image description here

The code:

HTML:

<div class="super-grupos-container">
    <!-- ... (other content) ... -->
    <div class="objetivo square-objetivo" *ngFor="let objetivo of grupos[0].objetivos" appPopup [popupContent]="objetivo.purpose">
        <b>{{ objetivo.reference }}</b>                      
        {{ objetivo.nome }}
    </div>
    <!-- ... (other content) ... -->
</div>

Typescript class:

 // Relevant TypeScript snippet
 export class PopupDirective {
// ... (other code) ...

private showPopup() {
    if (!this.popup) {
        this.popup = this.renderer.createElement('div');
        this.renderer.addClass(this.popup, 'popup-modal');
        this.renderer.setStyle(this.popup, 'position', 'fixed');

        const initialX = this.mouseX;
        const initialY = this.mouseY;

        this.renderer.appendChild(document.body, this.popup);

        setTimeout(() => {
            const popupWidth = this.popup.offsetWidth;
            const popupHeight = this.popup.offsetHeight;
            const maxX = window.innerWidth - popupWidth;
            const maxY = window.innerHeight - popupHeight;

            let adjustedX = Math.min(Math.max(initialX, 0), maxX);
            let adjustedY = Math.min(Math.max(initialY, 0), maxY);

            this.renderer.setStyle(this.popup, 'left', `${adjustedX}px`);
            this.renderer.setStyle(this.popup, 'top', `${adjustedY}px`);

            this.renderer.listen(this.popup, 'mouseleave', () => {
                this.hidePopup();
                this.popupActive = false;
            });
        }, 0);
    }

    this.renderer.setProperty(this.popup, 'innerHTML', this.popupContent);
}

// ... (other code) ...
}

CSS:

/* Relevant CSS styles */
.popup-modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.7);
    color: #fff;
    padding: 20px;
    border-radius: 8px;
    z-index: 1000;
}

useEffect using old variable value

In the below code, I expect it to run

start of useEffect

false

cleanup

start of useEffect

true

but it instead returns this, where isCanceled is still false even after the cleanup

start of useEffect

false

cleanup

start of useEffect

false

The code is this:

  useEffect(() => {
    console.log("start of useEffect")
    let isCanceled = false;
    console.log(isCanceled);

    return () => {
      isCanceled = true;
      console.log("cleanup");
    };
  });

Why is it still false even after cleanup? I was following this article for your reference https://dev.to/pallymore/clean-up-async-requests-in-useeffect-hooks-90h

Tried to reread article and google this question, but not sure why still.

finding the average of an array with a for loop in a function

I’m trying to find the average value of the array, I’m stumped on how to add the array values together, I have the for loop condition set up ( for ( i = 0; i < array.length; i++)

but how do I add the array values together ??

instructions:

// * PART 1
// * Return the average value for the given array of numbers.
// * Example: getAverage([22, 45, 4, 65]) => 34
// * */

where I’m at:

    function getAverage(array) {    
      for ( let i = 0; i < array.length; i ++){
      let total =              <-How do I add them together to get the total?
       return total / array.length
     } 

    }

    console.log(getAverage([20, 22, 24, 26]));

How to console.log array in 8 columns?

I need to console log array in 8 columns, but i am getting 6.

what I need -> as on green background
(https://i.stack.imgur.com/IbmJO.png)
what i got -> as on black backgroundenter image description here

Here is my code

let start = 0;
let end = 10752;
let increment = 256;
let columns = 8;
let res = [];
let counter = 0;

for (start; start <= end; start += increment) {
  res.push(start);
  ++counter;
  if (counter === columns) {
    res.join(`
    
    `);
    counter = 0;
  } else {
    res.join("");
  }
  res[res.length - 1] === 10752 ? console.log(res) : false;
}

console.log("*** End of program. ***");

Trying to make a XMLHttpRequest POST to my flask app but I keep getting 400 error

This is my flask app

from flask import Flask, render_template, request, jsonify 
from flask_cors import CORS


app = Flask(__name__) 
CORS(app)

@app.route("/") 
def hello(): 
    return render_template('index.html') 


@app.route('/process', methods=['POST']) 
def process(): 
    data = request.get_json() # retrieve the data sent from JavaScript 
    print("data")
    # process the data using Python code 
    result = data['value'] * 2
    return jsonify(result=result) # return the result to JavaScript 

if __name__ == '__main__': 
    app.run(debug=False) 

This is my js code, originally I was using jquery, but it wasnt working with cors so I switched to using XMLHttpRequest as suggested by another post, which fixed the cors error but now i have a 400 bad request error

function submit_clicked() {
    var info = document.getElementsByClassName("info")
    var title = document.getElementById("title").innerText
    console.log(title);
    if (title ==  "Create User Account") {
        const data = {
            "Firstname" : info[0].value,
            "Lastname" : info[1].value,
            "Username" : info[2].value,
            "Email" : info[3].value,
            "Password" : info[4].value,
            "Retype_Password" : info[5].value
        }
        sendData(data)
    }
}
function sendData(data) { 
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:5000/process"),
    xhr.send(JSON.stringify({ 'value': "value" })),
    xhr.onreadystatechange = function() { 
        if (xhr.readyState === 4 && xhr.status >= 400) { 
          console.log(xhr.response)
        } else { 
          //success 
        } 
    }
}

This is the error I get in the console of chrome when I try debug

I was trying to send the details stored in the var data to the flask app

pusher 403 forbidden – Laravel Broadcasting

I have an 403 forbidden error when using pusher, everything looks correct but I still face this error!

After the user create the order a new notification should be created:

    $order->doctor->user->notify(new AppointmentNotification($checkOrder, $user));

in the AppointmentNotification file:

public function via(object $notifiable): array
    {
        return ['broadcast'];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage([
            'title' => 'Appointment Reservation',
            'body' => 'New Appointment Reservation!',
            'icon' => 'fadeIn animated bx bx-health',
            'url' => route('doctor.appointments'),
            'doctorId' => $notifiable->id, 
        ]);
    }

The channel:

Broadcast::channel('Models.User.{doctorId}', function ($user, $doctorId) {
    return (int) $user->id === (int) $doctorId;
});

The bootstrap and js files countains:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
    wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

window.Echo.private(`App.Models.User.${doctorId}`)
    .notification(function(data){
        alert(data.body)
    })

And finally Im defining the doctorId in the layout and calling the Js file:

<script>
        const doctorId = "{{ optional(Auth::user()->doctor)->user_id }}";
    </script>
    <script>
        {!! Vite::content('resources/js/app.js')  !!}
</script>

Everything looks correct, I need you help, thanks.

I have tried to create event, and I faced the same error!

TMDB and Next Js

I am trying to integrate the TMDB API into my next js application. I went ahead and logged in, picked up my API key and saved it into a .env file. I then used axios to make the request. No error seems to occur in the file so far until I import the file into another file which I want to use. The data I am getting back seems not to be an array as expected. Instead, next js is throwing an error:

Error: Cannot read properties of undefined (reading ‘map’).

{movies.map((movie) => ({movie.title}))}

Below is my full code:

tmdb.js

import axios from "axios";

const TMDB_API_KEY = process.env.TMDB_API_KEY
const TMDB_BASE_URL = 'https://api.themoviedb.org/3';

export const fetchMovies = async () => {
    try {
        const response = await axios.get(`${TMDB_BASE_URL}/movie/popular`, {
            params: {
                api_key: TMDB_API_KEY,
                language: 'en-US',
                page: 1,
            },
        });
        return response.data.results;
    } catch (error) {
        return [];
    }
}

moviesdisplaylist.jsx

import './moviesdisplaylist.css'
import {fetchMovies} from '../../../../api/tmdb';

export default function MoviesDisplayList({movies}) {
  return (
      <>
        <div>
          <h1>TMDB movies</h1>
          <ul>
            {movies.map((movie) => (
              <li key={movie.id}>{movie.title}</li>
            ))}`your text`
          </ul>
        </div>
      </>
  );
}

export async function getStaticProps() {
  const movies = await fetchMovies();
  return {
    props: {
      movies: [],
    }
  }
}

I have tried searching up online for examples or the way it is supposed to be done but seems like the documentation is very limited. Even the TMDB docs does not show how to integrate it with different frameworks. Any help will be appreciated.

Firebase Service worker failed to register & Service worker evaluation failed

I am using FCM, to get the device token.
I am using React for frontend.
I need to setup the service worker to make it work.

The code works fine when run in localhost, it registers the service worker without any problem.
But when i use the hosted site, it fails and gives this error

Uncaught (in promise) FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope (‘https:// abc.netlify.app/firebase-cloud-messaging-push-scope’) with script (‘https:// abc.netlify.app/firebase-messaging-sw.js’): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).

Theres also another problem that i couldn’t use env variables directly into the SW file, so bard suggested me to use dotenv-webpack, i have created this file in root.

const Dotenv = require('dotenv-webpack');

module.exports = {
    plugins: [
        new Dotenv()
    ]
};

firebase-messaging-sw.js (service worker file)

importScripts('https://www.gstatic.com/firebasejs/9.6.4/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.4/firebase-messaging-compat.js');

const firebaseConfig = {
    apiKey: process.env.REACT_APP_FIREBASE_API,
    authDomain: process.env.REACT_APP_AUTHDOMAIN,
    projectId: process.env.REACT_APP_PROJECTID,
    storageBucket: process.env.REACT_APP_STORAGEBUCKET,
    messagingSenderId: process.env.REACT_APP_MESSAGINGSENDERID,
    appId: process.env.REACT_APP_APPID,
    measurementId: process.env.REACT_APP_MEASUREMENTID
}

firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging()
self.addEventListener('install', (event) => {
    event.waitUntil(self.register('firebase-messaging-sw.js'));
});

self.addEventListener('notificationclick', (event) => {
    event.waitUntil(
        // self.registration.showNotification(event.notification)
        //  add a condition to redirect to that particular app or just to /app 
        clients.openWindow('https://formatr.netlify.app')
    );
});

messaging.onBackgroundMessage((payload) => {
    console.log(
        "[firebase-messaging-sw.js] Received background message ", payload
    )
    console.log(payload.data)
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon
    }

    self.registration.showNotification(notificationTitle, notificationOptions)
})

Hide Contact Form 7 and show DIV after Sent

I want to hide my Contact Form 7 after validation and a successful sent, and show a div in its place. I’m using the shortcode ID. Its not working. Would it be easier to wrap the form in a div and hide that instead?

 <script type="text/javascript">
     document.addEventListener( 'wpcf7mailsent', function( event) {
  if ( '9a5f5ae' == event.detail.contactFormId ) { 
      var hid = document.getElementsByClassName("qtWRP2");

  if(hid[0].offsetWidth > 0 && hid[0].offsetHeight > 0) {
    hid[0].style.visibility = "visible";
}
  }
 }, true );
 </script>   

Jquery .load post value is accessible in local dev env but not in production

I have 2 files
loadmore.js

$(document).ready(function(){
    var postCount = 2;
    $("#btn-load_more").click(function() {
        postCount = postCount + 2;
        $("#posts").load("posts.php", {postNewCount: postCount});
        if (postCount >= x) {
            $("#btn-load_more").hide();
            
            return;
        }
    });
});

and post.php

<?php
    require 'dbh.php';

    $postNewCount = $_POST['postNewCount'];
    $sql = "SELECT * FROM posts ORDER BY postID DESC LIMIT $postNewCount";
    $result = mysqli_query($conn, $sql);
    $resultCheck = mysqli_num_rows($result);

    if ($resultCheck > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            require 'postPreview.php';
        }
    }
?>

I am having trouble reading the $postNewCount value when in production.

What am I doing wrong here?

I keep getting a 500 error when using the variable but the code successfully executes using a hard coded value or using the variable value in local dev env. I’ve narrowed it down to the .load jquery method not posting the postNewCount value or the post.php file not being able to retrieve the posted value.

FormData is empty in NextJS 14v


const Page = () => {


    const [categories, setCategories] = useState([]);
    const [productName, setProductName] = useState();
    const [categoryID, setCategoryID] = useState();
    const [productDescription, setProductDescription] = useState();
    const [price, setPrice] = useState();
    const [rating, setRating] = useState();
    const [image, setProductImg] = useState();

    const router = useRouter();
    const form = new FormData()

    useEffect(() => {
        GetCategories(setCategories)
    }, []);
    const handleSubmit = async (e) => {
        e.preventDefault();
        /* const formData = {
            productName,
            categoryID,
            productDescription,
            price,
            rating,
            image
        } */


        form.set('productName', productName)
        form.set('categoryID', categoryID)
        form.set('productDescription', productDescription)
        form.set('price', price)
        form.set('rating', rating)
        form.set('image', image)

        console.log(form)

        const jwt = await GenerateJWT(productName);
        await axios.post('/api/v1/products', form, {
            headers: {
                JWT: jwt,
                "Content-Type": 'multipart/form-data'
            }
        })
            .then(data => {
                console.log(data)
                alert('Product created successful');
                router.push('/');
            })
            .catch(err => {
                console.error(`Error to create a new product -> ${JSON.stringify(err)}`)
                console.log(err)
                alert('Error to create a new product, please try again later.')
            });
    };

    return (
        <div>
            <form
                onSubmit={(e) => {
                    handleSubmit(e);
                }}
            >
                <label htmlFor="productName">Product Name</label>
                <input type="text"
                    name="productName"
                    onChange={(e) => setProductName(e.target.value)}
                />
                <label htmlFor="categories">Categories</label>
                <select name="categories" id="categories"

                    onChange={(e) => setCategoryID(e.target.value)}
                >
                    {
                        categories.length && categories != undefined ?
                            categories.map(category => (
                                <option key={category.id} value={category.id}>{category.category}</option>
                            ))

                            : <option>Loading categories</option>
                    }
                </select>


                <label htmlFor="productDescription">Product description</label>
                <input type="text"
                    name="productDescription"
                    onChange={(e) => setProductDescription(e.target.value)}
                />
                <label htmlFor="price">Price</label>
                <input type="number"
                    name="price"
                    onChange={(e) => setPrice(e.target.value)}
                />
                <label htmlFor="rating">Rating</label>
                <input type="number"
                    name="rating"
                    onChange={(e) => setRating(e.target.value)}
                />
                <label htmlFor="productImg">Product image</label>
                <input type="file"
                    name="productImg"
                    onChange={(e) => setProductImg(e.target.files[0])}
                />
                <button type="submit">Create product</button>
            </form>
        </div>
    );
}

export default Page;

I am developing a form that communicates with the backend of my app with NextJS in its version number 14 and I try to send data through the FormData(), but the data is not saved in it, running the console.log(form) leaves the FormData empty. I thought it would be because of the React states but it still doesn’t work and I’m already going crazy lol.

Thank you very much in advance and I hope I can resolve this later.

Embedded images in EmailJS

I am using EmailJS, and I have created a form that requires the user to upload images from their device. I have taken these images and tried to add them to the template, but unfortunately, they are not getting added. Does EmailJS really support adding images? Should these images be processed or uploaded to a service to get a URL, or is it not necessary? These are all questions that anyone with answers to should please let me know because the task needs to be delivered to the client tomorrow, and it depends on these images. Help me, guys!

Note that I am using React.js, and I have tried sending the form using both sendForm and just form. If EmailJS supports sending images, what should be written in the React.js code, and what should be written in the Email Templates?

I tried adding the images locally within the frontend code only, but I failed.