I created a website that uses a weather API from RapidAPI to fetch data and I’ve hidden the API key. How do I host it?

I looked up online on how to deploy a website for free, and I found out that we can use Github Pages, Vercel or Netlify.

I tried using Vercel and Github Pages, but both of them don’t fetch data from the API for some reason. I’m not sure if it’s a mistake from my end. Is there no way to host websites that use such realtime APIs for free?

React update object array with values from another array of objects

In my project I am using a textbox where user can paste a text with a set of questions and answers. I need to get the input split each line in an array and add an object to the setState array with index and the content of the line.

The array of object in setState is

const [question, setQuestion] = React.useState([{quin:0,content:'',examid:''}])

and after the text is pasted in the textbox

function changeText(e){
      let v = e.target.value;
      let ar = v.split('n');
      let qu = [{quin:0,content:'',examid:''}];
      
      //console.log(ar)
      ar.forEach((element,index) => {
        
          qu.push([...qu,{quin:index,content:element,examid:'ABCD'}])            
        
      });

      setQuestion(qu);
      console.log('q: ' + JSON.stringify(question))
      
  }

How do I modify an array and retrieve the same modified values of an array outside a loop within a single iteration in JavaScript?

The idea is to loop across the diceValues array and within each single iteration, store the current item in loop into an outside array named “firstSplitDiceValues”. The codeblock below is a much simplified form to outline the challenge.

So in other words, every iteration should keep building the length of the firstSplitDiceValues and at the same time this firstSplitDiceValues should be pushed as value in another array named “moves”.

let firstSplitDiceValues = [];
const tokens = ['A', 'B', 'C', 'D'];
const diceValues = [1, 3, 4, 6];
const moves = [];

for (let diceValue=0; diceValue < diceValues.length; diceValue++) {
    firstSplitDiceValues[diceValue] = diceValues[diceValue];  // [1]
     
    moves.push([
       {
           [tokens[diceValue]]: firstSplitDiceValues
       }
    ]);
}
console.log(moves);

// What I expect:
// Moves array should contain:
[
    [{"A": [3, 4, 6]}],
    [{"B": [1, 4, 6]}],
    [{"C": [1, 3, 6]}],
    [{"D": [1, 3, 4]}]
]

// Actual results:
// Moves array only shows final expected value on all iterations
[
    [{"A": [1, 3, 4, 6]}],
    [{"B": [1, 3, 4, 6]}],
    [{"C": [1, 3, 4, 6]}],
    [{"D": [1, 3, 4, 6]}]
]

// What I expect:
// Moves array should contain:

[
    [{"A": [3, 4, 6]}],
    [{"B": [1, 4, 6]}],
    [{"C": [1, 3, 6]}],
    [{"D": [1, 3, 4]}]
]

tabs getting adding again and again

I am using jquery UI tabs and when i call them on success callback it will create two extra tabs if its JSON data from server, it works well the first time and it happens inside a modal, the modal is also closed and reopened, but model is not destroyed, the strucure is build in such a manner that destroy of modal might not work properly here

so the code below adds the tabs, but the moment i close the modal and reopen it again, it adds two more with same name and details, so it keeps on appending

success: function(response) {
      var tabTitle1 = response.title1; // replace with how you access your title in data
      var tabContent1 = response.msg1 + "n" + response.label1 + "n" + response.textData1 + "n" + response.content1; // replace with how you access your content in data
      var tabTitle2 = response.title2;// replace with how you access your title in data
      var tabContent2 = response.msg2 + "n" + response.label2 + "n" + response.textData2 + "n" + response.content2; // replace with how you access your content in data

      var tabTemplate = "<li><a href='#{href}'>#{label}</a></li>";
      var id1 = "tabs-" + ( $("#tabs li").length + 1 );
      var id2 = "tabs-" + ( $("#tabs li").length + 2 );

      var li1 = $( tabTemplate.replace( /#{href}/g, "#" + id1 ).replace( /#{label}/g, tabTitle1 ) );
      var li2 = $( tabTemplate.replace( /#{href}/g, "#" + id2 ).replace( /#{label}/g, tabTitle2 ) );

      $("#tabs").find( ".ui-tabs-nav" ).append( li1 );
      $("#tabs").append( "<div id='" + id1 + "'>" + tabContent1 + "</div>" );

      $("#tabs").find( ".ui-tabs-nav" ).append( li2 );
      $("#tabs").append( "<div id='" + id2 + "'>" + tabContent2 + "</div>" );

      $("#tabs").tabs( "refresh" );
    },

something is up and can’t figure out the time of me what is going on

Using Angular Signals with HostBinding to update style?

In a app-test component I have the following:

  @Input( { transform: booleanAttribute})
  reverse: boolean = false;

  @HostBinding('style.flex-direction')
  direction: string = this.reverse ? 'column-reverse' : 'column';

And so if the designer applies the reverse attribute to app-test like this:

<app-test reverse></app-test>

Then Angular should set style="flex-direction: column-reverse" on the app-test element.

And I’m wondering how to use Angular signals so that when reverse is set to true, direction will be set to column-reverse. Thoughts?

Why an array from a function is [empty x 3], has the expected values when reviewed on the console.log but value = array[“anyof three”] is undefined JS [duplicate]

I’m having serious problems with arrays as result from a function.

Have three procedures in JS, after splitting the original one, trying to find where is the problem:


  $(document).on("input", ".dpPago", function(){
    var dppago = $(this).val();
    var ArrPa = damedivis(dppago, buscando);
    console.log("ArrPa ", ArrPa);
    dimequehay(ArrPa);
  })

  function dimequehay(arrpa){
    var divis = arrpa["divis"];
    $(".rfTsc").val(divis);
    console.log("arrpa-dime ", arrpa);
    console.log("arrpa-divis ", arrpa["divis"]);
    console.log("divis ", divis);
    console.log("rfTsc ", $(".rfTsc").val());
    document.getElementById("rfTsc").readOnly = false;
  }

  function damedivis(dppago, cdCallback){
    return cdCallback(dppago);
  }

  function buscando(dppago){
    var pagarr = new Array(3);
    var datos = new FormData();
    datos.append("mppago",dppago);
    $.ajax({
      url: "ajax/ventas.ajax.php",
      method: "POST",
      data: datos,
      cache: false,
      contentType: false,
      processData: false,
      dataType: "json",
      success: function (dataset){
        pagarr["divis"] = parseInt(dataset["mp_divisa"]);
        pagarr["valid"] = parseInt(dataset["mp_valida"]);
        pagarr["impue"] = dataset["mp_impuesto"];
      }
    });
    console.log("pagarr ", pagarr);
    return pagarr;
  }  

[Output from Console](https://i.stack.imgur.com/SbotC.png)

I’m really baffled.

Some help, anyone???

As I said, it was a single procedure at first -and this is not even the whole one-;

I try to fill an array “ArrPa” with the result from “damedivis” which, at his time, calls-back the procedure “buscando” because this is an Ajax procedure to execute an asynchronous call to a DB -or, at least. that’s what I believe it does-.

The procedure “buscando”, executes a query on MariaDB and brings back some values in a dataset, from which it use 3 of them, that first I place in an declared array “pagarr” that I return as result of the function. The arrays are brought back and they are there but “empty”??? Because, when I try to use whatever should be inside the array it turns to be “undefined”.

As you might see I tried everything, even, finally, the Callback, but the results were the same in every case.

The console shows the arrays of 3 items, and even show their expected “right” values but, outside the console, those values are “undefined”.

What am I doing wrong?

Update a date time field after change on form, while preserving another date time field set on page load

I’ve got a form with many inputs, along with a a Start Date/Time and Updated Date/Time field.

On page load, the Start Date/Time field is set in mm/dd/yyyy HH:MM AM/PM format. There is also a date picker on this field, so that date/time can be manually changed to something in the past.

Then, the Updated date/time field is read only, and should be set initially on page load…and then updated anytime any field on the form is changed.

Currently, I have the code in two different js files, but that can be changed if necessary or more proficient in any way.

Without the 2nd argument, this code works…however, the start date/time is also updated whenever there is a change, and it shouldn’t. How to fix this?

The js in file 1:

//Account for timezones and formate date as mm/dd/yyyy HH:MM AM/PM
const date = new Date(Date.now());
const formattedDateTime = getFormattedDateTime(date,false);

function getFormattedDateTime(date,dateUpdated) {
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  };

  const formatter = new Intl.DateTimeFormat(options);
  const formattedDateTime = formatter.format(date);

  return formattedDateTime.replace(
    /(d+)/(d+)/(d+), (d+):(d+)/,
    '$3-$1-$2T$4:$5'
  );
}

document.querySelector('#date_started').value= formattedDateTime;   
document.querySelector('#date_updated').value= formattedDateTime;

The js in file 2:

//Set Date Updated field to current date time whenever a field is changed. 
const form = document.querySelector('form');
let dateUpdated = "false";

form.addEventListener('change', function() {
    let dateUpdated = "true";
    getFormattedDateTime(undefined,dateUpdated)
});

Tried this in js file 1, but doesn’t work. The start date doesn’t get set on page load and the updated date doesn’t get set on any form change :

if (dateUpdated != "true") {
  //Only set the Start Date if there was no change on the form.
  document.querySelector('#date_started').value= formattedDateTime; 
}  

document.querySelector('#date_updated').value= formattedDateTime;

printing every single topping out

I’m sure its a simple fix but I have a lot on my plate.
I just cant spot the error. any help would be great. my guess is its in the summarize block.

"use strict";
`/---------------- Object Code ----------------------/
let cart = {items: [],addItem: function(foodItem){this.items.push(foodItem);}}function Pizza(){this.size = '';this.crust = '';this.toppings = [];}
function topping(){this.name = '';this.side = '';}Pizza.prototype.addToCart = function(cart){cart.items.push(this);}Pizza.prototype.summarize = function(){let summary = "Pizza: "+this.size+" "+this.crust+" ";for(let i = 0; i < this.toppings.length ; i++){
    summary += this.toppings[i].name +"("+this.toppings[i].side+")";    
}
return summary;
}
Pizza.prototype.addToppings = function(topping){this.toppings.push(topping);}

/----------------------------- Interface Code -------------------------/
let pizzaPreviewBox = document.getElementById("previewBox");         // pizza imagelet pizzaSizeBox = document.getElementById("pizzaSize");             // pizza size selectionlet pizzaCrustBox = document.getElementById("pizzaCrust");           // pizza crust selectionlet toppingOptions = document.querySelectorAll("input.topping");     // pizza topping option buttonslet addToCart = document.getElementById("addToCart");                // Add to Cart buttonlet cartBox = document.getElementById("cart");                       // Shopping cart box
// Add event handlers for the pizza toppingsfor (let i = 0; i < toppingOptions.length; i++) {toppingOptions[i].onclick = drawPizza;}
// Event Handler for the addToCart buttonaddToCart.onclick = updateCart;
// Clear the pizza imagefunction clearPizzaImage() {while (pizzaPreviewBox.firstChild) {pizzaPreviewBox.removeChild(pizzaPreviewBox.firstChild);}}
// Unselect all toppingsfunction clearToppings() {let noTopping = document.querySelectorAll("input.topping[value='none']");for (let i = 0; i < noTopping.length; i++) {noTopping[i].checked = true;}}
/* Function to draw the pizza image  */function drawPizza() {// Erase current pizza imageclearPizzaImage();// Determine which toppings have been checkedlet checkedToppings = document.querySelectorAll("input.topping:checked");
// Draw the individual toppingsfor (let i = 0; i < checkedToppings.length; i++) {if (checkedToppings[i].value !== "none") {let toppingImage = document.createElement("img");toppingImage.src = checkedToppings[i].name + ".png";toppingImage.className = checkedToppings[i].value;pizzaPreviewBox.appendChild(toppingImage);}}}
// Function to build the pizzafunction buildPizza() {let checkedToppings = document.querySelectorAll("input.topping:checked");let myPizza = new Pizza();myPizza.size = pizzaSizeBox.value;myPizza.crust = pizzaCrustBox.value;for(let i = 0; i < checkedToppings.length ;i++){var myTopping = new topping();myTopping.name = checkedToppings[i].name;myTopping.side = checkedToppings[i].value;myPizza.addToppings(myTopping);}return myPizza;
}
// Function to add the built pizza to the shopping cartfunction updateCart() {let myPizza = new Pizza();myPizza = buildPizza();cart.addItem(myPizza);console.log(cart)console.log(myPizza.summarize)var p = document.createElement('p');p.textContent = myPizza.summarize();
cartBox.appendChild(p);
clearPizzaImage();
clearToppings();
}

cant seem to figure it out.

Convert a SQL query into specific json format | Javascript

I want to convert an sql query string (within where conditions only) into specific json format.

sample query string

lets queryString = "income = 25000 AND ((expense >= 50000) AND ((personal_expense >= 10000) OR (family_expense <= 50000)))".

JSON Format should be,

const QueryClass = {
    isGroup: "Y/N",
    conditions : "<queryCondition>",
    group : {
        operator : "AND/OR",
        filter: [ <Array of QueryClass>]
    }
}

Basically, if isGroup is Y, then condition should be empty and group value should be there, isGroup is N, condition should be there, group should be null.

for example : Result should be like

{
    isGroup : "Y",
    condition: null,
    group : {
        operator : "AND",
        filters : [
            {
                isGroup : "N",
                group : null,
                condition : "amount=1000"
            },
            {
                isGroup : "Y",
                condition : null,
                group : {
                    operator : "OR",
                    filters : [
                        {
                            isGroup : "N",
                            group : null,
                            condition : "expense >= 50000"
                        },
                        {
                            isGroup : "N",
                            group : null,
                            condition : "personal_expense >= 10000",
                        },
                    ]
                }
            }
        ]
    }
}

Basically, the expectation should be work in both ways,
SQL to JSON, JSON to SQL. But, i already handled the JSON to SQL part

Any suggestion to achieve the SQL to JSON part

Contact Form 7 issue submitting form, AJAX not working

I’m having an issue with a form that was created by another developer some time ago. When asked to implement a redirect upon form submission, I noticed that the form is no longer submitting correctly in the first place. Here is the website: https://thewaterblob.com/build-a-blob/

When you click the submit buttons on the final page of this form, the screen reloads with #wpcf7-f442-o1 tacked on to the end of the URL. From what I’ve gathered so far, this means the form is not submitting using AJAX. Luckily, for now, the client is receiving emails when a customer fills out the form, but it is not working as intended. Ideally it would behave like the example here: https://contactform7.com/why-isnt-my-ajax-contact-form-working-correctly/

However, I’m not sure what would conflict or cause the JavaScript not to load.

I saw responses that involved the functions wp_head() and wp_footer(), in header.php and footer.php, but I don’t see those functions referenced anywhere. The page uses .twig templates, and I’m not sure if there is an equivalent there for enqueueing JavaScript.

I’m not sure what files would be most helpful for finding the problem, whether it’s msco_buildablob.php, or the app.ts file. I have tried putting in some console.log statements to see where things stop working in app.ts.

Under methods:{} for the component, there is one
relating to form submission.

submitForm(event: Event) {

// Disable form submit buttons and show a spinner or something

    let submitBtns = jQuery("form [type=submit]");

    submitBtns.each(function (this) {

        let btn = jQuery(this);

        btn.prop("disabled", true);

    });

jQuery("form.wpcf7-form").trigger("submit");

},

There is also one called populateCf7Form() which appears
to be working, because I see a POST request after
submitting that includes:

_wpcf7: 442
_wpcf7_version: 5.8.4
_wpcf7_locale: en_US
_wpcf7_unit_tag: wpcf7-f442-o1
_wpcf7_container_post: 0
_wpcf7_posted_data_hash:
and the expected data for a water blob product request.

Finally, there is a method called mounted(), where I
have been experiencing issues. I’m trying to console.log
several places within the method to troubleshoot, and
functions within it, and I’m not even reaching some of
the code.

Here’s how it currently looks.
mounted() {
console.log(“Blob confirm page mounted”);

this.$nextTick(this.populateCf7Form);
let self = this;

// Check if .wpcf7 element exists
if (jQuery(".wpcf7").length) {
console.log("wpcf7 element non-zero, so it exists");
console.log("Length: " + jQuery(".wpcf7").length);
} else {
console.log("wpcf7 element has no length, so it doesn't exist");
}

//Global event listener
jQuery(document).on('wpcf7mailsent', function () {
console.log('Global wpcf7mailsent event triggered');
});

// wpcf7 event listeners
jQuery(".wpcf7").on("wpcf7invalid", function (event) {
// if (event.detail == undefined) return;
// @ts-ignore
let cf7container = jQuery(#${event.detail.id});
let tips = cf7container.find(".wpcf7-not-valid-tip");
// Notify user of the failed fields promting them to fix them.
tips.each(function () {
alert(jQuery(this).text());
});
});

jQuery(".wpcf7").on("wpcf7spam", function (event) {
alert("Spam detected. Mail not sent.");
});
console.log("Script loaded (which should appear same time as Blob confirm page mounted so it isn't actually that helpful)")
jQuery(".wpcf7").on("wpcf7mailsent", function (event) {
console.log("Mail sent event triggered");
// Dont alert on page leave
jQuery(window).off("beforeunload");
jQuery(window).off("unload");
// Redirect to complete page
window.location.replace(self.redirect);
});

jQuery(".wpcf7").on("wpcf7mailfailed", function (event) {
alert("Failed to send mail. See console log for details.");
console.log(event);
});

jQuery(".wpcf7").on("wpcf7submit", function (event) {
event.preventDefault();
console.log("Submit event triggered");
// Disable form submit buttons and show a spinner or something
let submitBtns = jQuery("form [type=submit]");
submitBtns.each(function (this) {
let btn = jQuery(this);
btn.prop("disabled", true);
// btn.prop("disabled", false);
});
console.log("Form submitted, buttons disabled");
});

jQuery(document).ajaxComplete(function () {
console.log("AjaxComplete event triggered");
let submitBtns = jQuery("form [type=submit]");
 submitBtns.each(function () {
let btn = jQuery(this);
btn.prop("disabled", false);
});
console.log("Ajax request complete, buttons enabled.");
});
},

I get “Blob confirm page mounted” to print when the page loads, along with “wpcf7 element exists”, but none of the console.logs within any “jQuery(“.wpcf7″).on ” print to the console before the page refreshes when you submit.

There is also the issue where the “Leave page without saving?” alert pops up when submitting the form, because the jQuery(window).off(“beforeunload”); is not being reached as well.

I don’t know how to identify where the precise issue breaking things is, whether it’s a conflicting plugin, a theme issue, or a problem with the custom plugin code. I’m not seeing errors in the console, nor sure there’s anything useful in the Network tab as the screen refreshes so fast. I’ve disabled all plugins but 1 which would otherwise break the site, and i’ve tried a separate theme and was still getting the issue.

How to make ray coordinate data compatible with rendering in ThreeJS without offset at different ends

This issue occurs when using THREEKS to create a dxf/image editor.

One of the functions is the point measurement function. You need to press the mouse in the canvas area to obtain the offsetW/H of that area, then convert it to the standard device coordinates, and use raycaster. setFromCamera (standard device coordinates, camera) to locate the clicked point (because a plane with a width of 10000000 and a height of 100000000 has been added inside the canvas, which is the intersection point of the ray and this plane), and obtain the ray coordinates of the point based on this point. Then render CircleGeometry to the specified location based on the ray coordinates.

The problem is here….

If we save this ray coordinate and render CircleGeometry on another device with inconsistent screen size, there will be a deviation in the rendering position of CircleGeometry. How can we solve this problem?

Based on the above issue, I suspect that the screen size of ThreeJS has changed due to devices of different sizes. Therefore, I calculated the ratio based on two different screen sizes, corrected the ray coordinates based on this ratio, and then rendered.

Result: The satisfactory effect was not achieved, and the deviation still exists

getBoundingClientRect() is giving dimensions of parent instead of target element

I’m rather new to webdesign, so apologies in advance. I have a simple grid layout for a website. Inside of one of the cells is an image with object-fit: contain to make it responsive.

I am trying to get the actual dimensions of the image as it is displayed. The problem is that getBoundingClientRect() gives me the dimensions of the parent div, not the image itself. The whole reason I want the image size is to account for the letter-boxing.

Below you can easily see that width > height according to the function, even though I’ve used a portrait format example image. So it’s taking the values from the parent.

EDIT for clarification: I see now that those are the right values of the img tag but not of the actual image. Any way to get those values?

function getImageSize() {
  const image = document.querySelector('#sample_image');
  var imgBounds = image.getBoundingClientRect();
  console.log(imgBounds);
}
window.onload = getImageSize;
window.onresize = getImageSize;
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.wrapper {
  display: grid;
  border-style: solid;
  border-color: red;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(5, 1fr);
  grid-gap: 10px;
  width: 100vw;
  height: 100vh;
}

.instructions {
  border-style: solid;
  border-color: blue;
  grid-column: 1 / -1;
  grid-row: 1;
}

.elements {
  border-style: solid;
  border-color: yellow;
  grid-column: 1;
  grid-row: 2 / -1;
}

.examples {
  border-style: solid;
  border-color: violet;
  grid-column: 2 / -1;
  grid-row: 2 / -1;
  background-color: #d3d3d3;
  position: relative;
}

.examples img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<html>

  <body>
    <div class="wrapper">
      <div class="instructions">text1</div>
      <div class="elements">text2</div>
      <div class="examples">
        <img src="https://upload.wikimedia.org/wikipedia/commons/9/9b/Gustav_chocolate.jpg" id="sample_image" />
      </div>
    </div>

  </body>

</html>

JSFiddle which shows the problem as well.

Onclick strictly javascript

I am trying to remove JS from my html and i am having a hard time. I removed the onclick and implemented it into my javascript. It doesn’t function as if it was still in my html.

  <div class="shirt1" onclick="showItemDetails('shirt1')">
            <img src="shirt1.jpg" alt="shirt1">
            <h2>90s Salem Sportswear Miami Hurricanes Lightning (AOP) Tee Size XL</h2>
            <h4>Condition: Like New</h4>
           <h3>$300</h3> 
           <h5> offer</h5>
        </div>

For my javascript I have the following code:

function showItemDetails(shirtId) {
    const shirt = document.getElementById(shirtId);
}


document.addEventListener('DOMContentLoaded', function() {
    const shirts = document.querySelectorAll('.shirt');
    shirts.forEach(function(shirt) {
        shirt.addEventListener('click', function() {
            const shirtId = shirt.id;
            showItemDetails(shirtId);
        });
    });
});

I have tried the following code above, i also have tried implmenting other ways but still cannot figure this out.

Aliexpress API signature algorithm and javascript

I have been working endlessly on trying to retrieve a correct signature for use in getting an access token from the aliexpress API. The signature is appended to the end of the url and then, if the signature is correct, it gives you back the access token, refresh token, user credentials, etc. Unfortunately, I have not been able to get back the proper signature as per “platform standards”. I am stumped at the moment

const generateSign = () => {
  const code = localStorage.getItem("authCode");
  const params = {
    app_key: appKey,
    timestamp: timestamp,
    sign_method: sign_method,
    code: code,
  };
  console.log(params);

  const sortedParams = Object.keys(params)
    .sort()
    .reduce((acc, key) => {
      acc[key] = params[key];
      return acc;
    }, {});
  console.log(sortedParams);

  let concatenatedString = "";
  for (const key in sortedParams) {
    concatenatedString += `${key}${sortedParams[key]}`;
  }
  const apiName = "/auth/token/security/create";
  concatenatedString = apiName + concatenatedString;
  console.log(concatenatedString);

  const encodedString = encodeURIComponent(concatenatedString);
  console.log(encodedString);
  const hash = CryptoJS.HmacSHA256(encodedString, appSecret);
  console.log(hash);
  const signature = hash.toString(CryptoJS.enc.Hex).toUpperCase();

  console.log(signature);

  return signature;
};