Integrating Next.js within a PHP Page: How to Append Next.js Components to Specific DOM Elements?

I’m working on integrating Next.js (v14.0.2) into an existing PHP-based web application (Phalcon framework). I am not sure if I can incorporate Next.js components into specific sections of the PHP-generated page. I want to render React components generated by Next.js within targeted elements based on certain conditions or actions in the PHP logic.

I’ve attempted to use ReactDOM.createRoot in a manner similar to standalone React applications, but I’m aware that Next.js abstracts some of the rendering setup. How can I dynamically append Next.js-generated components to particular DOM elements within a PHP-rendered page? Are there specific Next.js methods or strategies to achieve this integration effectively without disrupting the PHP-rendered content? Any guidance, examples, or best practices would be highly appreciated. Thank you!

How to confirm a user’s order

Good day techies, I am working on a project that can allow users to order for a customized clothes but I am having an issues on how to show that a user’s order is approved or declined on my frontend page. I want the order to be flagged “approved” or “declined” when the admin hit either button. These are the codes:

const express = require('express');
const bcrypt = require('bcrypt');
const session = require('express-session');
const flash = require('connect-flash');
const methodoverride = require("method-override")
const path = require('path');
const mongoose = require('mongoose');
const Order = require('./model/order.js');

mongoose
   .connect("mongodb://127.0.0.1:27017/tailor")
   .then(()=>{console.log('Mongo server has started')})
   .catch(()=>{console.log('Connection to Mongo Failed')})

const app = express()

app.use(session({
    secret: 'keyboard cat',
    saveUninitialized: true,
    resave: true
}))

app.use(flash());
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(methodoverride("_method")) 
app.use(express.json())
app.use(express.urlencoded({extended:true})) 

const port = 3000;

let information =

app.post("/accept/:postid", async (req, res)=>{
    const orderID = req.params.postid;

    try {
        await Order.findByIdAndUpdate(orderID, {information: "APPROVED"})
        res.redirect('/allOrder')        
    } catch (error) {
        console.log(error)
        res.redirect('/orders/:postid')
    }
})


app.get('/allOrder', async (req, res )=>{
    const allOrder = await Order.find()
    res.render('allorder.ejs', {title: 'ALL ORDERS', allOrder, information})
})

and I don’t know how to express it at my frontend. But these is my frontend.

<div class="allOrder">
        <h2>ALL ORDERS</h2>      
        
        <div id="order">
          <% if (allOrder.length > 0) { %>
            <% allOrder.forEach(order => { %>
              <div>
                <a href="/orders/<%=order._id %>">
                  <h4 class="username"> From <%= order.username %></h4>
                  <p class="snippet"><%= order.snippet %> </p>
                  <br> <br>
                </a>
              </div>
              <div id="approve">
                <p><%=information%></p>
              </div>              
            <% }) %>              
          <% } else { %>
            <p>No Order</p>
          <% } %>
</div>

but the error I do get is that information is not defined.

Why does a CORS error occur when redirecting in NodeJS?

I have a NextJS client on port 3000 and a NodeJS server on port 4000. I have CORS configured on the server and normal requests from the client work fine.

However when I want to make a redirect with http://localhost:4000/api/token/refresh to http://localhost:3000/login I get this error:

Access to XMLHttpRequest at ‘http://localhost:3000/login’ (redirected from ‘http://localhost:4000/api/token/refresh?logout=yes’) from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I repeat: normal requests pass normally, it is with redirects that the problem arises. here is the cors setup on the express server:

app.use(
  cors({
    credentials: true,
    origin: http://localhost:3000
  })
);

Thank you in advance!

input a week, submit input and get all days in that week each in its own paragraph

id like users to to input a date e.g 16 nov 2023, and get all dates in that specific week starting from monday which would return as example,
13 nov 2023
14 nov 2023
15 nov 2023
16 nov 2023
17 nov 2023
18 nov 2023
19 nov 2023

however i cant get around a way to bind then with my html page. such that there’s an input field where user enters date, theres a submit button where upon click the dates are retrieved and displayed on the page each in its own paragraph tag. help please.

this is the code i have but i’m failing to bind it with my page

function days(current) {
  var week = [];
  // Starting Monday not Sunday 
  var first = current.getDate() - current.getDay() + 1;
  current.setDate(first);
  for (var i = 0; i < 7; i++) {
    week.push(new Date(+current));
    current.setDate(current.getDate()+1);
  }
  return week;
}

var input = document.getElementById('date').innerHTML = new Date(2023, 05, 13);
console.log('input: %s', input);
var result = document.getElementById('date1').innerHTML = days(input);

press me

Morris JS Chart won’t display

I have a chart on a webpage that won’t display anymore. The MySQL query is ok and displaying the correct data when echoed. I can’t figure out why it won’t work.

P.S. The same chart with a different MySQL query displays correctly on another webpage.

Here’s the script:

    <head>
    <link rel="stylesheet" href="../assets/vendor/bootstrap/css/bootstrap.min.css" />
    
    <link rel="stylesheet" href="../assets/vendor/chartist/css/chartist.min.css" />
    <link rel="stylesheet" href="../assets/vendor/chartist-plugin-tooltip/chartist-plugin-tooltip.css">

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
    </head>

                  <div class="body">
                            <div id="water_graph"></div>
                            <script>
                            $(document).ready(function () {
                            new Morris.Area({
                             element : 'water_graph',
                             data:[<?php echo $chart_data; ?>],
                             xkey:'period',
                             ykeys:['water_level'],
                             labels:['water level'],
                             hideHover:'auto',
                              pointSize: 3,
                             fillOpacity: 0,
                             pointStrokeColors: ['#2cbfb7', '#f7750a', '#c0d0d6'],
                             behaveLikeLine: true,
                             gridLineColor: '#eeeeee',
                             lineWidth: 2,
                             lineColors: ['#2cbfb7', '#f7750a', '#c0d0d6'],
                             resize: true,
                              gridIntegers: true,
                             goals: [10,50],
                             //goalLabels: ['50', '10'],
                             goalTextSize: 5,
                             goalStrokeWidth: 1,
                             goalLineColors: ["red", "green"],
                             ymax: 100,
                             ymin: 0,
                             postUnits: '%',
                             gridTextSize: 'auto'

                            });
                            });
                            </script>
                            <ul class="ct-legend"><li class="ct-series-0" data-legend="0">Water Level</li>
                        
                        </div>
                    </div>

<script src="assets/bundles/libscripts.bundle.js"></script>    
<script src="assets/bundles/vendorscripts.bundle.js"></script>

<script src="assets/bundles/chartist.bundle.js"></script>

<script src="assets/bundles/mainscripts.bundle.js"></script>
<script src="assets/js/pages/tables/jquery-datatable.js"></script>
<script src="assets/js/index.js"></script>
<script src="assets/js/pages/charts/sparklinegraph.js"></script>
<script src="assets/bundles/morrisscripts.bundle.js"></script> <!-- Morris Plugin Js --> 

<script src="assets/js/pages/charts/morris.js"></script>

Javascript task – how do I create my own function with more constants [closed]

could someone help me with my javascript task? You need to download this library from github: https://github.com/Czechitas-podklady-WEB/cviceni-dovednosti

And this is the task:
Create a repository from the exercise-skills template above. In the repository, you will find source files for a page with three sliders. These sliders represent skill levels in different areas.

Add a JavaScript program to the page that, using the prompt function, asks the user to express their skill level in each displayed skill as a number from 0 to 100. The program will then set the sliders on the page to the corresponding length and values based on the numbers entered by the user.

At the beginning of your program, create a function called updateSkill that takes two inputs: a string representing the id of the element and a number between 0 and 100. When called, this function will set the slider with the specified id to the correct value. Use this function in your code so that you don’t have to write almost identical code three times in a row when setting the sliders.

Thank you very much 🙂

I only managed to find the ids through devtools but have no idea how to create function with 3 different ids,…

How can i solve image loading issue in github?

I am not able to get the images, its loading slow after hosting into the GitHub repository. even though the images are compressed and in .Png format (images are changing with morse code audio but after uploading to GitHub its loading slow) I want images to load quickly. how can I do that?

uploaded source file, I was expecting quick display of images.

Send Message to multiple users through Whatsapp API

  • pulling user info from database
  • puting it into loop to send message
  • its giving a bad request error after sending message to the first user.
  • the number format is [countrycode][phone number]
  • using axios to make request to the cloud api
const sendBrodcastAnnouncemntToAll = asyncHandler(async (req, res) => {
    const users = await User.find()

    if (users) {
        for (let index = 0; index < users.length; index++) {
            try {
                const config = {
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Bearer ${process.env.UserAccessToken}`,
                        'Accept-Encoding': 'gzip, deflate, br',
                        Accept: '*/*',
                    },
                }

                const { data } = await axios.post(
                    `https://graph.facebook.com/${process.env.Version}/${process.env.PhoneNumberID}/messages`,
                    {
                        messaging_product: 'whatsapp',
                        to: users[index].phoneNumber,
                        type: 'template',
                        template: {
                            .......
                        },
                    },
                    config
                )
                console.log(data)
            } catch (error) {
                res.status(404)
                console.log(error)
                throw new Error('Something went wrong')
            }
        }

        res.status(200).json({ message: 'Brocasted Successfully' })
    } else {
        res.status(404)
        throw new Error('Users Not Found')
    }
})

its sending message to the first user but giving error after that

Pusher channel in React Native + Redux does not use updated state

I’m using pusher-websocket-react-native to create a real-time chat for a mobile application on Expo.

I noticed that whenever I subscribe to a presence channel, it maintains its own state which means that when a state change occurs in Redux store, the channel’s onEvent does not use the latest value.

const {
  selectedChatRoom, // <--- When a state change occurs here...
  // ...
} = useSelector(state => state.chat, shallowEqual);

useEffect(() => {
  console.log(selectedChatRoom); // <--- This one uses new value
}, [selectedChatRoom]}

// ...

const onEvent = (event) => {
  switch (event.eventName) {
    case bindingKeys.chat.message:
      onMessageReceived(event);
      break;
    default:
      break;
  }
};

const onMessageReceived = (event) => {
  // ...
  const chatRoomId = event.data.chatRoomId;
  const isChatRoomOpen = selectedChatRoom?._id === chatRoomId; // <--- This one maintains old value
  // ...
};

Currently, I’m handling this issue by unsubscribing and then subscribing again (based on this thread, but there is no unbind and bind for Pusher in React Native) to update the state but I don’t think this is a good solution. Does anyone know of any other solution I could try? There does not seem to be many reference on this issue for React Native.

// Current solution
const resubscribeToChannels = async () => {
  if (selectedChatRoom?._id === undefined) return;
  await pusher
    .unsubscribe({
      channelName: `presence-${selectedChatRoom?._id}`,
    })
    .then(async () => {
      await pusher.subscribe({
        channelName: `presence-${selectedChatRoom?._id}`,
        onEvent, // <--- I believe this rebinds the event to the current state 
                 //      but will maintain this state until another re-subscription
      });
    }
  );
};

useEffect(() => {
  resubscribeToChannels();
}, [selectedChatRoom]);

Vuetify VDatePicker menu bug

I have a project (vue2 + vuetify2) with a component v date picker, which attribute active picker = “YEAR” and a list of years from 2000 to 2100, the problem is that sometimes the component opens on the selected year, and sometimes scroll up and the last years are already displayed (2100, 2099, 2098…), how do I fix that always when opening this component shows the current year?

<v-menu
      v-model="menu"
      :close-on-content-click="false"
      offset-y
      transition="scale-transition"
      min-width="290"
    >
      <template v-slot:activator="{ on, attrs }">
        <div v-if="$slots.activator" v-bind="attrs" v-on="on">
          <slot name="activator"></slot>
        </div>
        <v-card v-else flat width="100%">
          <v-text-field
            :disabled="disabled"
            :outlined="outlined"
            :dense="dense"
            :filled="filled"
            :rules="[...rules]"
            v-bind="attrs"
            v-on="on"
            :value="getFormattedTime(date)"
            :hide-details="hideDetails"
            :label="label"
            placeholder="placeholder"
            :error-messages="errorMessages"
            prepend-inner-icon="mdi-calendar"
            clearable
            @click:clear="clearDate()"
            readonly
          >
            <template v-slot:append>
              <v-icon class="pr-2">
                mdi-menu-down
              </v-icon>
            </template>
          </v-text-field>
        </v-card>
      </template>
      <v-card width="290">
        <v-card-text class="pa-0">
          <v-date-picker
            v-model="date"
            color="primary"
            no-title
            :disabled="disabled"
            :min="min"
            @click:date="changeData"
            :max="max"
            :active-picker.sync="activePicker"
            first-day-of-week="1"
            :readonly="readonly"
            :value="defaultValue"
          ></v-date-picker>
        </v-card-text>
      </v-card>
    </v-menu>
props: {
    value: {
      required: false,
      type: String
    },
    label: {
      required: false,
      default: "",
      type: String
    },
    min: {
      required: false,
      default: new Date("1970-01-01").toISOString(),
      type: String
    },
    max: {
      required: false,
      default: new Date("2100-01-01").toISOString(),
      type: String
    },
    hideDetails: {
      required: false,
      default: false,
      type: Boolean
    },
    disabled: {
      required: false,
      default: false,
      type: Boolean
    },
    outlined: {
      required: false,
      default: false,
      type: Boolean
    },
    dense: {
      required: false,
      default: false,
      type: Boolean
    },
    filled: {
      required: false,
      default: false,
      type: Boolean
    },
    errorMessages: {
      required: false,
      default: null,
      type: [String, Number, Array, Boolean]
    },
    rules: {
      required: false,
      default: () => [],
      type: Array
    },
    yearSelect: {
      required: false,
      default: true,
      type: Boolean
    },
    readonly: {
      required: false,
      default: false,
      type: Boolean
    }
  },

  data: () => ({
    activePicker: null,
    date: "",
    menu: false,
    defaultValue: null
  }),

  watch: {
    value: {
      immediate: true,
      handler() {
        if (this.value) {
          this.date = this.value;
        } else {
          this.date = "";
          this.defaultValue = new Date();
        }
      }
    },
    menu(val) {
      val && this.$nextTick(() => (this.activePicker = 'YEAR'))
    }
  },

  methods: {
    changeData() {
      this.$emit("input", this.date);
      this.menu = false;
    },
    close() {
      this.date = "";
      this.changeData();
      this.menu = false;
    },
    toggle() {
      this.menu = !this.menu;
    },
    clearDate() {
      this.date = "";
      this.changeData();
    },
    getFormattedTime(date) {
      const newDate = new Date(date);

      if (newDate) {
        return newDate;
      }
    }
  }

Reproduction link: codepen

I tried adding a value attribute with a value of new Date(), but the problem still remains

Getting a syntax error when attempting to remove an item from Selectize input

Whenever i try to remove an item from Selectize input, i get the following error in the console:

index.js:12 Uncaught Error: Syntax error, unrecognized expression: option[value="{"id":"allCustomers","type":"keyword"}"]
    at Sizzle.error (index.js:12:1)
    at Sizzle.tokenize (index.js:12:1)
    at Sizzle.select (index.js:12:1)
    at Function.Sizzle [as find] (index.js:12:1)
    at jQuery.fn.init.find (index.js:12:1)
    at Selectize.updateOriginalInput (<anonymous>:31913:16)
    at Selectize.removeItem (<anonymous>:31720:9)
    at HTMLDivElement.<anonymous> (<anonymous>:34943:33)
    at HTMLDocument.dispatch (index.js:12:1)
    at elemData.handle (index.js:12:1)

The code i use for removing the item looks like this:

    $(document).on('click', 'div.selectize-input div.item', function (e) {
            var select = $('#customerDropdownMailform').selectize();
            var selectedValue = $(this).attr("data-value");
            select[0].selectize.removeItem(selectedValue);
            select[0].selectize.refreshItems();
            select[0].selectize.refreshOptions();
        });

Anyone got any ideas as to why it breaks? The examples i find online recommend doing the above mentioned solution for removing the item.

I suspect that maybe the data-value is the culprit. I have tried modyfing it so that it is an int or json stringified, but i get the same syntax error.

Popup opening when clicking on thumbnails on the site liftprogress.it

Good evening,

we are having problems activating the opening of the popup when clicking on the thumbnails, which are

displayed, as you can see for example in the following link and in the following screenshot:

https://www.liftprogress.it/it/prodotto/sinoboom-0608me-1932me/

enter image description here

Could you tell us how to activate the functionality indicated in question, taking into consideration that

the WordPress platform is installed on the site liftprogress.it?

Thank you

I expect a solution to this problem

Refused to connect to ‘https://ipapi.co/json/’ because it violates the following Content Security Policy directive

While adding to get the public ip address of client system on Javascript, I’m getting this error on the console.

Error meesage as shown below.

Any assistance to solve this issue would be appreciated. Thanks

I tried with adding this below mentioned piece of code to get the public Ip.

$(document).ready(function () {

    alert(3);
    $.ajax({
        url: 'http://checkip.dyndns.org/?format=json',
        datatype: 'json',
        method: 'get',
        success: function (data) {
            console.log(data.ip);
            alert(data.ip);
        }
    });
})

I’m expecting to get an IP without any error which was attached above.