Proxied Browser Requests with Cookies through a node server

What I am trying to achieve is displaying html content to a user from another server (external server That I do not own) that is normally accessed through a browser.

To get the right html to display to the user, cookies related to that server’s domain must be provided.

APPROACH 1:

Easiest approach I tried is using an iframe. And of course, I got the usual CSP error from the chrome console:

Refused to frame ‘{{URL}}’ because an ancestor violates the following Content Security Policy directive: “frame-ancestors ‘self’ {{ACCEPTED DOMAINS}}”.

APPROACH 2:

I made a local proxy server in node.js and tried to setup a proxied request in browser axios:

axios.get("{{URL to external server}}", { proxy: { host: "localhost", port: 5050 }});

I quickly realized that axios proxy is a node only feature per this issue.

CONCLUSION:

I can’t find a way to make a GET request to get html in a browser to a cookie protected and CSP protected server/domain. If I am able to display html in the first place, I can probably use the same system to show a login page to update the user’s cookies. Just a heads up I am using react / node.js.

If you know of a better approach that completely scraps away my code or uses a different technology, please share!

Thank you in advance.

How do i count a data that includes another data in sequelize?

So i was trying to get a record about car dealers who successfully sold a specific car, sorted from how much the dealer successfully sold that car so the dealer that successfully sold the most of that specific car will appear first. The problem is that in the end i also need to group the car id, which makes the counting innacurrate. Can anyone please help me solve this problem where i can just get the record without needing to group the car id as well?

Here is my code:

const data = await models.Car.findAll({
      paranoid: false,
      attributes: [[Sequelize.fn('COUNT', Sequelize.col('userId')), 'carsCount'], 'userId'],
      where: { brandId, groupModelId, status: 2 },
      include: [
        {
          model: models.User,
          as: 'user',
          required: true,
          duplicating: false,
          attributes: ['name', 'phone', 'email'],
          include: [
            {
              model: models.UserAddress,
              as: 'userAddress'
            }
          ]
        }
      ],
      group: ['userId', 'user.id'],
      offset,
      limit
    })

Thank you in advance and sorry if my English is not perfect

Handling django form views using ajax

I am looking for more elegant way to solve this problem. Say I have say two buttons x, y in main.html:

<input class= "btn-check", name = "options", id="x">
<label class="btn btn-lg btn-info", for="x">x</label>
    
<input class= "btn-check", name = "options", id="y">
<label class="btn btn-lg btn-success", for="y">y</label>

What I want to do is after the button is clicked, I will do something in python and so in django views I will create a view function for each of the buttons (my current implementation):

def funcX(request):
    booleanX = doSomethingforX()
    return JsonResponse({"success": booleanX})

def funcY(request):
    booleanY = doSomethingforY()
    return JsonResponse({"success": booleanY})

and the ajax calls would be:

$("[id='x']").on("click", function(e){
    e.preventDefault();
    
    $.ajax({
        type:"GET",
        url: "{% url 'funcX' %}",           
        success: function(response){
            if(response.success == true){
                //Do something
            }
        }       
    })
});

The ajax call will be the same for button Y.

Now, I was wondering if it is possible to do this with forms?
Say the html becomes:

<form method="POST", class="form-group", id="post-form">
    <input type="submit", value="x", class= "btn-check", name = "options", id="x">
    <label class="btn btn-lg btn-info", for="x">x</label>

    <input type="submit", value="y", class= "btn-check", name = "options", id="y">
    <label class="btn btn-lg btn-success", for="y">y</label>

</form>

Then in django views I have a view for the main.html. This way it saves a lot of views written in django.

def main(request):
    
    if request.method == "POST" and request.POST["options"] == "x":
        booleanX = doSomethingforX()
        return JsonResponse({"success": booleanX})
    
    if request.method == "POST" and request.POST["options"] == "y":
        booleanY = doSomethingforY()
        return JsonResponse({"success": booleanY)})
    return render(request, "main.html")

Now the problem is I don’t know how to write the ajax calls to receive from views and get the JsonResponse return for X and Y respectively…

Any ideas?

Jquery – how to the set value for select option dropdown without using .change() to trigger the set value operation

So I have a dropdown which is within a form just like below:

<form id="formA" action="John/Doe" method="post">
    -hidden input with value-
    <select name="Letters" id="Letters">
        <option value="1">A</option>
        <option value="2">B</option>
        <option value="3">C</option>
        <option value="4">D</option>
    </select>
</form>

So my situation is once I make a selection on the dropdown, it will trigger a submit form action like below:

$(document).on('change', '#Letters', function() {
    // here I am submitting the form whenever the ajax call success
    $.ajax({
        type: "Get",
        url: "sample/url",
        success: function(data){
            console.log(data);
            $('#formA').submit();
        }
    });
});

Now I have another ajax call, when this ajax call is completed, I need to set the select value for this same dropdown list, I tried it with $('#Letters').val(newValue).change() just like below.

$.ajax({
    type: "POST",
    url: "sample/url",
    data: {sampleData}
    success: function(data){
        console.log(data);
    },
    complete: fuinction(){
        $('#Letters').val(newValue).change();
    }
});

However, this .change() will trigger the ajax call above again which is not something that I want. So I guess cannot use .change() here.

The reason I am doing this is that I wanted this value for the next form submit action.
If I don’t set this value after this 2nd ajax call, when I do next form submit, I got null values.

I also tried $("#Letters option[value=" + thatOptionValue + "]").attr('selected', true) But this one is not setting the value to the dropdown list at all. My controller is getting null from this.

It seems to me only when using .change() then it will do the set value operation. Is there any other solution to set the value without using .change()?

Any help will be appreciated!

Filtering array with multiple conditions (javascript/typescript)?

Right now I have an array of objects

array = [
{
text: 'Example 1',
colorCode: '1'
},
{
text: 'Example 2',
colorCode: '2'
},
{
text: 'Example 3',
colorCode: '3'
}, 
text: 'Example 4',
colorCode: '3'
}
]

then I have an array of filters

filters = [1, 3]

I’m attempting to write a function that returns an array based on the filters provided so this example would return an array of objects containing example 1, example 2, and example 4.

Currently I’m creating an array and looping through the filters one at a time. Something like this

let filteredArray = [];
filters.forEach((x: number) => {  
        filteredArray = filteredArray.concat(_.filter(this.array, {colorCode: x}))
 })

However this seems redundant as I have to loop through the array for each filter, and will take more time as the array grows. I loop through the array and find all colorCode === 1, then loop through the array and find all colorCode === 3. Is there a way for me to only loop through the array one time and checking if each object.colorCode === 1 || object.colorCode === 3.

My problem with this function is that filters array are constantly changing in values and size, so the function needs to account for that rather than static values being passed.

How can I display a value received from an API?

I have 2 HTML files and 1 javascript file. The first HTML file receives user input (username), uploads to the API server, and then redirects to the second HTML file that receives the username from the server and displays “Welcome username”.

My problem is that when I receive the name, it displays as undefined.

script:

  function welcomeUser() {
    console.log("In welcomeUser()");

    get("http://example.com").then(function(response){
      if(response.status == 200) {
        console.log("case 200");
        const username = String(response.data.id); //The username that was requested. In this case it is "myUserName".
        const score = response.data.score; //The user's current score.
        console.log(username, score);
        display (username, score);
      }
      else {
        //User "myUserName" not found.
        //response.data is null
        post("http://example.com", { id: response.data.id, score: 0 }); //create a new user.
      }
    });
  }



  function display(username, score) {
    let message = "Welcome ".concat(username);
    document.getElementById("welcome").innerHTML = message;
  }



 function get(url) {
   console.log("In get()");

    return new Promise((resolve, reject) => {
      const http = new XMLHttpRequest();
      http.onload = function() {
        resolve({ status: http.status, data: JSON.parse(http.response) });
      };
      http.open("GET", url);
      http.send();
    });
  }

  /**
   * @typedef {{status: number, data: User|Error}} Response
   */

  /**
   * @typedef {{id: string, score: number}} User
   */

HTML:

<body onload="welcomeUser()">
    <h1 id="welcome"></h1>

    <script src="app.js"></script>
</body>

Import functions that have parameter to vue methods without calling it

I have these methods with similar functionality in different js files. I want to import these methods and add them to the vue methods I already have. The methods have also dependency so I have to pass parameters.

I have used the bind method to avoid calling the functions
I used the spread operator to list all the available functions to vue methods.

The intention is to divide vue file with more than 150 methods in it into separate files/modules and import the methods to that file/component

// functionsToBeImported.js
export default(param) {
  method1 () {
    console.log(param);
  }

  method2 () {
    console.log(param);
  }

return {
     method1,
     method2
  }
}


import functionsToBeImported from './functionsToBeImported';
import anotherFunctionsToBeImported from './anotherFunctionsToBeImported';

export default {
  methods: {
       normalFunction(){},
       ...functionsToBeImported.bind(param),
       ...anotherFunctionsToBeImported.bind(param),
    }
}

Open modal using JavaScript (not jQuery)

I’m trying to repurpose some code I obtained from Codepen. It’s written using jQuery but I want to rewrite the script using JavaScript.

The original codepen (see: Codepen) shows a few ways to open a modal window using animation. I’m using the ‘UNFOLDING’ animation.

The Codepen uses the following jQuery:

$('.button').click(function(){
   var buttonId = $(this).attr('id');
   $('#modal-container').removeAttr('class').addClass(buttonId);
   $('body').addClass('modal-active');
})

$('#modal-container').click(function(){
   $(this).addClass('out');
   $('body').removeClass('modal-active');
});

I’m trying to rewrite this as JavaScript.

I’ve got the modal to open with the following JavaScript:

let button = document.getElementById('start');
let body = document.body;
button.addEventListener('click', () => {
   document.getElementById('modal-container').classList.add('one');
   body.classList.add("modal-active");
});

BUT, I can’t get it to close!

I tried the following but it doesn’t work properly (compared to original Codepen):

let button2 = document.getElementById('modal-container');
button2.addEventListener('click', () => {
   document.getElementById('modal-container').classList.add('out');
   document.getElementById('modal-container').classList.remove('one');
   body.classList.remove("modal-active");
});

Hoping someone can show me where I’ve gone wrong.

Thanks.

Wrack the mole in JavaScript [closed]

I am trying to complete a project for my course, it is a game wrack the mole. I am following a tutorial but still, my code is not working, I have gone through the code many times but still can’t find the mistake. Any help will be great.

// get a random cell,

var cells = document.getElementsByTagName ("TD")
var randomIndex = Math.floor(Math.random() + cells.length)
//mole appear on cell
var randomCell = cells[randomIndex]
var mole = document.createElement('img');
//source of mol picture
 mole.src ='./mole.PNG';
 mole.id = "mole";
 
 randomCell .appendChild (mole)
 mole .onClick = whackedMole;
// click on mole and than mole appear on different cel
function whackedMole(){
  randomIndex = Math.floor(Math.random() * cells.length)
  randomCell = cells.randomIndex
  randomCell.appendChild (mole)
  //audio for mole
  var audio = new Audio('./whack-audio.wav')
  audio.play();
}   

localStorage gets reset after button click ReactJS

I’m currently experiencing an issue where local storage is reset after trying to add an item that belongs to a different page(ex shown below) to the local storage. The local storage functionality is being used for a shopping cart feature.

It all works well when I try adding items from the same category, but once I switch the the category the local storage is reset.

A weird behavior that I also noticed is that for the first item that I try to add to the cart, I have to double click it for it to register in the local storage.

I’ve set the program so that only the shopping cart page needs to access the local storage.

Adding product from “Wearables category”
enter image description here

Going back and into the Items in the “Computers” section. Ignore sidebar
enter image description here

Adding item from wearable section and local storage is cleared.
enter image description here

Code:
App.js

class App extends Component {
  userData;
  constructor(props) {
    super(props);

    this.state = {
      cart: [],
    };

    this.handleAddToCart = this.handleAddToCart.bind(this);
  }

  handleAddToCart = (productId, prodName, description, price) => {
    console.log(" Handle Add to Cart Called ", productId);
    console.log("->cart state: ", this.state.cart);
    const holder = {
      productId,
      quantity: 1,
      prodName,
      description,
      price,
    };

    const idx = this.indexOfProduct(productId);

    if (idx == -1) {
      // Product does not exist in cart
      this.setState(
        {
          cart: [...this.state.cart, holder],
        },
        () => {
          console.log("Updated Cart: ", this.state.cart);
        }
      );
    } else {
      let newArray = [...this.state.cart];
      newArray[idx] = {
        ...newArray[idx],
        quantity: newArray[idx].quantity + 1,
      };
      this.setState(
        {
          cart: newArray,
        },
        () => {
          console.log("Updated Cart: ", this.state.cart);
        }
      );
    }
    localStorage.setItem("cart", JSON.stringify(this.state.cart));
  };

  indexOfProduct(productId) {
    for (let index = 0; index < this.state.cart.length; index++) {
      if (this.state.cart[index].productId == productId) return index;
    }
    return -1;
  }

  render() {
    return (
      <div className="App">
        {/* <div className="container-fluid">
          <NavBarComponent />
        </div> */}
        <>
          <Router>
            <div className="container-fluid">
              <NavBarComponent />
            </div>

            <Switch>
              <Route exact path="/sidebar">
                <SideBarComponent />
              </Route>
              <Route exact path="/products/:category">
                <ProductGridComponent />
              </Route>
              <Route exact path="/cart">
                <ShoppingCartComponent />
              </Route>
              <Route exact path="/product/:id">
                {/*onAddToCart={this.handleAddToCart} */}
                <ProductViewComponent onAddToCart={this.handleAddToCart} />
              </Route>

              <Route exact path="/contact">
                <ContactUsComponent />
              </Route>

              <Route exact path="/about-us">
                <AboutUsComponent />
              </Route>
              <Route exact path="/">
                <HomeComponent />
              </Route>
            </Switch>
          </Router>
        </>
        <FooterComponent />
      </div>
    );
  }
}

export default App;

ShoppingCartComponent.jsx

class ShoppingCartComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cart: [],
    };
    console.log("Hello Im the constructor");
  }
  static getDerivedStateFromProps(props, state) {
    console.log("Hello Im the dState Func");

    const sCart = localStorage.getItem("cart");
    const parsedCart = JSON.parse(sCart);

    if (sCart == null) {
      return { cart: [] };
    } else {
      console.log("cart String mount on shopping cart: ", sCart);
      console.log("cart Object at mount on shopping cart: ", parsedCart);
     

      return { cart: parsedCart };
      console.log("After appending", this.state.cart);
    }
  }


  render() {
    console.log("Shopping Cart Array at Render(): ", this.state.cart);
    return (
      <div className="container mt-5 p-3 rounded cart">
        <div className="row no-gutters">
          <div className="col-md-8">
            <div className="product-details mr-2">
              <div className="d-flex flex-row align-items-center">
                <i className="fa fa-arrow"></i>

                <button /* onClick={history.back} */>
                  <span className="ml-2">
                    <a style={{ color: "black" }}>Continue Shopping</a>
                  </span>
                </button>
              </div>
              <hr />
              <h6 className="mb-0">Shopping cart</h6>
              <div className="d-flex justify-content-between">
                <span>
                  You have {this.state.cart.length} items in your cart
                </span>
                <div className="d-flex flex-row align-items-center">
                  <span className="text-black-50">Sort by:</span>
                  <div className="price ml-2">
                    <span className="mr-1">price</span>
                    <i className="fa fa-angle-down"></i>
                  </div>
                </div>
              </div>

              {this.state.cart.map((product) => (
                <div className="d-flex justify-content-between align-items-center mt-3 p-2 items rounded">
                  <div className="d-flex flex-row">
                    <img
                      className="rounded"
                      src="https://i.imgur.com/QRwjbm5.jpg"
                      width="40"
                    />
                    <div className="ml-2">
                      <span className="font-weight-bold d-block">
                        {product.prodName}
                      </span>
                      <span className="spec">256GB, Navy Blue</span>
                    </div>
                  </div>

                  ...
         

ProductGridComponent.jsx //Where the products per categories are displayed. Sidebar is a separate component.

class ProductGridComponent extends Component {
  constructor(props) {
    super(props);

    const windowUrl = window.location.pathname.substring(1);
    console.log("window url: ", windowUrl);

    this.state = {
      category: windowUrl.substring(windowUrl.indexOf("/") + 1), //Please fix me, I am vulnerable to SQL Injection
      products: [],
    };
    console.log(this.state.category);

    this.handleShopButtonClick = this.handleShopButtonClick.bind(this);
  }
  componentDidMount() {
    ProductService.getProductsByCategory(this.state.category).then((res) => {
      this.setState({ products: res.data });
    });
  }
  handleShopButtonClick(productId) {
    this.props.history.push(`/product/${productId}`);
  }
  onAddClick() {}

  render() {
    return (
      <>
        {/* <div className="container-fluid page-body-wrapper"> */}
        <div className="wrapper">
          <SideBarComponent />
          <div className="row" style={{ marginLeft: "5px" }}>
            {this.state.products.map((product) => (
              <div className="col col-md-3" style={{ marginTop: "5px" }}>
                <div className="card">
                  <div className="d-flex justify-content-between align-items-center">
                    <div className="d-flex flex-row align-items-center time">
                      <i className=""></i>
                      <small className="ml-1">{product.vendorName}</small>
                    </div>
                  </div>
                  <div className="text-center">
                    <img src="https://i.imgur.com/TbtwkyW.jpg" width="250" />
                  </div>
                  <div className="text-center">
                    <h5>{product.prodName}</h5>
                    <span className="text-success">${product.price}</span>
                  </div>
                  <div>
                    <Link to={`/product/${product.id}`}>
                      <button
                        className="btn btn-outline-dark flex-shrink-0"
                        type="button"
                        style={{ marginLeft: "10px" }}
                      >
                        <i
                          className="bi-bag-fill me-1"
                          style={{ marginRight: "4px" }}
                        ></i>
                        Buy Now
                      </button>
                    </Link>
                    <Link to={`/product/${product.id}`}>
                      <button
                        className="btn btn-outline-dark flex-shrink-0"
                        type="button"
                        style={{ marginLeft: "10px" }}
                      >
                        <i className=""></i>
                        View
                      </button>
                    </Link>
                  </div>
                </div>
              </div>
            ))}
            {/* <img src="https://i.imgur.com/aTqSahW.jpg" width="250" /> */}
          </div>
        </div>
      </>
    );
  }
}

export default ProductGridComponent;

ProductViewComponent.jsx

class ProductViewComponent extends React.Component {
  constructor(props) {
    super(props);

    const windowUrl = window.location.pathname.substring(1);
    console.log("window url for product: ", windowUrl);

    this.state = {
      //id: this.props.match.params.id,
      id: windowUrl.substring(windowUrl.indexOf("/") + 1), //Please fix me, I am vulnerable to SQL Injection
      name: "",
      price: 0,
      vendor: "holder vendor",
      description: "",
    };
    console.log("ID: ", this.state.id);
  }

  componentDidMount() {
    ProductService.getProductById(this.state.id).then((res) => {
      let product = res.data;

      this.setState({
        name: product.prodName,
        price: product.price,
        vendor: product.vendorName,
        description: product.description,
      });
    });
  }

  render() {
    return (
...
  <button
                    className="btn btn-outline-dark flex-shrink-0"
                    type="button"
                    style={{ marginLeft: "10px" }}
                    onClick={() =>
                      this.props.onAddToCart(
                        this.state.id,
                        this.state.name,
                        this.state.description,
                        this.state.price
                      )
                    }
                  >
                    <i className="bi-cart-fill me-1"></i>
                    Add to cart
                  </button>
...

Shadowroot : Not getting the correct target for event listener

I have a webpage with a modal with a custom dropdown under a shadowroot as follows:

<div id="main">
#shadow-root
<div class="modal fade in" id="sample-modal">
    <div class="modal-dialog modal-xl" role="dialog" aria-hidden="true">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" style="font-size:0.85rem" id="download-modal-label">Modal Title</h6>
            </div>
            <form onsubmit="return false;">
                <div class="modal-body" id="modal-body" style="overflow: inherit !important">
                    <div class="dropdown">
                        <button onclick="myFunction()" class="dropbtn">Dropdown</button>
                        <div id="myDropdown" class="dropdown-content">
                        <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
                        <a href="#about">About</a>
                        <a href="#base">Base</a>
                        <a href="#blog">Blog</a>
                    </div>
                   </div>
                </div>
            </form>
        </div>
    </div>
</div>

For this, I want to add an event listener where if I click anywhere besides the dropdown, I hide the dropdown div. For this, I added the event listener as follows:

let root = document.getElementById("main").shadowRoot;
$(root).on("click", function(e) {
            var clickedOn=$(e.target);
        });

But this doesn’t seem to work at all. I tried attaching the click event listener to the document, to check the event target as follows:

$(document).on("click", function(e) {
            var clickedOn=$(e.target);
        });

This event listener is triggered, but the target element ‘e’ it shown as the <div id="main"> irrespective of if I click on any element including the dropdown element under the modal. How do I add the event listener where I get the correct element under the shadowRoot which was clicked on using the ‘click’ event listener?

fetch / response.text() messes up the utf-8

I am currently fetching(https://data.ssb.no/api/v0/dataset/49678.csv?lang=no) in javascript. I havent had any problem with fetching other sources so far but now I keep getting a issue with the decoding/encoding. When fetching in postman everything works fine and it returns the values “æøå”. However when I try to fetch this in node it gives a question mark where “æøå” is. I have a feeling something is off with the encoding however it prints fine in postman?

POSTMAN
0219 Bærum (-2019)";"0000 Alle husholdninger";"2005";"Inntekt etter skatt, median (kr)";411000
VSCODE:
"1621 �rland (-2017)";"0002 Par uten barn";"2020";"Inntekt etter skatt, median (kr)";.
async function FetchDataInntekt() {
  const url = "https://data.ssb.no/api/v0/dataset/49678.csv?lang=no";
  let dataresult = null
  const data = await fetch(url, {
    method: "GET",
    headers: { "Content-Type": "text/html; charset=UTF-8" }
  })
  console.log(data.body)
  let response = await data.text();
console.log(reponse)
}

The console.log(data.body)

<ref *1> Gunzip {
  _writeState: Uint32Array(2) [ 0, 0 ],
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    constructed: true,
    sync: false,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: null,
    closed: false,
    closeEmitted: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    dataEmitted: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {
    prefinish: [Function: prefinish],
    unpipe: [Function: onunpipe],
    error: [ [Function: onerror], [Function (anonymous)] ],
    close: [Function: bound onceWrapper] { listener: [Function: onclose] },
    finish: [Function: bound onceWrapper] { listener: [Function: onfinish] }
  },
  _eventsCount: 5,
  _maxListeners: undefined,
  _writableState: WritableState {
    objectMode: false,
    highWaterMark: 16384,
    finalCalled: false,
    needDrain: false,
    ending: false,
    ended: false,
    finished: false,
    destroyed: false,
    decodeStrings: true,
    defaultEncoding: 'utf8',
    length: 6406,
    writing: true,
    corked: 0,
    sync: false,
    bufferProcessing: false,
    onwrite: [Function: bound onwrite],
    writecb: [Function: nop],
    writelen: 6406,
    afterWriteTickInfo: null,
    buffered: [],
    bufferedIndex: 0,
    allBuffers: true,
    allNoop: true,
    pendingcb: 1,
    constructed: true,
    prefinished: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    errored: null,
    closed: false,
    closeEmitted: false,
    [Symbol(kOnFinished)]: []
  },
  allowHalfOpen: true,
  bytesWritten: 0,
  _handle: Zlib {
    onerror: [Function: zlibOnError],
    buffer: <Buffer 1f 8b 08 00 00 00 00 00 00 03 bc bd cd 8e a5 b9 91 a6 b9 9f ab 70 d4 4a 0d 54 cd 7c fc 27 7b 56 6a a0 0b d5 c0 74 4f 43 1a f4 3e 85 8c ca 4e 64 2a 53 ... 6356 more bytes>,
    cb: [Function (anonymous)],
    availOutBefore: 16384,
    availInBefore: 6406,
    inOff: 0,
    flushFlag: 2,
    [Symbol(owner_symbol)]: [Circular *1]
  },
  _outBuffer: <Buffer 22 72 65 67 69 6f 6e 22 3b 22 68 75 73 68 6f 6c 64 6e 69 6e 67 73 74 79 70 65 22 3b 22 e5 72 22 3b 22 73 74 61 74 69 73 74 69 6b 6b 76 61 72 69 61 62 ... 16334 more bytes>,
  _outOffset: 0,
  _chunkSize: 16384,
  _defaultFlushFlag: 2,
  _finishFlushFlag: 2,
  _defaultFullFlushFlag: 3,
  _info: undefined,
  _maxOutputLength: 4294967296,
  _level: -1,
  _strategy: 0,
  [Symbol(kCapture)]: false,
  [Symbol(kCallback)]: null,
  [Symbol(kError)]: null
}
```

What is the problem and why does it not return in utf8 like it does in postman and how can I encode/decode it to utf8? I have fetched from many other sites with no problem like this.

Search accordion content for ID and open

I am using a basic accordion plugin where each item is added as a separate Gutenberg Block. The plugin does not allow me to add an ID to each block, only a class. When I try to add an ID within the Gutenberg code it returns the error ‘this block contains invalid content’- it’s also impractical for the clent.

While I don’t have control over the plugins ability to facilitate ID’s, the content in each panel is made up of ACF blocks where I can add ID’s.

I need to link to each panel from anchor links but this does not currently work as the ID’s reside within the collapsed accordion and so nothing happens.

Is there a way to search hidden content for a ID’s and then open its parent accordion panel?

This is how the accordion is structured by the plugin with an ACF map section as the content as an example

<div class=".aab__accordion_container">
   <div class=".aab__accordion_head">
      <div class=".aab__accordion_heading .aab_right_icon">
        <h4>the heading</h4>
      </div>
   </div>
   <div class=".aab__accordion_body">
      <section id="map-section">
         Content
      </section>
    </div>
</div>

An active accordion gets the class

.aab__accordion_body--show

added to

.aab__accordion_body

This switches between aria exanded: true or false on the accordion body and the CSS is:

.wp-block-aab-accordion-block .aab__accordion_body {
    display: block !important;
    position: absolute !important;
    top: -9999px !important;
    left: -9999px !important;
}

.wp-block-aab-accordion-block .aab__accordion_body.aab__accordion_body--show {
    position: relative !important;
    top: 0 !important;
    left: 0 !important;
}

I switched it to this css from the original ‘display none/block’ for screen readers and in hopes it would make the task easier but the page still just re-loads at the top with no effect.

To complicate things even more, these accordion panels also reside inside a Gutenberg group

The URL is here

http://staging.caledoniaworldwide.com/package/package-template-1

Thanks in advance

Google Map How to clear poligon and marker

I can not speak English well. Google Map How to clear poligon and marker? Help me please. I want poligon and market to be deleted when I click the button. I tried but I couldn’t.
Myscript :

function initMap() {

....
    function attachPolygonInfoWindow(polygon) {
        .....
    }
    google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
        $(".clear").removeClass("d-none");
        if (e.type == "polygon") {
            drawingManager.setOptions({
                drawingControl: false,
            });
            allOverlays.push(e);
            if (e.type != google.maps.drawing.OverlayType.MARKER) {
                drawingManager.setDrawingMode(null);
                var newShape = e.overlay;
                newShape.type = e.type;
                google.maps.event.addListener(newShape, "click", function() {
                    setSelection(newShape);
                });
                    var path = newShape.getPath();
                    google.maps.event.addListener(path, "insert_at", function() {
                        attachPolygonInfoWindow(newShape);
                    });
                    google.maps.event.addListener(path, "set_at", function() {
                        attachPolygonInfoWindow(newShape);
                        var data = "";
                        $.each(e.overlay.getPath().getArray(), function(key, latlng) {
                            var lat = latlng.lat();
                            var lon = latlng.lng();
                            data += lat + " - " + lon + "<br>";
                        });
                        $(".map_coordinat").html(map.getCenter().lat() + " - " + map.getCenter().lng());
                        $(".poligon_coordinat").html(data);
                    });
                    attachPolygonInfoWindow(newShape);
                }
                setSelection(newShape);
            }
        
    });
}

Object, swiperjs, destructure, array, map, filter, forEach

I have two question about my project.

  1. Today I put swiperJS in my project and when you try to click Book in some items my slider move and don’t open the modal. When you try to click on Fiesta Hotel, after loading the web, it doesn’t open the modal. This is my first time with SwiperJS and maybe someone has the same problem and can tell me what’s wrong.

  2. I make modal and do foreach on every book button, now i create the array of object, and wanna connect ModalBtns.id with cities.id how i can do?? I try map, filter and everything but still dont know how to connect this item because i wanna add info to modal dynamically. Like price for ticket and everything. I know in the future react it will be simply to use for operation like that, but i try do in JS

https://margsoftbf.github.io/trip-rest-website/

https://github.com/margsoftbf/trip-rest-website