Javascript / HTML code doesn’t work on server [closed]

when I upload my code to the server, everything is mixed up and when I click on buttons, I get an error message:
VM53 :207 Uncaught TypeError: backPresentation is not a function
at HTMLImageElement.onclick (VM53 :207:10)

When testing the website on my computer, everything seems to be find. Does anybody has a solution?

href link not loading

I have an ignore button which isn’t picking up the correct link from Rails. When clicked it should send a post request with the link. Something like

https://myurl.co.uk/orders/174/ignore_export_errors

The browser shows no href link being picked up from the form:

<a class="button primary confirm" data-disable-with="Please wait.." data-id="" data-method="post" data-remote="true" href="">ignore</a>

Relevant code snippets below:

Rails

Views
= render layout: 'royal_mail_click_and_drop_apps/section', locals: { id: 'xero_errored_orders', title: 'Export Errors new' } do
  .row.column
    .record-list.errored_orders
      table.sw-table--inner
        thead
          tr
            th style="width: 30px" Ignore
        tbody
- @errored_orders.each do |order|
  tr.errored_order data-id=order.id
    td.text-center
      a.sw-input-group__button.ignore data-open="confirm-ignore-export-error" data-href=ignore_export_errors_order_path(order) data-id=order.id
        i.sw-icon-eye aria-hidden="true"
        span.show-for-sr ignore

Modal

#confirm-ignore-export-error.reveal data-reveal=""
  button.sw-modal__close.close-button aria-label="Close modal" data-close="" type="button"
    i.sw-icon-forbidden-mark.margin-0 aria-hidden="true"
  h1.sw-modal__heading Ignoring Export Error
  p.margin-top-2.margin-bottom-1.text-center Are you sure you want to ignore this error?
  .text-center
    a.button.primary.confirm href="" data-id="" data-remote="true" data-method="post" data-disable-with="Please wait.." ignore
    button.button.secondary data-close="" cancel

Logs
Started POST "/xero_apps?business_id=270&timestamp=1648723994&signature=09babb280a35f38617fa60dc78
dc175a50575a5bdf5a3aec18292138f2fa28a1" for 172.25.208.1 at 2022-03-31 11:54:09 +0100
Cannot render console from 172.25.208.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.2
55
No route matches [POST] "/xero_apps" excluded from capture: DSN not set

ActionController::RoutingError (No route matches [POST] "/xero_apps"):

The thing is I don’t want a post to this route anyway.

JavaScript

$ ->
  $('.export-errors .ignore').click ->
    $this = $(this)
    $('#confirm-ignore-export-error a').attr('href', $this.data('href')).data('id', $this.data('id'))

  $('#confirm-ignore-export-error .confirm').on 'ajax:success', ->
    orderId = $(this).data('id')
    $("tr.errored_order[data-id='#{orderId}']").fadeOut('normal', -> $(this).remove())
    $(this).closest('.reveal').foundation('close')

Upon clicking the ignore button I’m expecting the ignore_export_errors action to execute within OrdersController. However no path is being passed to the front-end button.

Implementing socket in reactjs with redux

I try to use socket in react and I made redux synced to share store with all chrome tabs then the socket will initialize at first tab only, my problem is when I close the first tab the socket also close and rest of tabs read only old data in store

How I can open socket in any tab when I close the main tab?

Security Issues: Injecting web3js into the window object of HTML

So I recently started learning web3js (using it with angular). And since using web3js with angular through the npm package is a bit cumbersome I was instead using a web3js cdn and injected it into the window object of my HTML (at the and of the body). Like this:

<script>
    if (typeof window.ethereum !== "undefined") {
        window.web3 = new Web3(window.ethereum);
    }
</script>

I was wondering if there are any security issues doing it like this? Should I stop doing it? I sadly couldn’t find any information online regarding this topic. Also is it bad in general when I inject stuff into the window object or is it fine?

Was googling few hours but couldn’t find any useful information.

Ajax function returns Error: INTERNAL SERVER ERROR (FLASK)

I am trying to populate a combo box based on the value of another combo box in Flask I am using Ajax for this. The first combo box is populated from a database and it works well. For the second combo box I am just returning a dummy json text to see how it works. The issue happens after the Post method in Ajax. The function returns an internal server. The code is below. Could you please check the code and let me know the issue.

app.py

@app.route('/get_vserver_name', methods = ["POST", "GET"])
def get_vserver_name():
    if request.method == 'POST':
        arrayname = request.form('arrayname')
        vservername = ['vserver1', 'vserver2']
    return jsonify({'vservername': vservername})

Javascript

    <script>
           $(document).ready(function () {
                $("#arrayname").selectpicker();

                $("#vservername").selectpicker();

                function load_data(type1, arrayname1) {
                    $.ajax({
                        url: "/get_vserver_name",
                        method: "POST",
                        data: { type: type1, arrayname: arrayname1 },
                        dataType: "json",
                        success: function (data) { //alert(category_id)
                            alert(data)
                            var html = "";
                            for (var count = 0; count < data.length; count++) {
                                html += '<option value="' + data[count].id + '">' + data[count].name + "</option>";
                            }
                            if (type == "arrayname") {
                                $("#arrayname").html(html);
                                $("#arrayname").selectpicker("refresh");
                            } else {
                                $("#vservername").html(html);
                                $("#vservername").selectpicker("refresh");
                            }
                        },
                        error: function (jqXhr, textStatus, errorMessage){
                        alert('Error: ' + errorMessage);
                        }
                    });
                }

                $(document).on("change", "#arrayname", function () {
                    var arrayname = $("#arrayname").val();
                    load_data("arrayname", arrayname);
                });
            });
    </script>

create.html

        <tr><td>

        <label for="arrayname">Select Array Name</label>
        <td>
        <select name="arrayname" data-live-search="true" id="arrayname" class="form-control" title="Select Array Name">
                {% for aname in arraynames %}
                <option value={{ aname[0] }}{% if aname[0] == state.choice %} selected {% endif %}>{{ aname[0] }}</option>
                {% endfor %}
        </select>

        <tr><td>

        <label for="vservername">Select Vserver Name</label>
        <td>
        <select name="vservername" data-live-search="true" id="vservername" class="form-control" title="Select Vserver Name">
        </select>
        <tr><td>

Trigger button from hover

I want to display the __button when I hover over the __image. But right now, the button has its own hover. It should do this: when the hover from __image is triggered, raise opacity of __button to visible.

Thanks for any help!

&__image {
    display:grid
    &:hover {
        transition: 1s;
        transform: scale(1.05);
    }
}

&__button {
    opacity: 0;
    display: grid;
    &:hover {
        opacity: 1;
    }
}

JS logic: Open / close menu on click or replace with another

I have a menu which opens up a submenu on click.

If a link has a dropdown menu (has class header--has-submenu), then on click, I’m making another element (.header__subContainer) appear.

The issue I’m having is with the logic. For example, in my demo, I have two links, what we deliver and about us, both have submenus.

I want a user to be able to click onto a link to open it and then click on the same link to close it (standard UX).

However, I also want the user to be able to click on one link (let’s say ‘what we deliver) and then click onto about usto show that menus dropdown (then the user can click theabout us` link again to close the menu).

I’ve tried toggleClass but this causes issues with the last scenario above.

Here’s a demo:

  $(".header--has-submenu a.header__parentLink").click(function(e) {
    e.preventDefault();
    
    console.log("click");

    var id = $(this).attr('data-menu');

    // add active state styles to link to showcase which menu is open
    $("li.header--has-submenu").removeClass("header--has-submenu--active");
    $(this).parent().addClass("header--has-submenu--active");


    // open subContainer (black div that contains all submenus)
    if ( $(".header__subContainer-menu").hasClass("header__subContainer-menu--active") ){
      $(".header__subContainer").removeClass("header__subContainer--active");
    } else {
      $(".header__subContainer").addClass("header__subContainer--active");
    }


    // remove active class from submenu, so only one menu is open at one time
    $(".header__subContainer-menu").removeClass("header__subContainer-menu--active");

    // open the relevant menu
    $(this).closest(".header__subContainer").addClass("header__subContainer--active");
    $(".header__subContainer-menu[data-menu='"+id+"']").toggleClass("header__subContainer-menu--active");

  });
.header {
  padding: 30px 0;
}
.header__parentUl * {
  color: #FFFFFF;
}
.header__li {
  margin: 0 20px;
}
.header__subContainer {
  display: none;
}
.header__subContainer--active {
  display: block;
}
.header__subContainer-menu {
  display: none;
}
.header__subContainer-menu--active {
  display: block;
}
.header--has-submenu--active a {
  color: green;
}

.background--black {
  background: #000000;
}

.reset-list {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.color--white {
  color: #FFFFFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<header class="header background--black">

  <div class="container">
    <div class="col-xl-9 justify-content-end">
      <nav class="header__menu">
        <ul class="header__parentUl d-flex reset-list">

          <li class="header__li header--has-submenu">
            <a class="header__parentLink" href="#" data-menu="what-we-deliver">What we deliver</a>
          </li>

          <li class="header__li header--has-submenu">
            <a class="header__parentLink" href="#" data-menu="about-us">About us</a>
          </li>

        </ul>
      </nav>
    </div>
  </div>

  <div class="container-fluid background--black header__subContainer">
    <div class="row justify-content-center">
      <div class="col-12">

        <nav class="header__subContainer-menu" data-menu="what-we-deliver">
          <ul class="header__subContainer-ul d-flex reset-list">
            <li class="header__subContainer-li">
              <a class="header__subContainer-link color--white " href="#">Link 1</a>
            </li>
            <li class="header__subContainer-li">
              <a class="header__subContainer-link color--white " href="#">Link 2</a>
            </li>
          </ul>
        </nav>

        <nav class="header__subContainer-menu" data-menu="about-us">
          <ul class="header__subContainer-ul d-flex reset-list">
            <li class="header__subContainer-li">
              <a class="header__subContainer-link color--white " href="#">Link 3</a>
            </li>
            <li class="header__subContainer-li">
              <a class="header__subContainer-link color--white " href="#">Link 4</a>
            </li>
          </ul>
        </nav>

      </div>
    </div>
  </div>

</header>

classList.contains(“class”) is not working

Please see my code below, I am trying to emulate that of githubs signup page where when a value is added or removed from the input field, the icon will switch on the left hand side of the input box from either an arrow to a check (if value input is True) or an X if value input field was true then was false once user input was deleted from the input field.
See my code below

JAVASCRIPT

 // toggle signup prompts
    const togglePrompts = document.querySelectorAll(".signup-input");

    const promptsArr = [...togglePrompts];
   
    promptsArr.forEach(input => {
        input.addEventListener("focus", function () {
            let nextTag = input.nextElementSibling;
            if (input === document.activeElement) {
                nextTag.classList.add("fa-arrow-right-long");
            }
        });
    });

    const signupForm = document.querySelector(".change");

    signupForm.addEventListener("change", function() {
        for (let i = 0; i < togglePrompts.length; i++) {
            let element = togglePrompts[i];
            let nextTag = element.nextElementSibling;
            if (element.value) {
                nextTag.classList.add("fa-check");
            }
            if (!element.value && element.classList.contains("fa-check")) {
                nextTag.classList.remove("fa-check");           
            }
        }
    });
});

HTML signup page

{% extends "layout.html" %}

{% block title %}
    Sign up
{% endblock %}

{% block main %}
    <div class="signup-div">
        <form action="/signup" method="post" autocomplete="off" class="change">
            <div class="form-control">
                <label class="signup-label" for="first_name">Enter your first name</label>
                <input class="signup-input" type="text" name="first_name" id="first_name" required autofocus>
                <i class="fa-solid fa-arrow-right-long" id="signup-continue-prompt"></i>
            </div>
            <div class="form-control">
                <label class=signup-label for="last_name">Enter your last name</label>
                <input class="signup-input" type="text" name="last_name" id="last_name"  required>
                <i class="fa-solid" id="signup-continue-prompt"></i>
            </div>
            <div class="form-control">
                <label class=signup-label for="email">Enter your email</label>
                <input class="signup-input" type="email" name="email" id="email" required>
                <i class="fa-solid" id="signup-continue-prompt"></i>
            </div>
            <div class="form-control">
                <label class=signup-label for="password">Create a password</label>
                <input class="signup-input" type="password" name="password" id="password"  required readonly onfocus="this.removeAttribute('readonly');">
                <i class="fa-solid" id="signup-continue-prompt"></i>
                <i class="fa-solid" id="toggle-password"></i>
            </div>
            <div class="form-control">
                <label class=signup-label for="confirmation">Confirm your password</label>
                <input class="signup-input" type="password" name="confirmation" id="confirmation" required>
                <i class="fa-solid" id="signup-continue-prompt"></i>
                <i class="fa-solid" id="toggle-confirmation"></i>
            </div>
            <button class="btn" type="submit">Sign up</button>                                
        </form>
    </div>
    <div class="terms-div">
        <p class="text-small">By creating an account, you agree to the 
        <a class="signup-terms" href="/terms" target="_blank">Terms of Service</a>
        . For more information about Hoook's privacy practices, see the 
        <a class="signup-terms" href="/privacy" target="_blank">Hoook Privacy Statement</a>
        . We'll occasionally send you account-related emails.</p>
    </div>
{% endblock %}

The issue is in the element.classList.contains("fa-check") statement as I have troubleshoot using just that condition in my if statement as well as just !element.value which works fine.

How can I make a component render onClick in a React functional component?

I’m a bit surprised I’m having trouble finding this online, but I can’t seem to find an example of how to do this in a React functional component. I have a React component that I would like to render when I click a button. Right now the function fires and I can see my console.log firing, however the component isn’t rendering. My first guess was that it won’t render because React doesn’t know to update the view, however I added boolean via useState and it still won’t render. What am I doing wrong?

Below is the relevant code. How can I get the component in addSection to render?

const FormGroup = ({index}) => {
  const [additionalSection, setAdditionalSection] = useState(false);

  const addSection = form => {
    setAdditionalSection(true);
    console.log('form', form);

    return additionalSection && (
      <div key={form.prop}>
        <p>This should render</p>
        <AdditiveSection
          form={form}
          register={register}
          errors={errors}
        />
      </div>
    );
  };
  ...
 return (
...
 <FormAdd>
   <LinkButton
      type="button"
      onClick={() => addSection(form)}
   >
     span className="button--small">{form.button}</span>
   </LinkButton>
 </FormAdd>
);

How could I create an element wrapper in Javascript?

For pure educational and curiosity purposes, I am trying to create an element-wrapper object that allows me to tack-on my own properties and methods to an element. The behavior I’m trying to simulate is basically this:

// get a button element to wrap
const button = document.querySelector('button');

// some function that wraps new properties/methods around a given element
function wrap(element) {
    this.customName = 'John';
    this.customAge = 100;

    this.printName = function() {
        console.log(this.customName);
    }

    // ...
    // ...somehow inherit element fields...
    // ...
}

// wrap the button element
const customElement = new wrap(button);

// custom behavior:
console.log(customElement.customAge) // output => 100
customElement.printName() // output => 'John'

// legacy behavior
console.log(customElement.clientHeight) // output => client height
customElement.remove() // => should still call 'remove' on the element

So, here I should be able to add my own methods/properties but still access the original fields normally. Is this even possible?

I’m using a constructor function here as an example just to demonstrate the intended behavior, but I don’t actually know if this would be relevant for the solution. I’m new to Javascript and I have done a ton of research on prototypes and classes, but I’m still confused on what approach I would take here.

Edit: As Brad pointed out in the comments, I also tried this implementation using classes:

class MyButton extends HTMLButtonElement {
    constructor() {
        super();
        this.customName = 'John';
        this.customAge = 100;
    }

    printName() {
        console.log(this.customName);
    }
}

const myBtn = new MyButton();

But this resulted in the error:
Uncaught TypeError: Illegal constructor

I got this error : JSON.parse: unexpected character at line 1 column 1 of the JSON data

I have this error and i need help please

This error appear after second like to another post or unlike the same post.

I am getting this error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.

this is what i get from data variable

{"link":"http://localhost/home/like/post/782532159775447%22,%22action%22:%22like_post"}

This seems to be a common “problem” but I could not find a solution somewhere else, so I’m asking here.

this is my code:

 <script type="text/javascript">
    
    function ajax_send(data,element){
                
        var ajax = new XMLHttpRequest();
        
        
        ajax.addEventListener('readystatechange', function(){
            
                response(ajax.responseText,element);
                           
        });
        
        data = JSON.stringify(data);
        
        ajax.open("post","<?=ROOT?>ajax.php",true);
        ajax.send(data);
    }
    function response(result,element){
     
        if(result != ""){
            
            
            var obj = JSON.parse(result);
         
            
            if(typeof obj.action != 'undefined'){
                
                if(obj.action == 'like_post'){
                    
                    var likes = "";
        
                    if(typeof obj.likes != 'undefined'){
                        likes = (parseInt(obj.likes) > 0) ? "Like(" +obj.likes+ ")" : "Like" ;
                        element.innerHTML = likes;
                    }
                    
                    if(typeof obj.info != 'undefined'){
                        var info_element = document.getElementById(obj.id);
                        info_element.innerHTML = obj.info;
                    }
                }
            }
        }
    }
    
    function like_post(e){
        
        e.preventDefault();
        var link = e.target.href;
        var data = {};
        data.link = link;
        data.action = "like_post";
        ajax_send(data,e.target);
    }
</script>
php

    $obj = (object)[];
    $obj->likes = count($likes);
    $obj->action = "like_post";
    $obj->info = $info;
    $obj->id = "info_$_GET[id]";
    
    echo json_encode($obj);

I got this java script json parse problem and i need help

Get different timezone names using new Date() [duplicate]

When I run new Date() in my browser I get this output:

Thu Mar 31 2022 17:46:12 GMT-0300 (Brasilia Standard Time)

in this case my timezone name is: Brasilia Standard Time

I need to get the same output but from other timezones, I already tried that:

new Date().toLocaleString('en-US', { timeZone: 'America/New_York' })

But that doesn’t give me the timezone name.

I need to get that timezone name because then I can get the abbreviation for the timezone by getting only the first letter of each word, which in my case would be BST (Brasilia Standard Time)

Create Proxy for accessing json object values using .value

Example
Json

  let Settings = {    
      "Policy": {        
          "allowP": true,
          "allowC": false,            
      }
  }

How can i access get value using following syntax

console.log( Policy.allowP ); // should return true
console.log( Policy.value.allowP ); // should also return true 

i tried following using javascript proxy

 let  createProxy = (settings : any) => {
const p = new Proxy(settings, {
      get(target, p, _r) {
        debugger;
        if (p === "value") {
          return settings;
        }
        return (target as any)[p];

      },
    });
 return p;
 }

 let  getSettings = () => {
  var settings = Settings;
  const p = new Proxy(settings, {
      get(target, p, _r) {
        debugger;
        if (p === "value") {
          return  createProxy(settings);
        }
        return createProxy((target as any)[p]);

      },
    });
 return p;
};

Tried to create Nested proxy so that i can access values using key.value syntax.

Is this correct way to implement it ? or is there any better way ?

Adding nas media library to site

Learning react and c# at the moment and thought of a project I would like to start. I have a Synology Nas drive (8tb) with 1800 movies on it. I wanted to make a personal site that I can stream them from and eventually make an Android app for personal use. What is the best file sharing method to stream these? It also needs to be accessible externally. I have ftp set up already for external access, smb for home use with Kodi. Just need a general direction to go in. I don’t need any help coding the site just trying to figure out how I should approach sharing the files for streaming and accessing them via JavaScript.