post method in ajax request Method Not Allowed in js

`I tried to post method in ajax request Method Not Allowed in js and give me Status Code 405

// js code
const xml = new XMLHttpRequest();

xml.onload = function(){
   console.log(this.responseText);
}


xml.open("POST","receive.php",true);

xml.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xml.send("name=kareem&lastvist=Today");
// php code
<?php
foreach ($_POST as $post_var) {
    echo strtoupper($post_var)
}

?>

`

Rename all keys in an object

I’m trying to rename all the keys in an object to a new and different key which is value but all solutions I found on the internet show how to add a prefix to an existing key thus renaming it.

I have the following implementation

const shippingOption =  {
                "": "Automatic",
                "ES_CartasNacionalesDeMas20": "Correos: cartas ordinarias, 2-4 Days",
                "ES_CorreosCartasCertificadas": "Correos: cartas certificadas, 2-4 Days",
                "ES_CorreosCartasCertificadasUrgentes": "Correos: cartas certificadas urgentes, 1-2 Days",
                "ES_CorreosChronoexpres": "Correos Express / Paq 24, 1 Day",
                "ES_CorreosPaq48": "Correos: Paq Premium, 2 Days",
                "ES_CorreosPaq72": "Correos: Paq Estándar, 2-3 Days",
                "ES_EconomyDeliveryFromAbroad": "Envío económico desde el extranjero, 10-22 Days",
                "ES_EconomyShippingFromGC": "Envìo economico desde China/Hong Kong/Taiwan to worldwide, 11-35 Days",
                "ES_EconomySppedPAK": "Envìo SpeedPAK economico desde China/Hong Kong/Taiwan, 10-15 Days",
                "ES_ENTREGA_KIALA_8KG": "Entrega a un punto Kiala (hasta 8 kg), 2-4 Days",
                "ES_EntregaConInstalacion": "Entrega con instalación (ver detalles), 3-5 Days",
                "ES_EntregaEnElPortal": "Entrega en el portal (ver detalles), 3-5 Days",
                "ES_EntregaEnNacexShop": "Entrega en NACEX.shop, 1-2 Days",
                "ES_EnvioEstandarAIslasBalearesCeutaMelilla": "Envío estándar a Ceuta/Melilla, 3-7 Days",
                "ES_EnvioEstandarALasIslasCanarias": "Envío estándar a las islas Canarias, 3-7 Days"
    }

let renamed= Object.entries(shippingOption).reduce((acc, [k, v]) => {
    return { ...acc, [`value[${k}]`]: v};
}, {})

How can I do this?

JavaScript decreasing value depending on input

I had found this code on the internet somewhere a while ago to decrease the number depending on how many values have been inputted, i am not good with JavaScript at all and will be learning about it more soon.

But i just need an explanation of what the JS function does row by row.

function numberOfCharacters(textbox,limit,indicatore){
  chars = document.getElementById(textbox) .value.length;
  document.getElementById(indicatore).innerHTML = limit-chars;

}
<textarea rows="4" maxLength="255" onkeyup="numberOfCharacters('mytextbox',255,'characterLimit');" name="contact_message" id="mytextbox" placeholder="Message (255 Characters)"required></textarea>
                    
<div class="chars">
     <span id="characterLimit">255</span>
</div> 

.

How to disable specific hours in specific dates in jquery datetimepicker (xdan)?

i’m using jquery datetimepicker (from https://github.com/xdan/datetimepicker), i want to disable some specific hours in some specific dates. For example, I want to disable 09:00AM option in 29/03/2022 and 10:00AM option in 30/03/2022.

I already found this code, but it doesn’t works. (Inline calendar is running correctly)

The code :

var specificDates = ['29/03/2022','30/03/2022'];
var hoursToTakeAway = [[09,10],[10]];
 
onGenerate:function(ct,$i){
          var ind = specificDates.indexOf(ct.dateFormat('d/m/Y'));
          $('.xdsoft_time_variant .xdsoft_time').show();
          if(ind !== -1) {
              $('.xdsoft_time_variant .xdsoft_time').each(function(index){
                  if(hoursToTakeAway[ind].indexOf(parseInt($(this).text())) !== -1){
 
                  $(this).hide();   
 
                  }
              });
          }
        }

Deploying a web app using Vite, I am unable to deploy the .js file. ” in “/index.html” can’t be bundled without type=”module”

When Deploying a web app using Vite, I am unable to deploy the .js file. Getting the below issue.

“$ vite build
vite v2.8.6 building for production…
<script src=”/index.js”> in “/index.html” can’t be bundled without type=”module” attribute
transforming…”
I cannot use in script “type=module” as I have no import of code to be done. I I use then error is coming.

If anyone can help.

I tried using script type=module but erroe is coming. Is there any way I can deploy with** Vite** without using type=module ?

Not able to understand the output of this for loop in Js

I have understood ,why the output of this code should be 3 3 3.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}

I am not able to understand , why the output of this code is 0 1 2

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}

I want more clarity with the output of the second for loop.

Google sheets api append multiple values with formatting

I have an array of values that i want to insert to a google sheet via API, i need to give color formatting to certain cells depending on the content of the cell like the image below:

enter image description here

I get to insert the values using append but i have no found any example on formatting append requests.

let values = [["Department",    "Product",  "Cost", "Status"],
["Clothes", "Socks", "12"   "On Stock"],
["Clothes", "Hat",  "15.99",    "Out of stock"],
["Fresh","Apple",   "18",   "Pending"],
["Fresh",   "Bannana",  "17"    "Out of stock"],
["Kitchen", "Spoon",    "0.99", "Out of stock"]]

await googleSheets.spreadsheets.values.append({
  auth,
  spreadsheetId,
  range: "Products",
  valueInputOption: "USER_ENTERED",
  resource: {
    values: values,
  },
});

What is the best approach to achieve this? batchUpdate? how would it be implemented with batchUpdate?

how to validate swift format in javascript

i am working in a bank.
in my dept, we are checking if swift format is correct.
swift is a financial network for settlement.
my boss requires me to make a javascript for swift format validation like “3!c” is “3 alphabet letters”.
do you know any useful javascript libraries to validate them?

if you know regex(regular expression) for them, please give it me.

angular-translate , fetching translation dynamically from the server and updating on runtime

I am using angular-translate in my application to manage translation. At the moment I am fetching all the language translation [4/5 languages] from the database on application loading, as the translations are getting bigger, have seen performance issue. The thing is pretty simple, I want to load language from the server [Database] based on the user’s preferred language [User has prefLang in his/her database] if logged in or fetch default language if not logged in or so.

Basically I want is :

if(userLoggedIn) {
 // fetch data as per user's pref lang
 // load config and update translatorProvider
} else {
    // fetch default language and do the same as before
 }

Actually I tried getting response from server by checking loggedin status and if I get response[translated text] I tried updating config and this fails.

 function fetchTranslationFromServer() {
        var get = $http.get('/api/v1/commonTranslation/fetchTranslation', {prefLang:usersPrefLang}, {
            headers: { 'Content-Type': 'application/json'}
        });
        get.success(function (res) {
            console.log("Response from server : ", res);
            loadTranslation(usersPrefLang, res); // do this to load config
        }).
            error(function (error) {
            console.log('error while getting translation ', error)
        });
    }

And my loadTranslation is as follows :

 function loadTranslation(usersPrefLang, translation) {
        console.log("load translations .config on calling method : " , prefLang, " ", 
        translation);   // this is calling 
        angular.module('centEventApplication').config(['$translateProvider', 
 function($translateProvider) {
     // this doesn't call and I know this doesn't work >>>>
            console.log("inside config...");
            var convert = function(messages) {
                var newMessages = {};
                angular.forEach(messages, function(value, key) {
                    if(value) {
                        newMessages[key] = value.replace(/{(d+)}/g, '{{p$1}}');
                    } else {
                        newMessages[key] = '';
                    }
                })
                return newMessages;
            }
            $translateProvider.translations(usersPrefLang, convert({data from server}));
            $translateProvider.preferredLanguage(usersPrefLang);
        }])
    }

If I put what’s inside of loadTranslation outside of this function but inside of IIFE, it works, can’t figure out how to achieve what I want.
I am doing this inside of service in angualr JS. I want to load and update .config on runtime. Is it achievable ? I will appreciate any ideas.

JSDoc: Auto detecting class methods

My jsdocs look like the following

module.exports = class gateio extends Exchange {
    /**
     * @class
     * @name gateio
     */

    async fetchOrder (id, symbol = undefined, params = {}) {
        /**
         * @method
         * @name gateio#fetchOrder
         * @description Retrieves information on an order
         * @param {string} id : Order id
         * @param {string} symbol : Unified market symbol
         * @param {boolean} params.stop : True if the order being fetched is a trigger order
         * @param {dictionary} params : Parameters specified by the exchange api
         * @returns [Order structure]{@link https://docs.ccxt.com/en/latest/manual.html#order-structure}
         */

Is there any way to auto detect that

  • that fetchOrder is a method
  • its name is fetchOrder and it belongs to class gateio
  • its description is “Retrieves information on an order”
  • That gateio is a class
  • that gateio’s name is gateio

Or do I have to specify @method, @name, @class, @description for every doc?

These @’s seem superfluous and I would like to exclude them if I could

should I add .then() after the async function call even when i don’t need anything back from that function?

Let’s say I have two async functions.

const functionTwo = async () => {
    //do something
}

const functionOne = async () => {
    try { 
        //do something
        functionTwo();
        //do something else
    } catch (e) {
        handleError(e)
    }
}

I dont want functionOne() to wait for functionTwo() to finish its execution so I didn’t put await infront of functionTwo().
I’m using WebStorm IDE and its showing a warning that I should either put await or add .then() to functionTwo() call. Is it the right thing to do to put .then(), even when i don’t need to do anything in it?

In react how to detect the button id clicked on not

In this case when I clicked the button I want to access the button Id and also want to checked that button is clicked or not. here I have use the e.currentTarget.idto detect the button ID and want to checked that its clicked or not by using document.getElementById("yourID").clicked === true. But after clicking the button its not give the alert. So how do I achieved that

import * as React from "react";
export default function Map() {
  const getButtonId = (e) => {
    if (e.currentTarget.id === "yourId") {
      if (document.getElementById("yourID").clicked === true) {
        alert("button clicked");
      }
    }
  };
  return (
    <div>
      <button id="yourID" onClick={getButtonId}>
        Button
      </button>
    </div>
  );
}

Performance JS | One loop per selector or single conditional loop

On page load I want to select various groups of elements to attach function and change classes.
So I have n getElementsByClass or querySelector in my onload function.

Performace wise, which is the best approach between one loop for each group of element I want to target or a single conditional loop?

The two approaches:

One getElementsBy..(target-group) for each target-group

or

One big conditional loop where I check attributes and/or classes

A single loop seems better, but I don’t know if these are true loops or the browser has way to optimize them.