How do I get a specific key value from JSON object

This is my first time using any kind of APIs, and I’m just starting out in JS. I want to get the status of a server within a server hosting panel, to do this I need to log in (API/Core/Login), get a the value of a key called sessionID, then send that value to /API/Core/GetUpdates to get a response. When trying to pass the sessionID to GetUpdates, it sends undefined instead of the sessionID, I’m guessing I’m doing something wrong when trying to reference the key value. Here’s my code:

var loginurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/Login";

var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", loginurl);

loginRequest.setRequestHeader("Accept", "text/javascript");
loginRequest.setRequestHeader("Content-Type", "application/json");

loginRequest.onreadystatechange = function() {
  if (loginRequest.readyState === 4) {
    console.log(loginRequest.status);
    console.log(loginRequest.responseText);
  }
};

var logindata = '{"username":"API", "password":"password", "token":"", "rememberMe":"true"}';

loginRequest.send(logindata);

var statusurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/GetUpdates";

var statusreq = new XMLHttpRequest();
statusreq.open("POST", statusurl);

statusreq.setRequestHeader("Accept", "text/javascript");
statusreq.setRequestHeader("Content-Type", "application/json");

statusreq.onreadystatechange = function() {
  if (statusreq.readyState === 4) {
    console.log(statusreq.status);
    console.log(statusreq.responseText);
  }
};

var statusdata = `{"SESSIONID":"${loginRequest.responseText.sessionID}"}`; // Line I'm having problems with

statusreq.send(statusdata);

console.log(loginRequest.responseText.sessionID)

Here’s the response of /API/Core/Login

{"success":true,"permissions":[],"sessionID":"1d212b7a-a54d-4e91-abde-9e1f7b0e03f2","rememberMeToken":"5df7cf99-15f5-4e01-b804-6e33a65bd6d8","userInfo":{"ID":"034f33ba-3bca-47c7-922a-7a0e7bebd3fd","Username":"API","IsTwoFactorEnabled":false,"Disabled":false,"LastLogin":"/Date(1639944571884)/","GravatarHash":"8a5da52ed126447d359e70c05721a8aa","IsLDAPUser":false},"result":10}

Any help would be greatly appreciated, I’ve been stuck on this for awhile.

JQuery TablEdit add editable column dropdown option from database

I have a problem with TableEdit

This is in the documentation I read:

// Example #2
columns: {
    // Column used to identify table row.
    // [column_index, input_name]
    identifier: [0, 'id'],
    // Columns to transform in editable cells.
    // [[column_index, input_name], [column_index, input_name, select_options]]
    editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}

In the editable key, the second array contains a json-like string that renders as a dropdown list when I press the edit button.

My question is, how do I make that json-like string dynamically?

I have an ajax request that returns a list of departments. I want to pass those departments into that editable column.

Change website when redirecting from another page

I have a main page that redirects to another page called example.com

the code of the main page is:

 <! DOCTYPE html>
 <html>
 <body>

 <h2> Redirect to a Webpage </h2>
 <p> The replace () method replaces the current document with a new one: </p>

 <button onclick = "myFunction ()"> Replace document </button>

 <script>
 function myFunction () {
   location.replace ("https://www.example.com")
 }
 </script>

 </body>
 </html>

example.com shows “Original Webpage” if you enter directly
the code for example.com is:

 <! DOCTYPE html>
 <html>
 <body>

 <h2> Original Webpage </h2>
 </body>
 </html>

I want that when redirecting from the main page to example.com, example.com shows “modified page”.
then you should change <h2> Original Webpage </h2> from main page before entering example.com

React and Laravel with Sanctum authentication setup can’t read cookie?

I currently have a React Application spawned via CRA running on http://paulsamazinglocalhost.com:3000

package json as follows:

"start": "HOST=paulsamazinglocalhost.com PORT=3000 react-scripts start",

I’m currently (trying) to talk to a Laravel API running on port 8000 specifically

http://api.paulsamazinglocalhost.com:8000

spawned via laravel as follows:

php artisan serve --port 8000 --host api.paulsamazinglocalhost.com

Now, “what does the Laravel CORS configuration look like” well here it is in all its glory:

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

and “what about the sanctum configuration in your environment file?” here you go:

SESSION_DRIVER=cookie
SESSION_DOMAIN=.paulsamazinglocalhost.com:8000
SANCTUM_STATEFUL_DOMAINS=paulsamazinglocalhost.com:3000

What about the API Kernel:

 'api' => [
            FruitcakeCorsHandleCors::class,
            LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

So to clarify, the api runs on http://api.paulsamazinglocalhost.com (Laravel)
and the React app on http://paulsamazinglocalhost.com

To get the party started, and to try and actually authenticated against my POS API – I hit this first (via FETCH – not AXIOS) – I’m using React Toolkit Query, so here is the request:

GET: http://api.paulsamazinglocalhost.com:8000/api/sanctum/csrf-cookie

my next request is:

Route::post('/auth/login', 'AppHttpControllersApiAuthController@login');

This currently returns a 419 expired message. We sounds to me like we haven’t set something on the request, you know like some beautiful XSRF cookie token or something.

See here: https://laravel.com/docs/8.x/sanctum#spa-authenticating

The documentation states:

This token should then be passed in an X-XSRF-TOKEN header on subsequent requests.

well, yes that’s great, my problem appears to be reading it, becomes the response is completely empty, and I therefore assume that I need to read a cookie, see my lump of react toolkit query code below.

Currently I can’t read any cookies to add them to any subsequent request. Presumably because of some cross domain cookie problem? Not sure.

var getCookies = function(){
  var pairs = document.cookie.split(";");
  console.log(document.cookie)
  var cookies = {};
  for (var i=0; i<pairs.length; i++){
    var pair = pairs[i].split("=");
    cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
    console.log(pair);

  }
  return cookies;
}


// Define a service using a base URL and expected endpoints
export const authApi = createApi({
  reducerPath: 'authApi',
  baseQuery: fetchBaseQuery({ 
    baseUrl: Endpoint.URL + 'auth',
    prepareHeaders: (headers, { getState }) => {
      // By default, if we have a token in the store, let's use that for authenticated requests
      var myCookies = getCookies();
      const cookieToken = Cookies.get('XSRF-TOKEN');
      const token = cookieToken || (getState() as RootState).authApi.token;
      if (token) {
        alert(cookieToken);
        headers.set('X-XSRF-TOKEN', `${token || cookieToken}`)
      }
      return headers;
    },
 }),

Long story short. Can’t read cookies from a sanctum pre auth request, not sure why, any detail on how to authenticate using Sanctum and React Toolkit Query appreciated.

Cannot Install Appcelerator CLI or SDK

I am trying to install Appcelerator CLI and SDK, but I get errors all the time. I´m using Windows.
When I do npm install appcelerator -g, in cmd, (run as admin) I get:

npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142

changed 122 packages, and audited 123 packages in 9s

4 packages are looking for funding
run `npm fund` for details

2 high severity vulnerabilities

To address all issues (including breaking changes), run:
npm audit fix --force

Run `npm audit` for details.

And, when I run appc, in cmd (run as admin) I get program.allowUnknownOption is not a function.

When I install the extension in VSCode, as detailed on VSCode official marketplace and Titanium WebSite, and the click “Install Tooling”, this Titanium SDK Titanium Updates: Installing Titanium SDK: 10.1.1.GA (1/1) simply doesn´t install.

Please, someone help me install the CLI and the Titanium SDK. (I know I have to use it in VSCode).

Move the folder from one directory to another based on google sheet value (apps script)

I want the folders with all the files or subfolders in them to be moved from one directory/folder to another based on the value in the google sheet. After some research, I have found some snippets that may not do exactly what I want like keep the folder shared after it moves but it does create a copy of the same folder with the same name in another directory and move files there. I am further struggling to make it as per my needs like moving the folder based on values in the spreadsheet.

Here is the snippet that makes a copy of the folder in another directory and moves the files there.

// main function (recursive)
function migrateFolderToSharedDrive(folder,parent) {
  var copiedFolder = 
  parent.createFolder(folder.getName()).setDescription('previous Id: 
  '+folder.getId());
  Logger.log('Folder created with id %s in parent 
  %s',copiedFolder.getId(),parent.getId());

  // move files
  var files = folder.getFiles();
  while (files.hasNext()) {
  Logger.log('File with id %s moved to %s', 
  files.next().moveTo(copiedFolder).getId(), copiedFolder.getId())
  }



// recurse any subfolders 
  var childfolders = folder.getFolders();
  while (childfolders.hasNext()) {
  var child = childfolders.next();
  Logger.log('processing subfolder %s',child.getId());

  migrateFolderToSharedDrive(child,copiedFolder); // recursive call
 }
}

Here is the snippet that I tried on my end to make the function run as the values change in the spreadsheet. I tried to do it on onEdit earlier but it doesn’t work with that(OnEdit requires authorization and DriveApp don’t work with that). As I am new to coding, I know the function I have made has many bugs and is not working but I am adding it here just to show what I am struggling to achieve.

function movefolder(){
 const inactive_folder = 
 DriveApp.getFileById('1_hBkktH0Alzx06XS0Hu2tI0MSQ_SffKw');
 const active_folder = 
 DriveApp.getFolderById('13uon5guBduiA0gCKiLjl9ElOgek9CiU6');
 var lastRow = SS.getSheetByName("Clients").getLastRow();
 var statusrange = SS.getSheetByName("Clients").getRange("A2:M" & lastRow);
 var statusvalue = statusrange.getValues()



// look into the status of every row
 for (i = 0, l = statusvalue.length; i < l; i++){
  var client_name = statusvalue[i][1];    // get client name from 2nd column
  var client_folder_name = active_folder.getFoldersByName(client_name)    //Get 
  folder name from active folder directory



// Move the folder to inactive directory if the cell value in column 1 is 
  inactive and folder exists in active folder directory
   if (statusvalue[i][0] === 'inactive' && client_name === client_folder_name){
     var folder_id = DriveApp.getFolderById(client_folder_name)   //Get folder 
     id from folder name

     migrateFolderToSharedDrive(folder_id,inactive_folder); // copy folders and 
     move files

     folder_id.setTrashed(true); // trash original folder

     // update the the new url to the 11th column in the sheet
     statusvalue[i][11].setValue([migrateFolderToSharedDrive.copiedFolder]);
  
   }
   else{
    // Move the folder to active directory if the cell value is active and 
    folder exists in inactive folder
    if (statusvalue[i][0] === 'active' && client_name === ia_client_folder_name) 
    {
      var ia_client_folder_name = inactive_folder.getFoldersByName(client_name)    
      //Get folder name from inactive folder directory
    
      var ia_folder_id = DriveApp.getFolderById(ia_client_folder_name)   //Get 
      folder id from folder name

      migrateFolderToSharedDrive(ia_folder_id,inactive_folder); // copy folders 
      and move files

      folder.setTrashed(true); // trash original folder

      // update the the new url to the 11th column in the sheet
      statusvalue[i][11].setValue([[migrateFolderToSharedDrive.copiedFolder]]);
     }
    }
   }
  }

Any help would be highly appreciated. Thank you.

does “onplay” have a delay?

When calling the play() function, I can see that there’s a noticeable delay of 0.0~0.5 seconds before it actually starts playing.

I am facing some problems when using the following event listener

media.addEventListener(
    "play",
    function(){
        toggle_class(button[0], true);
        
        // compute animations for seekbar
        time_to_compute = media.duration - media.currentTime;
        progress.style = "transition: width linear " + time_to_compute + "s; width:100%;";
    }
);

Instead of changing the bar’s position on time change, im changing it once and making it animated using a transition. The problem is that the transition starts BEFORE the video plays (0.0~0.5 seconds). This problem happens in both chrome and firefox.

Is there a javascript event for when the video actually plays?

how do i get imdb_id from api query with JS

i need to get imdb_id by title using tmdb api and add imdb_id into my div on html website
my code is:

<script>
  const settings = {
    async: true,
    crossDomain: true,
    url: "https://api.themoviedb.org/3/search/multi?api_key=98771c266fc9b4e8718a98a7b1232&language=de-DE&query={title}&page=1&include_adult=false",
    method: "GET",
  };

  $.ajax(settings).done(function (data) {
    const settings = {
      async: true,
      crossDomain: true,
      url:
        "https://api.themoviedb.org/3/movie/" +
        data.results[0].id +
        "/external_ids?api_key=987766fc9b4e8718a2a598a7b1232",
      method: "GET",
    };
  });
  
  $.ajax(settings).done(function (data) {
    document.getElementById("imdbdiv").href =
      "https://example.com/?imdb_id=" + data.imdb_id;
  });
</script>

Vue JS: can’t gett array index of JSON data

in my project i have data from JSON API and i wanted to view the index of each data.. for example, below i viewed the floors from array index numbered from 0 to 22 but when it comes to view flats in each floor i couldn’t get the array index, below for floor 0 i have 6 arrays for flats until 22 all have array(6) of flats so i wanted to view them from 0 to 6 for each floor but i couldn’t.
can someone help in this please?

https://i.stack.imgur.com/aWzCj.png

<template>
    <b-card no-body class="bg-default shadow">
  
 <b-table-simple responsive>
  <b-thead>
    <b-tr>
      <b-th sticky-column>flats </b-th>
      <b-th >  //here i want to show the indexes of array(6) in provided image
      
      </b-th>
   
    </b-tr>
  </b-thead>
  <b-tbody >
    <b-tr  v-for="(floor,floor_index) in Building.floors"
              :key="floor_index">
      <b-th sticky-column>{{floor_index}}</b-th> //here i viewed from 0 to 22 floors
      <b-td>Cell</b-td>
 
    </b-tr>
  </b-tbody>
 </b-table-simple>

    </b-card>
    
</template>
<script>
  import projects from './../projects'
  import { Table, TableColumn} from 'element-ui'
  import BuildingsService from "@/services/ApiService"
  export default {
    name: 'light-table',
    components: {

    },
    data() {
      return {
          Flats:[],
          index:0,
          Floors:[],
          Building:[],
         NoOfFloors: [],
        projects,
        currentPage: 1
      };
    },

mounted: function(){
 
      
      BuildingsService.getOneBuilding(`${this.$route.params.id}`).then((response) => {
      this.Building = response.data.response;
 this.NoOfFloors = this.Building.floors;

console.log(this.Building.floors,"single");
   

    });

        BuildingsService.getFlats().then((response) => {
      this.Flats = response.data.response;
 

    });




    
    }
  }
</script>

Next Js Error with Dynamic Pages FUNCTION_INVOCATION_TIMEOUT

I have a page in my next js site (/flats/[id].js) in pages folder

here is my page

import React, { useState, useEffect } from "react";
import styled from "styled-components";

export default function FlatPage() {
  return (
    <Wrapper>
      <Meta title="FlatDetail" />
      <>Hello</>
    </Wrapper>
  );
}

const Wrapper = styled.div`
  padding: 20px;
`;

for some reason I get this error when navigating to the page


This Serverless Function has timed out.

Your connection is working correctly.

Vercel is working correctly.

504: GATEWAY_TIMEOUT
Code: FUNCTION_INVOCATION_TIMEOUT
ID: fra1::kzjbt-1639939593230-a5edd370b414

I have no Idea why the function timed out(nothing much on the page), plus it works fine locally too.

Flexmonster – Cannot format values in first column

I’m trying to configure the following code in order to format the PROFIT column (which is the first one) as a currency.

Right now the values in that column are getting shown as:

1243898
1538192
1921982

But I want them to get shown as:

$1,243,898
$1,538,192
$1,921,982

Here you have a preview…

enter image description here

And below is the code, where you can see I introduced a new format: currency which I tried to use for that first column: PROFIT, but had no success.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.flexmonster.com/flexmonster.js"></script>
<script>
$(function() {
    let pivot = new Flexmonster({
        container: "pivot-container",
        componentFolder: "https://cdn.flexmonster.com/",
        toolbar: false,
        report: {
            data: [
                {
                    "Profit": "1243898",
                    "Following": 81,
                    "Followers": 242,
                },
                {
                    "Profit": "1538192",
                    "Following": 728,
                    "Followers": 2178,
                },
                {
                    "Profit": "1921982",
                    "Following": 4423,
                    "Followers": 12387,
                },
                {
                    "Profit": "1243898",
                    "Following": 63,
                    "Followers": 189,
                },
                {
                    "Profit": "1538192",
                    "Following": 342,
                    "Followers": 931,
                },
                {
                    "Profit": "1538192",
                    "Following": 487,
                    "Followers": 1242,
                },
                {
                    "Profit": "1921982",
                    "Following": 3827,
                    "Followers": 15281,
                },
                {
                    "Profit": "1243898",
                    "Following": 97,
                    "Followers": 279,
                },
                {
                    "Profit": "1538192",
                    "Following": 242,
                    "Followers": 728,
                },
                {
                    "Profit": "1921982",
                    "Following": 4921,
                    "Followers": 12489,
                },
                {
                    "Profit": "1243898",
                    "Following": 69,
                    "Followers": 182,
                },
            ],
            formats: [
                {
                    name: "",
                    thousandsSeparator: " ",
                    decimalSeparator: ".",
                    decimalPlaces: -1,
                    maxDecimalPlaces: -1,
                    maxSymbols: 20,
                    currencySymbol: "",
                    negativeCurrencyFormat: "-$1",
                    positiveCurrencyFormat: "$1",
                    isPercent: "false",
                    nullValue: "",
                    infinityValue: "Infinity",
                    divideByZeroValue: "Infinity",
                    textAlign: "right",
                    beautifyFloatingPoint: true,
                },
                {
                    name: "currency",
                    currencySymbol: "$",
                },
            ],
            slice: {
                rows: [{
                    uniqueName: "Profit",
                    format: "currency",
                }],
                columns: [{
                    uniqueName: "[Measures]",
                }],
                measures: [{
                        uniqueName: "Following",
                    },
                    {
                        uniqueName: "Followers",
                    },
                ],
            },
        },
    });
});
</script>
</head>

<body>
    <div id="pivot-container"></div>
</body>

</html>

Do you have any idea on how can I make this to work?

Here you have a JSFiddle with the code above:

https://jsfiddle.net/tlg265/eo1bkjwy/

Thanks!

multiple url path ways with prox

I’am trying to get my front end to when the 1st proxy returns a 404 response it will try two use the second proxy link and then if that fails finally produce an out put of “error bad pathway” if both fail. Below is what i have at the moment.

function Wordcount()

{

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {   
    
        if (this.readyState == 4 && this.status == 200) {
        var j = JSON.parse(this.response);
        document.getElementById('output').value = j.answer;
        
        
    } 
    
    else {
        document.getElementById('output').value = "error bad pathway";
    }
          
};
let url = proxyURl + "/?text=" + encodeURI(document.getElementById('content').value) + "&route=" + "wordcount";
xhttp.open("GET",url);
        xhttp.send();

}

jQuery .append doesn’t work with $(document).ready

This is a followup to toggleClass of parent div not changing with onClick

In my HTML layout, I’ve found that I need to generate the div #filters after the records, not before, because I need to use PHP to build the buttons for each state. This gave me the idea to use jQuery .append to move the #filters to the #move-filters-here above the records. But after I filter on a state, the filters appear below the records and .append doesn’t work to move the #filters to #move-filters-here above the records.

Is .append not working with (document).ready?

Is there a different way to get .append to move the #filters?

Does .append need to “fire” again after the Onclick function?

Fiddle: https://jsfiddle.net/j3semt6h/10/

$(document).ready(function(){

$("#filters").append("#move-filters-here");

$('.state-button').on('click', function() {

  let _this = $(this);

  if (!_this.hasClass('active')) {

    $('.state-button.active, .record.active').removeClass('active');
    $('[data-state=' + _this.data('state') + ']').addClass('active');

  }

});

});
  .record {
    display: none;
}

.state-button {
    border: 2px solid #c2c2c2;
    padding: 5px;
    border-radius: 5px;
    margin: 0 10px 0 10px;
}

.state-button.active {
    border-color: red;
}

.record.active {
    display: block;
}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="move-filters-here"></div>

<div class="record" data-state="AK">
    <h1 class="name">Customer 1</h1>
    <ul>
        <li class="focus">Focus: </li>
        <li class="course">Course: </li>
        <li class="business">Business: </li>
        <li class="address">Location: 345 Cow Town, Anchorage, <span class="state">AK</span></li>
    </ul>
</div>
<div class="record" data-state="AR">
    <h1 class="name">Customer 2</h1>
    <ul>
        <li class="focus">Focus: </li>
        <li class="course">Course: </li>
        <li class="business">Business: </li>
        <li class="address">Location: Mobile, <span class="state">AR</span></li>
    </ul>
</div>
<div class="record" data-state="CA">
    <h1 class="name">Customer 3</h1>
    <ul>
        <li class="focus">Focus: </li>
        <li class="course">Course: </li>
        <li class="business">Business: </li>
        <li class="address">Location: Los Angeles <span class="state">CA</span></li>
    </ul>
</div>

<div class="record" data-state="AZ">
    <h1 class="name">Customer 3</h1>
    <ul>
        <li class="focus">Focus: </li>
        <li class="course">Course: </li>
        <li class="business">Business: </li>
        <li class="address">Location: Flagstaff <span class="state">AZ</span></li>
    </ul>
</div>

<div class="record" data-state="UT">
    <h1 class="name">Customer 3</h1>
    <ul>
        <li class="focus">Focus: </li>
        <li class="course">Course: </li>
        <li class="business">Business: </li>
        <li class="address">Location: SLC <span class="state">UT</span></li>
    </ul>
</div>


<div id="filters">
<button class="state-button state-button-ak" data-state="AK">Alaska</button>
<button class="state-button state-button-ar" data-state="AR">Arkansas</button>
<button class="state-button state-button-ca" data-state="CA">California</button>
<button class="state-button state-button-ca" data-state="AZ">Arizona</button>
<button class="state-button state-button-ut" data-state="UT">Utah</button>
</div>