Successful ajax call but data received is not being updated in the database

I have the following js ajax call code, which creates a js object in the form of {1: '440', 5: '115'} and passes it via ajax to a php function:

        function saveCredits() {
          // Define an object to store the user IDs and credit values
          var credits = {};
          
          // Select the last column of each row in the table
          $("table tbody tr").each(function() {
            var userId = $(this).find("td:first-child").text();
            var creditValue = $(this).find("td:last-child input").val();
            credits[userId] = creditValue;
          });
          
          // Log the credits object to the console
          console.log(credits);
          var credits = JSON.stringify(credits);
          
          // Send the credits object to the server via AJAX
          $.ajax({
            url: "'.$adminAjaxUrl.'",
             data: {
                        action: "update_usermeta",
                        credits: credits
                    },
            method: "POST",
            success: function(response) {
              console.log("Credits saved successfully");
            },
            error: function(xhr, status, error) {
              console.log("Error saving credits: " + error);
            }
          });
        };

and the following PHP ajax code:

function update_usermeta_callback() {
    // Get the credits data sent via POST
    $credits = $_POST['credits'];
    $credits = json_decode($credits);
    
    // Loop through the credits data and update the user meta values
    foreach ( $credits as $user_id => $credit_value ) {
        // Update the user meta value for 'ai_anna_credit'
        update_user_meta( $user_id, 'ai_anna_credit', $credit_value );
    }

    // Send a success response
    $response = array( 'success' => true );
    echo json_encode( $response );
}

The ajax returns a success message but the database doesn’t update.

I believe that the JS object is correctly stringified and then decoded in the PHP, but why is the PHP function not correctly updating the dB?

Datatable Jquery sending wrong Draw value

I have Jquery Datatable that uses server side pagination and it only works for forward selection of pagination numbers,

Which means if the dataset is having 4 pages I can navigate only one by one sequentially, If I press page 3 after page 1 results shows for the data related to 2nd page.

as per my understanding jquery code is sending incorrect draw value, But i don’t know how to change it.

this is the jquery code,


    $("#ReportTable2").DataTable({
                "processing": true,
                "serverSide": true,
                "filter": false,
                "searching": false,
                "lengthChange": false,
                "pageLength": 5,
                "lengthMenu": [10, 25, 50, 100],
                "aoColumnDefs": [
                    { "bVisible": false, "aTargets": [0, 6] }
                ],
                "ajax": {
                    "url": "/Admin/RptVisitorNotLoggedOut",
                    "type": "POST",
                    "datatype": "json",
                },
                "columnDefs": [
                    {
                        "visible": false,
                        "targets": -1,
                    }
                ],
                "columns": [
                    { "data": "VisitorInID", "name": "VisitorIn ID", "autoWidth": true },
                    { "data": "SiteName", "name": "Site Name", "autoWidth": true },
                    { "data": "RFIDCardNumber", "name": "RFID", "autoWidth": true },
                    { "data": "VisitorName", "name": "Visitor Name", "autoWidth": true },
                    { "data": "IDNumber", "name": "ID Number", "autoWidth": true },
                    { "data": "ContactNumber", "name": "Contact Number", "autoWidth": true },
                    { "data": "Company", "name": "Company", "autoWidth": true },
                    { "data": "PurposeOfVisit", "name": "Purpose Of Visit", "autoWidth": true },
                    { "data": "ResposiblePersonName", "name": "Resposible Person Name", "autoWidth": true },
    
                ]
            });

server side code,

                int siteID = (Session["SiteID"] != null) ? (int)Session["SiteID"] : 0;
                if (siteID == 0)
                {
                    siteID = (int)this.DetermineSiteID();
                    Session["SiteID"] = siteID;
                }
                // new Code for pagination included

                var draw = Request.Form["draw"].FirstOrDefault().ToString();
                //var start = Request.Form["start"].FirstOrDefault().ToString();
                var length = Request.Form["length"].FirstOrDefault().ToString();
                var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault().ToString();
                var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault().ToString();
                var searchValue = Request.Form["search[value]"].FirstOrDefault().ToString();
                int pageSize = length != null ? Convert.ToInt32(length) : 0;
                int skip = 0;
                int recordsTotal = 0;

                var userData = rule.GetVisitorSummerybyDates(DateTime.Parse(toDate), DateTime.Parse(fromDate), siteID.ToString());

                if (!string.IsNullOrEmpty(searchValue) && searchValue != "")
                {
                    userData = (List<VisitorInOutDetails>)userData.Where(
                                                   m => m.IDNumber.Contains(searchValue)
                                                || m.ContactNumber.Contains(searchValue)
                                                || m.Company.Contains(searchValue));
                }

                recordsTotal = userData.Count();
                skip = (Convert.ToInt32(pageSize) * (Convert.ToInt32(draw) - 1));
                var data = userData.Skip(skip).Take(pageSize).ToList();

                var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };

                return Json(jsonData);

Any idea on how to change it would much appreciated.

How can I fire an event when resize is done?

I’m trying to adjust the margin of the footer so it goes 100% across the window (main element has a max-width: 960px;) and the footer needs to go all the way to the edges of the window when its wider than 960px.

It works fine on page load, but resize event is buggy:

let resizeTimeout = null;

function fixJoin(e){
    const el = document.querySelector('.join');
    const pageWidth = window.innerWidth;

    el.style.width = `${pageWidth}px`;
    el.style.marginLeft = `-${el.offsetLeft}px`;
}

window.addEventListener('DOMContentLoaded', fixJoin);
window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
        fixJoin();
    }, 50)
});

Thingsboard IoT Payload Decoder Unit/Integration Tests for TBEL

At our Company we have a running Thingsboard PE Instance.
Just recently, we started to migrate all our Rule Chains, Converters and Scripts from Nashorn JS to TBEL.
We have a lot of devices from different manufacturers. They all provide us Payload Decoders in JS Code, so we could basically just copy+paste them in the past. But now, that we want to use TBEL, we need to basically re-code them ourselfs. This causes a lot of insecurity and we want to setup a test environment, that monitors all changes made to certain Decoders and runs Unit+Integration Tests.
We use the VCS Auto-Commit Feature from Thingsboard, so we could just put some Test-Framework Code in our Git Repository and build a CI/CD Pipeline inside Git to automatically test every commit.

My Question: Does somebody has experience with Testing Payload Decoders written in TBEL? Maybe a clever Strategy we could use? Or in General, how do you test your self-written Payload Decoders or other Thingsboard Rule Chains in General?

Thanks for any help

I just want some tip-off.

Error while trying to render a vid file from firebase using mongoDB and ejs

I am trying to make something similar to youtube clone app using Node, express, mongoose and ejs. When trying to use res.render() to send results to the iframe in the ejs file, im getting an error.

Here is the code for both the ejs and server files:-

index.js:-


>! 
>! `const express = require('express');
>! const mongoose = require('mongoose');
>! const bodyParser = require('body-parser');
>! const ejs = require('ejs');
>! 
>! const app = express();
>! 
>! app.use(bodyParser.urlencoded({
>! extended: true
>! }));
>! app.use(express.static("public"));
>! app.set('view engine', 'ejs');
>! 
>! mongoose.connect("mongodb://127.0.0.1:27017/VidDb");
>! 
>! const userSchema = new mongoose.Schema({
>! name:{
>! type:String,
>! required:true,
>! unique:true
>!   },
>! email:{
>! type:String,
>! required:true,
>! unique:true
>!   },
>! password:{
>! type:String,
>! required:true,
>!   },
>! image:{
>! type:String,
>!   },
>! },{timestamps:true});
>! 
>! const User = mongoose.model("User",userSchema);
>! 
>! const vidSchema = new mongoose.Schema({
>! vidName:{
>! type:String,
>! required:true,
>! unique:true
>!   },
>! vidThumb:{
>! type:String,
>! required:true,
>! unique:true
>!   },
>! vidLink:{
>! type:String,
>! required:true,
>! unique:true
>!   },
>! likes:{
>! type:Number,
>! default:0
>!   },
>! views:{
>! type:Number,
>! default:0
>!   },
>! });
>! 
>! const Vids = mongoose.model("Vid",vidSchema);
>! 
>! app.get("/",function(req,res){
>! Vids.find().then(function(vids,err){
>! res.render("index",{
>! videos:vids
>!       });
>!   });
>! });
>! 
>! app.get("/vids/:vidId",function(req,res){
>! const videoID = req.params.vidId;
>! Vids.findById(videoID).then(vid => {
>! res.render("vid",{
>! video:vid
>!     });
>!   });
>! });
>! 
>! app.listen(3000,function(){
>! console.log("Server Started");
>! });
>! 
>! `

vid.ejs:-


`<%- include('partials/header'); -%>
<!-- <video
    id="my-video"
    class="video-js"
    controls
    preload="auto"
    width="640"
    height="264"
    poster="MY_VIDEO_POSTER.jpg"
    data-setup="{}"
  >
    <source src="<%= video.vidLink %>" type="video/mp4" />
    <p class="vjs-no-js">
      To view this video please enable JavaScript, and consider upgrading to a
      web browser that
      <a href="https://videojs.com/html5-video-support/" target="_blank"
        >supports HTML5 video</a
      >
    </p>
  </video> -->



<iframe width="1020" height="815" src= "<%= video.vidLink %>" ></iframe>
<script src="https://vjs.zencdn.net/8.0.4/video.min.js"></script>
<%- include('partials/footer'); -%>

`

I get the link when console logging but when trying to send the link to the ejs file, it doesnt work anymore.

What function does “return -1;” perform?

This program is designed to search for a car in the parking lot.

function findCarInLot(car) {
  for (var i = 0; i < lot.length; i++) {
    if (car === lot[i]) {
      return i;
    }
  }
 **return -1;**
}

var chevy = {
  make: "chevy",
};
var taxi = {
  make: "taxi",
};
var fiat = {
  make: "fiat",
};

var fiat2 = {
  make: "fiat2",
};

var lot = [chevy, taxi, fiat, fiat2];
var loc1 = findCarInLot(fiat2);
var loc2 = findCarInLot(taxi);
var loc3 = findCarInLot(chevy);
var loc4 = findCarInLot(fiat);

The function iterates through the array elements and returns the sequence number of the array element when the condition returns “true”.
I don’t understand why the “return” operator is assigned the value “-1” and not some other and what it is needed for.

I created a few more objects without putting them in the “lot[]” array. And when I passed them to the function as an argument, it returned “-1”.
What condition must be met for “return -1;” to work and can “-1” be replaced with “alert(‘There is no such car in the parking lot!’);” or “false” to preserve the logic?

Next 13 error node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js

I need help! My application on next throws errors when the serialize function is used

error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString
error - URI malformed

1

2

Пробовал почти все, не могу понять где искать ошибку. Мне кажется, что возможно это баг next13

Get Name of object’s property type

Let say I have this class and object from it

export class Person {
   constructor(name: string, age: number) { 
      this.name = name;
      this.age = age;
   }
   public name: string,
   public age: number
} 

const person = new Person();

Is there any way to get its properties’ types like:

console.log(person.age.type) ????? => 'number' 

Error in Javascript/node: flatMap not working properly [duplicate]

I was writing about version news and I came across something that I think is a bug in javascript.
The code:

const arrValor = [1,2,3,4,5,,6,[7,8,9,[10,11,[111,222]],12],13,14];
//console.log("Original :",arrValor);
console.log("mas s  :",arrValor.flatMap(val=>val+"s"));

the result:

mas s  : [
  '1s',
  '2s',
  '3s',
  '4s',
  '5s',
  '6s',
  '7,8,9,10,11,111,222,12s',
  '13s',
  '14s'
]

The detail is in the 12, since it is at the same level as the 7,8,9 and to those it does not add the s… Why to the 12?

Test with Node v18.13.0 en windows 10Pro 21H2

I expected the layered application to be homogeneous, and I have tried mixed numeric and alphabetic arrays, but it always behaves the same

how can I add my product2 in my cart using javascript

This is my code and I cant add another product to my cart, it only works to my product 1

<script>
    var Add = document.getElementById("Add");
    
    var product = document.getElementById("products");
    var cart = document.getElementById("cart");
    
    
    Add.addEventListener("click", ()=>{
        
        var clone = product.cloneNode(true);
        var dup = cart.appendChild(clone);
    })
    
    
    
</script>

I want to add my products to my cart`

How to convert a header row into typescript array in cypress which return the array

Let’s say I am iterating over the header of a ag-grid and want to save it a array in typescript enter image description here

I can easily get text of each column in cypress through

cy.get("#myGrid").find('.ag-header-cell').invoke('text').then((text)=>{
var headArr:Array<String>;
headArr = text.trim()
})

But this is not creating an array and also wanted to know how to return this array and assign it to a variable

Google AppScript / Javascript – this.ClassName = class ClassName() required to access library class in namespace

AppScript v8 doesn’t support ES6 modules. To import other modules you have to load them as AppScript libraries. Once loaded you access properties through library loaded namespace e.g. you might have a math isEven() function in a math namespace in your Utils library. When you import it to the Utils library you would then access it as Utils.math.isEven(). Library root level root function work fine as well e..g if you had initUtils() you could access it with Utils.initUtils()

However when it is not a function, like a class I have to assign it to a namespace before I can access the library property. For example class ExampleClass {} off globalThis cannot be found once imported as a library, however this.ExampleClass = class ExampleClass {} fixes the problem. Example below. Is this Javascript or AppScript?

Example: AppScript Library: SheetServices

    class ClassWillFail {
        constructor(name) {
            name = name || "TemplateServices"
        }
        // ... remove for brevity sake
    }

    this.ClassWillSucceed = class ClassWillSucceed {
        constructor(name) {
            name = name || "TemplateServices"
        }
        // ... remove for brevity sake
    }

AppExample AppScript with imported library SheetServices

function initApp() {

    console.log(new SheetServices.ClassWillSucceed())
    // results in: ClassWillSucceed {name: "TemplateServices"}

    console.log(new SheetServices.ClassWillFail())
    // results in error: TypeError: SheetServices.ClassWillFail is not a constructor or undefined
}

initApp()

This also works

this.services = {
    ...this.services, ...{
      ClassWillSucceed: class ClassWillSucceed {
        constructor(name) {
            name = name || "TemplateServices"
        }
      }
    }
  };

How to change the value of the parameter in the closure [duplicate]

function handleChange(a) {
  return new Promise(resolve => {
    a = '4566'
    
    resolve()
  })
}

const init = async function () {
  let a = '123'

  await handleChange(a)
  
  console.log(a) // 123
}

Please checkout this function.
The handleChange is a closure function that return new Promise.
Can you tell What can I do if I want to change the ‘a’ value.And I don’t want to return it it the Promise like resolve(a). Thanks.

NextJS ReactJS mobile deployment

Although the deployed site from Vercel act normal on web (computer and laptop). The same site fails while browsing on mobile.

The issue happens after the index page loads and error is given below.


A problem repeatedly occurred on www.example.com

I am at odds since there is no change in code.

What steps I can take to resolve the issue.