Remember Scroll Position With Javascript when page is redirected with php $_GET statement

I’m currently using Javascript to remember the scroll position of my page. The problem I am having is that when I use PHP to update something in my database and return back to the page with a $_GET statement, the script does not work to maintain the previous scroll position.

Example: if I am on a page named settings.php and I refresh the page while in a new scroll location, the script works. However, if I use a form to process some PHP data and return to something akin to settings.php?id=1 the script does not remember the scroll position. Is there a way to fix this? Any help would be greatly appreciated. The code is below.

<script type="text/javascript"> <!-- This is the Java Script For maintaining scroll position. Useful for when someone is adding card quantities -->
            $(document).ready(function (e) {
                let UrlsObj = localStorage.getItem('rememberScroll');
                let ParseUrlsObj = JSON.parse(UrlsObj);
                let windowUrl = window.location.href;

                if (ParseUrlsObj == null) {
                    return false;
                }

                ParseUrlsObj.forEach(function (el) {
                    if (el.url === windowUrl) {
                        let getPos = el.scroll;
                        $(window).scrollTop(getPos);
                    }
                });

            });

            function RememberScrollPage(scrollPos) {

                let UrlsObj = localStorage.getItem('rememberScroll');
                let urlsArr = JSON.parse(UrlsObj);

                if (urlsArr == null) {
                    urlsArr = [];
                }

                if (urlsArr.length == 0) {
                    urlsArr = [];
                }

                let urlWindow = window.location.href;
                let urlScroll = scrollPos;
                let urlObj = {url: urlWindow, scroll: scrollPos};
                let matchedUrl = false;
                let matchedIndex = 0;

                if (urlsArr.length != 0) {
                    urlsArr.forEach(function (el, index) {

                        if (el.url === urlWindow) {
                            matchedUrl = true;
                            matchedIndex = index;
                        }

                    });

                    if (matchedUrl === true) {
                        urlsArr[matchedIndex].scroll = urlScroll;
                    } else {
                        urlsArr.push(urlObj);
                    }


                } else {
                    urlsArr.push(urlObj);
                }

                localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));

            }

            $(window).scroll(function (event) {
                let topScroll = $(window).scrollTop();
                console.log('Scrolling', topScroll);
                RememberScrollPage(topScroll);
            });
        </script>

Why DashboardCode/BsMultiSelect looks ugly in my app?

I need to add dropdown to laravel app with bootstrap 5.1, but without jquery as it is not used in my app.
I found package https://github.com/DashboardCode/BsMultiSelect and I installed it with npm and in file resources/js/bootstrap.js
I added lines :

window._ = require('lodash');

try {
    require('bootstrap');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


import { createPopper } from "@popperjs/core";
import { ModuleFactory as bsMultiSelectFactory } from "@dashboardcode/bsmultiselect";

const multiSelectEnv = {window, createPopper};
const multiSelect = bsMultiSelectFactory(multiSelectEnv).BsMultiSelect;

window.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("select[multiple]").forEach((select) => {
    multiSelect(select);
  });
});

In blade.php file with select definition :

<div class="col-md-4 d-inline-flex justify-content-start align-items-start">
    <select name="filter_html_block_id[]" id="filter_html_block_id" multiple>
        <option value=""> - Select all html blocks - </option>
        @foreach($htmlBlocksSelectionArray as $htmlBlocksSelection )
            <option value="{{ $htmlBlocksSelection['id'] }}"
                    @if ( in_array($htmlBlocksSelection['id'], $filter_html_block_id) or count($htmlBlocksSelection) === 0) selected @endif>
                {{ $htmlBlocksSelection['name'] }}
            </option>
        @endforeach
    </select>

    <a class="nav-link link-secondary ml-2" onclick="javascript:filter_html_block_idOnChange()">
        <i class="bi bi-filter" ></i>
    </a>

</div>

I also added css styles :

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@dashboardcode/[email protected]/dist/css/BsMultiSelect.min.css">

@section('scripts')
    <script>
        ...

But when page is opened I see : https://prnt.sc/djQonuPc2ZIw

When I click on select input I see : https://prnt.sc/_kp_Uq5MdXz7
In package.json :

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "@popperjs/core": "^2.10.2",
        "axios": "^0.21",
        "bootstrap": "^5.1.3",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "resolve-url-loader": "^5.0.0",
        "sass": "^1.32.11",
        "sass-loader": "^11.0.1"
    },
    "dependencies": {
        "@dashboardcode/bsmultiselect": "^1.1.18"
    }
}

What is wrong and how can it be fixed ?

Thanks!

Firebase cloud functions errors

Greetings of the day to everyone,

So I’m having a really hard time with Firebase cause there’s just so many versions and things going on. Its extremely complicated. I wanted to achieve some functionality which is not available through the client modular web 9 version.

So I have been trying to use the Cloud functions to just get the list of all the collections in a document.

My cloud function looks like this so far –

const functions = require("firebase-functions");
const admin = require('firebase-admin');
const { object } = require("firebase-functions/v1/storage");
admin.initializeApp();
const db = admin.firestore();

exports.addMessages = functions.https.onCall(async (data, context) => {
    // Grab the text parameter.
    const original = data.text;
    var test;
    const writeResult = admin.firestore().collection('users').doc(original)

    const collections = await writeResult.listCollections();
    collections.forEach(collection => {
        console.log('Found subcollection with id:', collection.id);
        test = collection.id;

    });
    // Send back a message that we've successfully written the message

    return { id: test }
});

I call this function on my front end simply like this —

const functions = getFunctions();
    const addMessage = httpsCallable(functions, 'addMessages');

    const Cloud = () => {
        addMessage({ docPath: `users/${userProfile.uid}` })
            .then(function (result) {
                var collections = result.data.collections;
                console.log(collections);
            })
            .catch(function (error) {
                // Getting the Error details.
                var code = error.code;
                var message = error.message;
                var details = error.details;
                // ...
            });
    }

However, I get a 500 ERROR. I have checked the payload and everything, the data is being passed and the function is being called but there is some other kind of bug that I seem to be missing.

If anyone has any ideas please do let me know.

my zip file is getting corrupt when its download

i am trying to download zip which contain multiple files now i am able to download zip but files inside get’s corrupt enter code here

downloadListConfig = () => {
    const { selectedList } = this.state;
    const list_ids = [];
    selectedList.forEach(list => {
      list_ids.push(list.id);
    });
    this.downloadListFile(list_ids);
  };
  // 1
  downloadListFile = list_ids => {
    downloadListConfig({ list_ids })
      .then(response => {
        const { body, headers } = response;
        let fileName = headers['content-disposition'].split('filename=')[1].split(';')[0];
        let data;
        if (headers['content-type'] === 'application/json') {
          data = new Blob([JSON.stringify(body)], { type: 'text/json' });
        } else {
          data = new Blob([body], { type: 'octet/stream' });
          // data = new Blob([body], {type})
        }
        const jsonURL = window.URL.createObjectURL(data);
        const tempLink = document.createElement('a');
        tempLink.href = jsonURL;
        tempLink.setAttribute('download', `${fileName}`);
        tempLink.click();
      })
      .catch(err => {
        console.log(err);
      });
  };

why local storage not working react js in real time?

I’m doing this code from a blog example as local storage with react .but it doesn’t work in real-time after refreshing it. how can I do it in real-time? I think it can use the effect hook used to be solved but I cannot implement it, does anybody help me with this solution

import './App.css';
import React, { useState,useEffect } from 'react';

function App() {
  
  const [name, setName] = useState('');
  const [pwd, setPwd] = useState('');
  
 
  
  const handle = () => {
     localStorage.setItem('Name', name);
     localStorage.setItem('Password', pwd);
  };
  const remove = () => {
     localStorage.removeItem('Name');
     localStorage.removeItem('Password');
  };
  return (
    <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            placeholder="Password"
            value={pwd}
            onChange={(e) => setPwd(e.target.value)}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {localStorage.getItem('Name') && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {localStorage.getItem('Password') && (
            <div>
               Password: <p>{localStorage.getItem('Password')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   ); 
}

export default App;
    

This code has no problem but I want to work with real-time when I click done it shows real-time how do I?

Js function that shows a div as a result of a search but the disappear when something else is searched

Baby developer here. So, I’m creating a weather app using Axios and open weather API to grab live forecast info. I created an empty div in my HTML and then created a function that would show an alert at the bottom of the page ONLY if the city that was searched for has an active weather alert. It works great, the only issue I have is that once I search for a city that has an active alert the alert just stays there, does not disappear unless I refresh the page.
So for example if I search for Paris and paris has an active alert it appears but then if i search for rome and rome does not have an active alert, the paris alert just stays there until I refresh the page

Heres my function: I’m using css html and js only

function showAlerts(response) {
  let alertsElement = document.querySelector("#alerts");
  if (response.data.alerts && response.data.alerts.length > 0) {
    alertsElement.style.backgroundColor = "#981f15";
    alertsHTML = `<div class="alert"> ⚠️ ALERT! ${response.data.alerts[0].event} </div>`;
    alertsElement.innerHTML = alertsHTML;
  } else if (response.data.alerts && response.data.alerts.length < 1) {
    alertsElement.innerHTML = "";
  }
}

Heres a link to the API I’m using and my Git repository

https://openweathermap.org/api/one-call-3

https://github.com/SarahAbousenna/vanilla-weather-application

web scraping javascript span element python

Context: I would like to get data located in nested span elements. On the page, the span elements update when I scroll over a particular element on that page. I want to get all data eventually but right now I’m struggling with even getting a single value from a span element.

<span id="spanId01" class="item-template templates-cell grid-cell column-0 cells-normal " title="">TEXT I WANT</span>

Set up:
Selenium 4.3.0
geckodriver 0.31.0
Firefox 102.0.1

# specify the url
urlpage = 'http://....htm' 
print(urlpage)
driver = webdriver.Firefox(executable_path = <executable path>)

# get web page
driver.get(urlpage)
# execute script to scroll down the page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
# sleep for 30s
time.sleep(30)

results = driver.find_elements('xpath', '//*[@id="spanId01"]')
print(results)

Output:
[]
or
“
I already tried this to get the text of the span element:

results = driver.find_elements('xpath', '//*[@id="spanId01"]').text
results = driver.find_elements('xpath', '//*[@id="spanId01"]').getText()
results = driver.find_elements('xpath', '//*[@id="spanId01"]').get_attribute("value")

What am I missing? Could the website have a web scraper blocker?
Even when I get the text of a single span element how would I get text values of multiple span elements that are updated when scrolling?

React.js cant find image with variable in it’s path

I didn’t use React before, so my question could be silly, but anyway, i have simple project with TailwindCSS, i want to check if image exists and set a class pointing to that image, but Reacts gives me an error.

App.js:

import './App.css';
import Header from './Header';
import Tools from './Tools';

function App() {
  return (
    <div>
      <header>
        <Header/>
      </header>
      <main className='flex w-[80vw] mx-auto'>
        <div id='tools'>
          <Tools/>
        </div>
      </main>
    </div>
  );
}

export default App;

Tools.js:

const Tools = () => {
    return (
        <main className="my-4">
            <h1 className="text-4xl">Инструменты</h1>
            <div>
                <ul>
                    {Box("Big test", "TESTS ARE COOL", "construction.png", "#!")}
                </ul>
            </div>
        </main>
    )
}

const Box = ({name, desc, img, href}) => {
    let imgExists;
    try{
        require(`./img/tools/${img}`);
        imgExists = true;
    }
    catch(err){
        imgExists = false;
    }
    return (
        <li>
            <a href={href}>
                <div>
                    <h2>{name}</h2>
                    <p>{desc}</p>
                </div>
                <div className={imgExists === true ? `bg-[url('./img/tools/${img}')]` : "not-found"}></div>
            </a>
        </li>
    )
}

export default Tools

(There are no errors in Header.js)

Error:

Failed to compile.

Module not found: Error: Can't resolve './img/tools/${img}' in '/home/anime/PRACTICE/ddracenet/src'
ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/index.css) 5:36-82
Module not found: Error: Can't resolve './img/tools/${img}' in '/home/anime/PRACTICE/ddracenet/src'

webpack compiled with 1 error

TypeError: Cannot read properties of undefined (reading ‘then’) – while Mocking Fetch call in Jest

This is the file containing the fetch call, which just sends some locally stored json file.

// eslint-disable-next-line import/prefer-default-export
export const get = () => {
  // eslint-disable-next-line no-undef
  return fetch('data/posts.json').then((res) => res.json());
};

My test where I mock the fetch method and Promise.resolve a mock array.

import { get } from './posts';

const mockData = [
  {
    "id": "ig-1",
    "accountId": "IG",
    "accountIcon": "/images/ig-icon.svg",
    "accountName": "IG account",
    "accountImageInitial": "J",
    "imageUrl": "/images/social_logo.png",
    "caption": "test",
    "timestamp": 1635510651638
  },
  {
    "id": "fb-1",
    "accountId": "FB",
    "accountIcon": "/images/fb-icon.svg",
    "accountName": "FB account",
    "accountImageInitial": "J",
    "imageUrl": "/images/social_logo.png",
    "caption": "test",
    "timestamp": 1635510051638
  }
];

global.fetch = jest.fn(() => 
  Promise.resolve({
    json: () => Promise.resolve(mockData)
  })
);

describe('The posts API controller', () => {
  test('get() returns expected default payload', async () => {
    const result = await get();
    expect(fetch).toHaveBeenCalledTimes(1);
    expect(result).toBeTruthy();
  });
});

Error

TypeError: Cannot read properties of undefined (reading ‘then’)

TypeError: Cannot read properties of undefined (reading 'then')

      2 | export const get = () => {
      3 |   // eslint-disable-next-line no-undef
    > 4 |   return fetch('data/posts.json').then((res) => res.json());
        |          ^
      5 | };

enter image description here

Unsure as to why I’m getting this error, as it appears that I have mocked fetch correctly?

Refused to apply style to form [duplicate]

I am trying to build a signup page using one of the templates by boostrap, but after I downloaded the source code and tried running the file, the browser gives me this message: Refused to apply style from ‘http://localhost:3000/style.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I have added my files below.

    const express = require("express");
    const bodyParser = require("body-parser");
    const app = express();

    app.listen(3000, ()=> {
        console.log("Server is running on port 3000");
    });

    app.get("/", (req, res) =>{
        res.sendFile(__dirname + "\signup.html");
    })

html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.form-signin {
  max-width: 330px;
  padding: 15px;
}

.form-signin .form-floating:focus-within {
  z-index: 2;
}

.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.98.0">
    <title>Signin Template · Bootstrap v5.2</title>

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }

      .b-example-divider {
        height: 3rem;
        background-color: rgba(0, 0, 0, .1);
        border: solid rgba(0, 0, 0, .15);
        border-width: 1px 0;
        box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);
      }

      .b-example-vr {
        flex-shrink: 0;
        width: 1.5rem;
        height: 100vh;
      }

      .bi {
        vertical-align: -.125em;
        fill: currentColor;
      }

      .nav-scroller {
        position: relative;
        z-index: 2;
        height: 2.75rem;
        overflow-y: hidden;
      }

      .nav-scroller .nav {
        display: flex;
        flex-wrap: nowrap;
        padding-bottom: 1rem;
        margin-top: -1px;
        overflow-x: auto;
        text-align: center;
        white-space: nowrap;
        -webkit-overflow-scrolling: touch;
      }
    </style>

    
    <!-- Custom styles for this template -->
    <link  rel="stylesheet" href="../styles.css">
  </head>
  <body class="text-center">
    
<main class="form-signin w-100 m-auto">
  <form>
    <!-- <img class="mb-4" src="../assets/brand/bootstrap-logo.svg" alt="" width="72" height="57"> -->
    <h1 class="h3 mb-3 fw-normal">Please sign in</h1>

    <div class="form-floating">
      <input type="email" class="form-control" id="floatingInput" placeholder="[email protected]">
      <label for="floatingInput">Email address</label>
    </div>
    <div class="form-floating">
      <input type="password" class="form-control" id="floatingPassword" placeholder="Password">
      <label for="floatingPassword">Password</label>
    </div>

    <div class="checkbox mb-3">
      <label>
        <input type="checkbox" value="remember-me"> Remember me
      </label>
    </div>
    <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2017–2022</p>
  </form>
</main>


    
  </body>
</html>

If the external value changes in the middle of setInterval or setTimeout, I want to recognize it and stop setInterval or setTimeout

 import React, {useState} from 'react';
 
 //...
    const [isPreparationTime, setIsPreparationTime] = useState(true);


  useEffect(() => {
    if (isPreparationTime) {
      runPosenet();
    }
  }, [isPreparationTime]);
  
  
  const runPosenet = async () => {
    const net = await posenet.load({
      inputResolution: { width: 640, height: 480 },
      scale: 0.8,
    });

    const temp = setInterval(() => {
      detect(net);
    }, 1000);

    setTimeout(() => clearInterval(temp) & console.log("done"), 3000);
  };
  
  const detect = async (net) => {
    if (
      typeof firstParticipantRef.current !== "undefined" &&
      firstParticipantRef.current !== null &&
      firstParticipantRef.current.video.readyState === 4
    ) {
      const firstVideo = videoReference(firstParticipantRef);
      const secondVideo = videoReference(secondParticipantRef);

      const firstVideoPose = await net.estimateSinglePose(firstVideo);
      const secondVideoPose = await net.estimateSinglePose(secondVideo);

      drawCanvas(
        firstVideoPose,
        firstVideo,
        firstVideo.width,
        firstVideo.height,
        firstCanvas
      );
      drawCanvas(
        secondVideoPose,
        secondVideo,
        secondVideo.width,
        secondVideo.height,
        secondCanvas
      );

      if (isReady) {
        addFirstParticipantPose(firstVideoPose);
        addSecondParticipantPose(secondVideoPose);
      } else {
        addPreStartFirstParticipantPose(firstVideoPose);
        addPreStartSecondparticipantPose(secondVideoPose);
      }
    }
  };
  //...

I want setInterval to exit before setTimeout is finished. I’ve tried clearTimeout or clearInterval, but it doesn’t work because it’s inside an async function.

I wanted to quit when isPreparationTime becomes false, so I wrote if(!isPreparation) { clearInterval(temp)} in setInterval, but it does not work. I don’t know what to do. Please help.

Typing a Nested Method

I’m trying to understand how I can properly type a nested method… a method that returns a method, which returns a value. This is useful in things like Vuex getters, but I’d like to remove Vuex from the equation and just focus on the TypeScript aspect of it. Here’s a Fiddle, and the code:

interface IData {
    name: string;
}

type IGetters = {
    data(getters: IGetters): IData;
    getDataByKey: (getters: IGetters) => (name: string) => string;
    getName(getters: IGetters): string;
}

const getters: IGetters = {
    data(getters) {
        return {
            name: 'Hello'
        };
    },
    getDataByKey: (getters) => (name) => {
        return getters.data[name as keyof typeof getters.data];
    },
    getName(getters) {
        return getters.getDataByKey('name');
    }
}

The issue I’m having is getName. When invoking getDataByKey, TS throws TS-2345 Argument of type 'string' is not assignable to parameter of type 'IGetters'. To me, it seems like it thinks I need to call the function that has (getters) as the params, but that’s not how this works in Vuex.

I saw this SO answer, and I tried to implement what was done, but it didn’t work, so I’m pretty sure I didn’t implement it properly. Does anyone have any suggestions?

Uncaught (in promise) TypeError: relativeURL.replace is not a function

I am trying to use axios to get data. I have setup .env file,AxiosSetup,ApiConstants that contains hard coded api
.env file

REACT_APP_BASE_URL= "http://localhost:3000/"

AxiosSetup.js

import axios from 'axios';

const customAxios = axios.create({
  baseURL: import.meta.env.REACT_APP_BASE_URL,
  headers: {
    Accept: '*/*',
    'Content-Type': 'application/json',
  },
  timeout: 5000,
});

export default customAxios;

ApiConstants.js

const ApiConstants = {
  COMPANY: {
    ADD: () => {
      return 'company/';
    },
    FIND_ALL: () => {
      return 'company/';
    },
    FIND_ONE: (companyId) => {
      return 'company/' + companyId;
    },
  },
};
export default ApiConstants;

This is where I am writing down the get request

  const companyResponse = async () => {
    const response = await customAxios.get(ApiConstants.COMPANY.FIND_ALL);
    setCompanies([response.data]);
  }

Errors I Have been getting:

Uncaught (in promise) TypeError: relativeURL.replace is not a function

Why can’t I delete a record from the table using AJAX and PHP?

I used SweetAlert with AJAX for displaying the delete modal, but the delete button isn’t working. Can anyone tell me what I did wrong with my code? This is what I have done so far. What’s wrong with my AJAX and PHP code? Here are the snippets for my PHP and JS codes.

code.php

else if(isset($_POST['delete_product_btn']))
{
    $product_id = mysqli_real_escape_string($con, $_POST['product_id']);

    $product_query = "SELECT * FROM products WHERE id='$product_id' ";
    $product_query_run = mysqli_query($con, $product_query);
    $product_data = mysqli_fetch_array($product_query_run);

    $image = $product_data['image'];

    $delete_query = "DELETE FROM products WHERE id='$product_id' ";

    $delete_query_run = mysqli_query($con, $delete_query);

    if($delete_query_run)
    {
        if(file_exists("../uploads/".$image))
        {
            unlink("../uploads/".$image);
        }

        // redirect("products.php", "Category deleted");

        echo 200;
    }
    else
    {
        // redirect("products.php", "Something went wrong");    
        echo 500;   
    }
}

SweetAlert Delete Modal

custom.js

$(document).ready(function(){


    $('.delete_product_btn').click(function (e) {
        e.preventDefault();

        swal({
          title: "Are you sure?",
          text: "Once deleted, you will not be able to recover!",
          icon: "warning",
          buttons: true,
          dangerMode: true,
        })
        .then((willDelete) => {
          if (willDelete) {
            $.ajax({
                method: "POST",
                url: "code.php",
                data: {
                    'product_id':id,
                    'delete_product_btn': true
                },

                success: function(response) {
                    if(response == 200)
                    {
                        swal("Good job!", "Product deleted successfully!", "success");                      
                    }
                    else if(response == 500)
                    {
                        swal("Error!", "Something went wrong!", "error");
                    }
                }

            });
          } 

        });

    });

});

footer.php

<footer class="footer pt-5">
      <div class="container-fluid">
        <div class="row align-items-center justify-content-lg-between">
          <div class="col-lg-6 mb-lg-0 mb-4">
          </div>
          <div class="col-lg-6">
            <ul class="nav nav-footer justify-content-center justify-content-lg-end">

             <li class="nav-item">
                <a href="#" class="nav-link pe-0 text-muted" target="_blank">About Us</a>
              </li>

               <li class="nav-item">
                <a href="#" class="nav-link pe-0 text-muted" target="_blank">Service</a>
              </li>

               <li class="nav-item">
                <a href="#" class="nav-link pe-0 text-muted" target="_blank">Contact</a>
              </li>

              <li class="nav-item">
                <a href="#" class="nav-link pe-0 text-muted" target="_blank">About</a>
              </li>


            </ul>
          </div>
        </div>
      </div>
    </footer>
  </main>

    <script src="assets/js/jquery-3.6.0.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/perfect-scrollbar.min.js"></script>
    <script src="assets/js/smooth-scrollbar.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="assets/js/custom.js"></script>

    <!-- JavaScript -->
    <script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>


    <script type="text/javascript">

      <?php if(isset($_SESSION['message'])) { ?>

      alertify.set('notifier','position', 'top-right');
      alertify.success('<?= $_SESSION['message'] ?>');

      <?php unset($_SESSION['message']); } ?>


    </script>

  </body>

</html>

Cant make autocomplete work (Google Maps )

I have this project i’m working in my site.
In a page of it, its asking from user an address and creating a simple map and stores the values of Lat and Lon for future use.

Javascripts are :

<script>
 
var apiKey = '***(MYAPIKEY)***';
var longitude, latitude, map;

jQuery(document).ready(function($) {
  $('#find-address').click(function() {
    var address = $('#address').val();
    var postcode = $('#postcode').val();
    var addressClean = address.replace(/s+/g, '+');
    var postcodeClean = postcode.replace(/s+/g, '+');
    var apiCall = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + addressClean + ',+' + postcodeClean + '&key=' + apiKey + '';

    //$.getJSON(apiCall,function (data, textStatus) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      address: addressClean + "," + postcodeClean
    }, function(results, status) {
      console.log(status);
      if (status == 'OK') {
        longitude = results[0].geometry.location.lng();
        latitude = results[0].geometry.location.lat();
        document.getElementById("long").value = longitude;
        document.getElementById("lat").value = latitude;
        // geocoder is asynchronous, do this in the callback function
        longitude = $("input#long").val();
        latitude = $("input#lat").val();

        if (longitude && latitude) {
          longitude = parseFloat(longitude);
          latitude = parseFloat(latitude);

          initMap(longitude, latitude);
        }
      } else alert("Geocode failed")
    });
  });

  function initMap(longitude, latitude) {
    var myLatlng = new google.maps.LatLng(latitude, longitude);

    var mapOptions = {
      zoom: 16,
      center: myLatlng
    }

    var map = new google.maps.Map(document.getElementById("map-embed-div"), mapOptions);

    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      draggable: true
    });
  };
})
</script>

Part of that web code is :

<form method="post" novalidate="novalidate">
                                      
  <label for="street-address">Type your address</label>
  <div class="input-group input-group-md">
                                           
    <input type="text" name="street-address" placeholder="i.e. 13 London Square, Stockport, 
    Manchester, UK"  size="80" id="address" aria-required="true" aria-invalid="false"  />
    <input type="text" hidden name="post-code" value="02139" size="40" id="postcode" aria- 
    required="true" aria-invalid="false" placeholder="Post Code" />
                                        
    <input type="hidden" id="lat" value=""><input type="hidden" id="long" value="">
     <input type="hidden" name="addressField1" value="">
     <a href="#" id="find-address" title="Find Address" type="button" class="btn btn-info 
     btn-flat"><i class="fa fa-search" aria-hidden="true"></i></a>
                                        
    </div>
    <div id="map-embed">
    <br><br><br>
    <div id="map-embed-div" style="height:250px;width:100%;"></div>
  </div>
</form>
        

                   

How can I add autocomplete in my input field ?
PS Ι guess autocomplete should work on windows load because otherwize it wouldnt be live… and my code starts to work only when i submit the button.
Any help ?