Passing JSON to Javascript in Laravel – but JS is converting the JSON to HTML Entities

In my Laravel controller, I am creating a multidimensional associative array:

$trendChart = Array (
    "series" => Array (
        "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5)
    ),
    "xaxis" => Array (
        "categories" => Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
    ),
    "chart" => Array (
        "type" => "line",
        "height" => 350,
    ),
    "stroke" => Array (
        "curve" => "smooth",
    ),
    "dataLabels" => Array (
        "enabled" => false,
    ),
    "fill" => Array (
        "colors" => Array ("#006ba6", "#f23f2b", "#f3f3f3")
    ),
    "annotations" => Array (
        "yaxis" => Array (
            "y" => 4.8,
            "borderColor" => "rgba(155, 199, 0, 1)",
            "borderWidth" => 3,
            "label" => Array(
                "borderColor" => "rgba(155, 199, 0, 1)",
                "style" => Array(
                    "color" => "#fff",
                    "background" => "rgba(155, 199, 0, 1)",
                ),
                "text" => "Ideal Average",
            ),
        ),
    ),
);

I then encode it into JSON, with:

$defaultChartOptions = json_encode($trendChart);

And then I pass $defaultChartOptions into my view:

return view('myview')->with(['defaultChartOptions' => $defaultChartOptions]);

Inside my view, I have the following JS:

var chartOptions = JSON.parse({{$defaultChartOptions}});

For the record, I have also attempted this without the JSON.parse command. Either way, by the time it gets passed to the JS, all of the quote marks have been converted into HTML entities. To view the page source, it looks like this:

var chartOptions = {"series":{"data":[1,1,2,2,3,3,3,3,4,4,4,5]},"xaxis":{"categories":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},"chart":{"type":"line","height":350},"stroke":{"curve":"smooth"},"dataLabels":{"enabled":false},"fill":{"colors":["#006ba6","#f23f2b","#f3f3f3"]},"annotations":{"yaxis":{"y":3,"borderColor":"rgba(229, 78, 78, .65)","borderWidth":3,"label":{"borderColor":"rgba(229, 78, 78, 1)","style":{"color":"#fff","background":"rgba(229, 78, 78, 1)"},"text":"Your Average"}}}}

What am I missing here?

Web scraping Javascript page with Python

I have little to no knowledge on dynamic page, so, this might come across as duplicate questions. But so far I have not been able to find a solution.

What I want to do is the scrape prices of financial products (index, futures, VI) from this website. (It is in Japanese though.)

https://nikkei225jp.com/chart/

If I look at the network tab, I can see that it is sending a request to the server every second to retrieve a payload, which is then used to update the prices. The end of the string looks suspiciously like epoch time, but it is not exactly it either, I think it has about 4 extra characters.

Sample request URL:
https://nikkei225jp.com/_data/_nfsWEB/ajax_nikkei.js?_=1652153479901

Payload:
A[111]=”25978.44_-340.90_-1.30_12:35_1_26193.44_25773.83″;
A[112]=”1854.24_-24.15_-1.29_12:35_1_1865.04_1840.00″;
…

I thought if I could just have a way to generate the timestamp, and using the request from Python, I could retrieve the payload, but website engineering is much more complicated than what I was thinking.

I could use selenium, but it was a bit too slow. Is headless browser the only way to achieve what I want? Or am I missing some other methods? Also, this webpage is considered as Javascript, but I heard it has something to do with websocket, which I have little to no idea.

Currently, I am using request and beautifulsoup to obtain the index price, but I needed other prices, which is not available in the html code.

Thanks in advance.

Unable to install ts-node using brew because it cannot be found

brew install ts-node
Warning: No available formula with the name “ts-node”.
==> Searching for similarly named formulae…
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)…
Error: No previously deleted formula found.
==> Searching taps on GitHub…
Error: No formulae found in taps.

Would appreciate any assistance as it cannot find ts-node.

How to find the approximate color of any color in a given palette?

I’m working on a pixel game that has a limited palette, but lighting and translucency can cause colors to go out of the palette. To make the overall picture uniform, I need a color approximation algorithm with low time complexity.

I’ve searched about how to find the differences between colors, and find that the distance between colors is not consistent with the distance of their color space coordinates. So I may need a way to optimize the distance finding algorithm for non-uniform spaces, but I’m completely confused about it.

This project is an Webapp game which run on browser, but at this stage it is only planned to be compatible with electron.

How can i iterate an imported component in a v-data-table without using v-slot?

i want to do this
My example (open the image)
but without using v-slots like this

<template v-slot:[`item.actions`]="{ item }">
                            <v-btn
                                class="ma-2"
                                fab
                                x-small
                                dark
                                color="#E7BD37"
                                @click="newdialog(item)"
                            >
                                <v-icon dark small> mdi-pencil </v-icon>
                            </v-btn>
                        </template>

because i want an icon but i dont want to saturate my component, so how can i iterate my component keeping my index to use the button in a correct way. thanks c:

How to pass React Native Component as a JSON object

I want to use react-native-intro-slider in my react native application to make the intro pages as a slider. I have already implemented the pages as react functional components (where I can import them and use, ex:- ). But it seems that react native slider takes an array of json objects as inputs.

Ex:-

const slides = [
  {
    key: 1,
    title: 'Title 1',
    text: 'Description.nSay something cool',
    image: require('./assets/1.jpg'),
    backgroundColor: '#59b2ab',
  },
  {
    key: 2,
    title: 'Title 2',
    text: 'Other cool stuff',
    image: require('./assets/2.jpg'),
    backgroundColor: '#febe29',
  },
  {
    key: 3,
    title: 'Rocket guy',
    text: 'I'm already out of descriptionsnnLorem ipsum bla bla bla',
    image: require('./assets/3.jpg'),
    backgroundColor: '#22bcb5',
  }
];

Instead of above json objects I want to pass the already created pages (functional components) as an input array. How can I do it, please?

Thanks in advance.

Confused pls help: .innerText or .value in JavaScript?

There’s a problem I’ve encountered but can’t find explanation so far. The code is as follows:

let textbox = document.getElementById("textbox");
let result = document.getElementById("result");

function convertToCm() {
  value = textbox.value;
  result.innerText = +value * 2.54;
  document.body.appendChild(result);
}
<input id="textbox" type="text">
<button onclick="convertToCm()">Convert to cm</button>
<div id="result">result</div>

(I tried pasting the code here but it keeps telling me there’s indentation problem even after fixing it, so there’s the link to the screenshot)

In the second line of the function, I tried to use textbox.innerText instead, however this gives me output of 0 of whichever number I put in the textbox. In the third line, I also tried to use result.value instead, but it would then output the same number I put in the textbox. I’m really confused.

I’ve tried looking on google but haven’t found an explanation so far. Could someone please help me? Thank you so much!

Expand console nested object in node.js

when I do this in node.js: console.log(someObject) I got [Object] or [Array]. How do I see what’s inside without access to it? Like seeing the “entire” thing. I tried JSON.stringify but it only format it, it doesn’t expand it.

How to prevent duplicate booking and set time slots using nextjs and prisma

Bellow I have my nextjs app booking system. I am new to this and trying to make my own website for simple booking. I have it all connected to netlify. I am able to collect booking time and name etc.

I am using netlify forms for that however I am trying to stop duplicated bookings and some last two hours were some last three hours so I need to be able to set a different block time in order to do this. I have no idea…

I connected my nextjs app to prisma and created a CRUD based of tutorials. However I do not know where to start or how the logic would even look to do that?

Below is what I have.

testme.jsx

import { GetServerSideProps } from 'next'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { prisma } from '../lib/prisma'


interface Notes{
  notes: {
    id: string
    title: string
    time: string
    email: string
    date: string
    content: string
  }[]
}

interface FormData {
  title: string
  time: string
  email: string
  date: string
  content: string
  id: string
}

const Home = ({notes}: Notes) => {
  const [form, setForm] = useState<FormData>({title: '', email: '', date: '', time: '', content: '', id: ''})

  const router = useRouter()

  const refreshData = () => {
    router.replace(router.asPath)
  }

  useEffect(() => {
    const fetchForm = async () => {
      const res = await fetch('http://localhost:3000/api/create')
      const data = await res.json();
      setForm(data)
    }
    fetchForm();
  }, []);


    async function create(data: FormData) {
    try {
      fetch('http://localhost:3000/api/create', {
        body: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'POST'
      }).then(() => {
        if(data.id) {
          deleteNote(data.id)
          setForm({title: '', time: '', email: '', date: '', content: '', id: ''})
          refreshData()
        } else {
          setForm({title: '', time: '', email: '', date: '', content: '', id: ''})
          refreshData()

        }
      }
        )
    } catch (error) {
      console.log(error);
    }
  }


  async function deleteNote(id: string) {
    try {
     fetch(`http://localhost:3000/api/note/${id}`, {
       headers: {
         "Content-Type": "application/json",
       },
       method: 'DELETE'
     }).then(() => {
       refreshData()
     })
    } catch (error) {
     console.log(error); 
    }
  }

  async function pauseNote(time: string) {
    try {
     fetch(`http://localhost:3000/api/note/${time}`, {
       headers: {
         "Content-Type": "application/json",
       },
       method: 'DELETE'
     }).then(() => {
       refreshData()
     })
    } catch (error) {
     console.log(error); 
    }
  }

  const handleSubmit = async (data: FormData) => {
    try {
     create(data) 
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <div>
      <h1 className="text-center font-bold text-2xl mt-4">Notes</h1>

      
      <form onSubmit={e => {
        e.preventDefault()
        handleSubmit(form)
      }} className='w-auto min-w-[25%] max-w-min mx-auto space-y-6 flex flex-col items-stretch'>
        <input type="text"
          placeholder="Name"
          value={form.title}
          onChange={e => setForm({...form, title: e.target.value})}
          className="border-2 rounded border-gray-600 p-1"
        />
         <input type="time"
          placeholder="time"
          value={form.time}
          onChange={e => setForm({...form, time: e.target.value})}
          className="border-2 rounded border-gray-600 p-1"
        />
          <input type="date"
          placeholder="date"
          value={form.date}
          onChange={e => setForm({...form, date: e.target.value})}
          className="border-2 rounded border-gray-600 p-1"
        />

<input type="email"
          placeholder="Email"
          value={form.email}
          onChange={e => setForm({...form, email: e.target.value})}
          className="border-2 rounded border-gray-600 p-1"
        />
        <textarea 
          placeholder="Content"
          value={form.content}
          onChange={e => setForm({...form, content: e.target.value})}
          className="border-2 rounded border-gray-600 p-1"
        />
        <button type="submit" className="bg-blue-500 text-white rounded p-1">Add +</button>
      </form>
      <div className="w-auto min-w-[25%] max-w-min mt-20 mx-auto space-y-6 flex flex-col items-stretch">
        <ul>
          {notes.map(note => (
            <li key={note.id} className="border-b border-gray-600 p-2">
              <div className="flex justify-between">
                <div className="flex-1">
                  <h3 className="font-bold">{note.title}</h3>
                  <p className="text-sm">{note.content}</p>
                  <p className="text-sm">{note.time}</p>
                </div>
                <button onClick={() => setForm({title: note.title, date: note.date, email: note.email, time: note.time, content: note.content, id: note.id})} className="bg-blue-500 mr-3 px-3 text-white rounded">Update</button>
                <button onClick={() => deleteNote(note.id)} className="bg-red-500 px-3 text-white rounded">X</button>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

export default Home


export const getServerSideProps: GetServerSideProps = async () => {
  const notes = await prisma.note.findMany({
    select: {
      title: true,
      time: true,
      email: true,
      date: true,
      id: true,
      content: true
    }
  })

  return {
    props: {
      notes
    }
  }
}

inside my API folder i have

create.ts

import { NextApiRequest, NextApiResponse } from "next";
import { prisma } from "../../lib/prisma";

export default async function handler(req: NextApiRequest, res: NextApiResponse){
    const {title, time, content, email, date} = req.body

    try {
        await prisma.note.create({
            data: {
                title,
                time,
                email,
                date,
                content
            }
        })
        res.status(200).json({message: 'Booking made'})
    } catch (error) {
        console.log("Sorry time has been taken");
    }
}

Along side create.ts I have a note folder inside my api with
[id].tsx

import { NextApiRequest, NextApiResponse } from "next";
import { prisma } from "../../../lib/prisma";

export default async function handler(req: NextApiRequest, res: NextApiResponse){
    const noteId = req.query.id

    if(req.method === 'DELETE') {
        const note = await prisma.note.delete({
            where: {id: Number(noteId)}
        })
        res.json(note)
    } else {
        console.log("Note could not be created");
    }
}

I am sorry if this is a lot If you see my GitHub commits I promise I’ve been trying just need guidance?

How can I pass routes in nextjs?

I’m trying to pass routes to my NEXTJS app but it’s returning an error, I’ve looked everywhere but I can’t find the answer.

MY _App.tsx:

import Routes from './Routes'

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Index/>
  )
}

export default MyApp

MY Routes.tsx

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
import { SideBar } from './components/sideBar'

const Routes = () => {
  return (
    <div className={styles.container}>
      <Router>
        <Routes>
          <Route path='/' element={<SideBar />}/>
        </Routes>
      </Router>
    </div>
  )
}

export default Routes

My error:

ReferenceError: document is not defined

Validator not working at all when receving a $request->all()

I have a problem, I’m receiving data in my API from a frontend built with Angular, when the API receives the data it validates some values with the Validator library, but the validator library is not working because it’s not getting the data from the $request->all() because it’s always entering to the error condition of $validateData->fails() and not returning me the JWT of the successful login.

I would be very grateful if you could help me, down here my code:

Response when returning data from Angular before it’s send to the API:

Object { userId: "", tipo_documento: "", nombres: "", apellidos: "", direccion: "", correo_electronico: "[email protected]", contrasena: "Prueba123", telefono: "", celular: "", tipo_Usuario: "", … }
user.service.ts:25:16

response when returning $request->all() from the API on Laravel :

Object { "{"userId":"","tipo_documento":"","nombres":"","apellidos":"","direccion":"","correo_electronico":"test123@hotmail_com","contrasena":"Prueba123","telefono":"","celular":"","tipo_Usuario":"","ultima_act":""}": null }
login.component.ts:35:16

login method in Laravel:

    public function userLogin(Request $request){
        $jwtValidator = new JwtAuth();

        $validateData = Validator::make($request->all(),[
            'correo_electronico' => 'required|email',
            'contrasena' => 'required'
        ]);

        if($validateData->fails()){
            return $request->all();
            $signUp = array(
                'status' => 'Error',
                'code' => 404,
                'message' => 'El usuario no se ha podido identificar',
                'errors' => $validateData->errors()
            );

        }else{
            $hashPass = hash('sha256', $request->contrasena);
 
            $signUp = $jwtValidator->signUp($request->correo_electronico, $hashPass);

            if(!empty($request->getToken)){
                $signUp = $jwtAuth->signUp($request->correo_electronico, $hashPass, true); 
            }

        }

        return response()->json($signUp, 200);
    }

Login Componen.ts in Angular:

export class LoginComponent implements OnInit {

  public user: User;
  public status: string;

  constructor( private _userService: UserService ) {

    this.user = new User('', '', '', '', '', '', '', '', '', '', '');
    this.status = '';

  }

  ngOnInit(): void {
  }

  onSubmit(form: any){
    this._userService.signup(this.user).subscribe(
      response => {
        if (response.status == 'Success') {
          this.status = response.status;
        } else {
          this.status = 'Error';
        }
        console.log(response);
      },
      error => {
        this.status = 'error';
        console.log(<any>error);
      }
      )
  }

}

SignUp method in a service from Angular:

    signup(user: any, getToken = null): Observable<any>{
        if(getToken != null){
            user.getToken = true;
            console.log(user.getToken);
        }

        let params = user;
        let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
        console.log(params);

        return this._http.post(this.url+'/login', params, {headers: headers});
    }

How to ensure that `self.skipWaiting()` works while allowing POST requests in service worker’s fetch event

I’ve noticed that my service worker doesn’t respond to self.skipWaiting() when there are still tasks to be run.

In my service worker’s fetch event, I see various Firebase polls that use HTTP POST requests.

If I handle these requests in the service worker like so:

self.addEventListener("fetch", (event) => {
  if (event.request.method === "POST") {
    return event.respondWith(new Response(null, {status: 444}))
  }

  ...
})

Then self.skipWaiting() always works as expected.

However, if I do the following:

self.addEventListener("fetch", (event) => {
  if (event.request.method === "POST") {
    return event.respondWith(fetch(event.request))
  }

  ...
})

Then self.skipWaiting() seems to have no effect. In Chrome’s devtools, the new service worker still isn’t active (and also clicking on the blue skipWaiting link also has no effect). Chrome devtools screenshot showing the new service worker as waiting to activate

As a result, it seems that I have to choose between ensuring that self.skipWaiting() works, and allowing Firebase’s polling requests, but not both. Is there a way get self.skipWaiting() to work while still allowing Firebase’s polling requests?

“POST /user/repos” does not support clientId/clientSecret basic authentication

I’m trying to create a Github Repository via an NPM package Octokit. I’ve set up the necessary oAuth stuff, but keep getting the same error:

HttpError: [@octokit/auth-oauth-app] “POST /user/repos” does not support clientId/clientSecret basic authentication.

import { Injectable } from '@nestjs/common';
import { Octokit } from "@octokit/rest";
import { createOAuthAppAuth } from "@octokit/auth-oauth-app";

@Injectable()
export class AppService {
  private auth() {
    return createOAuthAppAuth({
      clientType: "oauth-app",
      clientId: "xxxxxxxxxxxxxxx",
      clientSecret: "xxxxxxxxxxxxxxxxxxxxxxx",
    });
  };

  public async create() {
    const octokit = new Octokit({
      authStrategy: createOAuthAppAuth,
      auth: this.auth()
    });

    return await octokit.rest.repos.createForAuthenticatedUser({
      name: `repoName/${new Date().toString()}`
    }).then(({ data }) => { message: data });
  }

}