Ajax and flask The server responded with a status of 405 (METHOD NOT ALLOWED)

I’m trying to create a web app and finished the front end, I’m new to java scrip (first day with it), and I’m having issues with my login. I keep getting a The server responded with a status of 405 (METHOD NOT ALLOWED) error, I think it has to do with my calling a request to my API (written in java springboot) 192.168.1.31:6969/debug. also if this helps I’m able to make requests to the API in postman and I’ve done similar projects and have never had an issue like this so I think its just Ajax. I’ve tried everything I’ve seen online by enabling cors on everything, flask, the ajax script itself, and it won’t work. Please help me.

This is my login.html

{% extends 'base.html' %}
{% include 'header.html'%}


{% block title %} Login {%endblock%}

{%block body%}

<div class="container">
    <div class="row">
        <div class="p-5 bg-light">
            <form action="" method="POST">
                <b><h1 class="float-center text-center">Login</h1></b>
                <div class="col-xs-8 col-lg-offset-2">
                    <div class="form-group">
                        <h3>Username:</h3>
                        <input type="text" class="form-control" id="username" required="1">
                    </div>
                </div>
                <div class="col-xs-8 col-lg-offset-2">
                    <div class="form-group">
                        <h3>Password:</h3>
                        <input type="password" class="form-control" id="password" required="1">
                    </div>
                </div>
                <br>
                <div class="form-group">
                    <button class="btn btn-lg btn-success pull-right" onclick="login()" type="submit">Login</button>
                </div>

                <script>
                    function login(){
                        var username = document.getElementById("username").value;
                        var password = document.getElementById("password").value;

                        var response = ""

                        var settings = {
                            'cache': false,
                            'dataType': "jsonp",
                            "async": true,
                            "crossDomain": true,
                            "url": "http://192.168.1.31:6969/debug",
                            "method": "POST",
                            "headers": {
                                "accept": "application/json",
                                "Access-Control-Allow-Origin":"*"
                            }
                        }
                        $.ajax(settings).done(function (response) {
                            jQuery.support.cors = true;
                            response = response.data
                            console.log(response);

                        });

                        if(response != "-1"){
                            setCookie('session_token', response, 1)
                            window.open('http://localhost:5000/credentials',"_self")
                        }else{
                            window.alert("Username or Password is incorrect!")
                        }
                    }

                    function setCookie(name,value,days) {
                        var expires = "";
                        if (days) {
                            var date = new Date();
                            date.setTime(date.getTime() + (days*24*60*60*1000));
                            expires = "; expires=" + date.toUTCString();
                        }
                        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
                    }

                    function getCookie(name) {
                        var nameEQ = name + "=";
                        var ca = document.cookie.split(';');
                        for(var i=0;i < ca.length;i++) {
                            var c = ca[i];
                            while (c.charAt(0)==' ') c = c.substring(1,c.length);
                            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
                        }
                        return null;
                    }
                </script>
        </form>
        </div>
    </div>

    <a href="credentials">for now use this to go to next page</a>
</div>



<div class="container">
    <footer class="py-3 my-4">
    <p class="text-center text-muted">&copy; 2021 McHugo</p> <p class="text-center text-muted">Developed by Daniel Caminero from &copy;<a href="https://anonyomail.com">Anonyomail</a></p>
    </footer>
</div>


{%endblock%}

app.py

from unicodedata import name
from flask import Flask, render_template
from flask_cors import CORS, cross_origin


app = Flask(__name__)
app.secret_key = "pass"
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'


@app.route('/')
@cross_origin()
def Index():
    return(render_template('login.html'))

@app.route('/shoran')
@cross_origin()
def Shoran():
    return(render_template('shoran.html'))

@app.route('/credentials')
@cross_origin()
def Credentials():
    return(render_template('credentials.html', data = Credentials))


if __name__ == "__main__":
    app.run(debug=True)

How to get the title collection on firebase?

I want to get the tittle of collections in my firebase project to a select, but i only get the responde inside the collection i want that the select show titles of picture #1enter image description here

This is my code i use vuejs:

import Firebase from "firebase";
import { configFirebasecalidair } from "../../../constants/config";
let app = Firebase.initializeApp(configFirebasecalidair, "calidair");
let db = app.database();
let datacalidairef = db
  .ref("CalidAir/")
  .limitToLast(20);
datacalidairef.on("value", (snapshot) => {
      const data = snapshot.val();


  for (let key in data){
      sensors.push(data[key]);
  }
  me.resultsensors = data
  console.log('Resultados',data);
  console.log('sensorelista',sensors);

})

and this is my response
enter image description here

UIComponent.prototype.init.apply(this, arguments)

I am trying to understand several technical points based on JavaScript syntax for this line “UIComponent.prototype.init.apply(this, arguments)” based on the below code snippet.

I have read several times of this link for the similar question: Prototype & Extend in SAPUI5 (Component.js)

But the answer is still not so clear for me. For this answer: “What they’re doing here is very Java-ish. With extend they’re creating a subclass of UIComponent. In this subclass the init method is overridden. When you override a method of the parent object, it’s a good practice to call the parents original method from the method that overrides it. By doing so, you’re avoiding unexpected situations such as variables that have not been defined at the parent etc. Calling the parent’s original method is exactly what the init.apply statement is doing. It’s doesn’t make sense to me to do this twice though.”

To make this answer more clear. I add my comments, please correct me if my understanding is wrong.

  1. Firstly here the parent class refers to the UIComponent itself,
    right? It means the overridden init is only done for the extended
    sub-class, but the parent class UIComponent is still the original
    without change.

  2. From the syntax UIComponent.prototype.init, it means call
    the init from the upper calss of UIComponent, right? UIComponent is
    upper class is Component. So it likes to use apply to binding this –
    ‘the extended sub-class object’ to call the class Component, right?

    sap.ui.define([
    “sap/ui/core/UIComponent”,
    “sap/ui/model/json/JSONModel”,
    “sap/ui/model/resource/ResourceModel”
    ], function (UIComponent, JSONModel, ResourceModel) {
    “use strict”;
    return UIComponent.extend(“myAppAddress.Component”, {
    metadata : {
    “interfaces”: [“sap.ui.core.IAsyncContentCreation”],
    “rootView”: {
    “viewName”: “myAppAddress.view.App”,
    “type”: “XML”,
    /“async”: true, // implicitly set via the sap.ui.core.IAsyncContentCreation interface/
    “id”: “app”
    }
    },
    aaa: function () { console.log(“aaa”)},

       init : function () {
          // call the init function of the parent
          UIComponent.prototype.init.apply(this, arguments);
          // set data model
          var oData = {
             recipient : {
                name : "Sissi, Jacky, Patty"
             }
          };
          var oModel = new JSONModel(oData);
          this.setModel(oModel);
    
          // set i18n model
          var i18nModel = new ResourceModel({
             bundleName: "myAppAddress.i18n.i18n"
          });
          this.setModel(i18nModel, "i18n1");
       }
    });
    

    });

How to build a simple web page Monitor in Javascript

I would like to write a javascript program to monitor a given web page (like a shopify page) and create an alert when a change is detected.

What is the simplest way to implement this in Javascript? Is there any one library that provides tools to monitor page changes? Ideally, this program could run continuously on my computer and create a notification on my phone.

For the phone notification part, I was thinking I could just use a whatsapp Bot to send a text to my phone

access value of JSON by key using ajax doesn’t display result

I have a JSON data looking like this (it’s not an object, it’s an array):

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "[email protected]",
  }
]

and a function to get data and display it using AJAX, I use JSON.parse() to get the JSON from string:
Initialize a XMLHttpRequest object:

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
        var jsonObj = JSON.parse(xhttp.responseText);

Add a new element to the document:

var table='<tr><th>Name</th><th>Email</th></tr>';
        table += '<tr><td>' +
            jsonObj["name"] +
            '</td><td>' +
            jsonObj["email"] +
            '</td></tr>'
        document.getElementById('demo').innerHTML = table;
    }
};

But when I run the browser doesn’t display value in the table field, it shows undefined. Is there something wrong? I also changed to use JSON.stringtify(), but the result still didn’t change. Please help me to figure out the problem

How do I force label and dropdown to be on same line?

I want to force the dropdown and the label to be on the same line. How can I force this. Because for now I get the label : Taste above the dropdown.

export default function MenuItemDisplay() {
    const { menuId, itemId } = useParams();
    const { match } = JsonData;
    const matchData = match.find((el) => el._id_menu === menuId)?._ids ?? [];
    const item = matchData.find((el) => el._id === itemId);
    ...
    return (
        <div>
            <h2 className="text-3xl"> Rule: {item.name}</h2>
            <div className="RuleMetaData">
                Availability :  <Checkbox value={!!item.availability} />
            </div>
            ...
            <div className="RuleMetaData"> 
                Taste : <CustomDropdown style={styles.select} options={TASTE} defaultValue={LIKELIHOOD.find((t) => t.label === item.taste)} />
            </div>
            ...

        </div >
    );
}

CustomDropdown:

export default function CustomDropdown({ style, options, styleSelect, defaultValue, isMulti }) {
    return <div style={style}>
        <Select styles={styleSelect} options={options} defaultValue={defaultValue} isMulti={isMulti} />
    </div>
}

index.css :

.RuleMetaData{
    margin-top: 30px;
    font-size: 20px;
    font-family: ui-sans-serif, system-ui,' -apple-system', BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
    margin-right: 1em;
    display: inline-block;
    vertical-align:middle;
  
  }

Advice Needed PLEASE [closed]

I am new to programming and I want to be an expert web developer. I don’t know , should I build a great programming foundation by learning a programming language like C++ and then learn JavaScript OR Should I learn JavaScript Directly ???

Please add any books or resources for learning the path of your own choice.

THANKS

Why doesn’t Array.from(HtmlCollection) work?

I took d3js code here (this page I can open just by firefox). Here document.getElementsByTagName("circle") is a HtmlCollection. When I do

console.log(Array.from(document.getElementsByTagName("circle")))

it returns an empty array, although collection is fullfil. What could be the reason?

Questions Regarding Displaying Error and Preventing Submission of Form Until Passwords Match

I am trying to display an error informing the user that their passwords do not match, and prevent the submission of said form until the passwords do match.

But I can’t seem to get it to work.

Neither the error displays, nor is submission prevented.

What am I doing wrong, and how do I fix it?

const password = document.querySelector('password');
const passwordError = document.querySelector('#password + span.error');
const confirmpassword = document.querySelector('confirmpassword');





  confirmpassword.addEventListener('input', function (event) {
  if (password.value == confirmpassword.value) {
    passwordError.textContent = '';
    passwordError.className = 'error';
  } else {
    showError();
  }
});

confirmpassword.addEventListener('submit', function (event) {
  if (password.value != confirmpassword.value) {
    showError();
    event.preventDefault();
  }
});

<form novalidate>
      <label for="mail">
        <input type="email" id="mail" name="mail" required minlength="8" placeholder="Email*">
        <span class="error" aria-live="polite"></span>
      </label>
      <label for="password">
        <input type="password" id="mail" name="mail" placeholder="Password*">
        <span class="error" aria-live="polite"></span>
      </label>
      <label for="confirmpassword">
        <input type="password" id="confirmpassword" name="confirmpassword" placeholder="Confirm Password*">
        <span class="error" aria-live="polite"></span>
      </label>
    <button>Submit</button>
  </form>

Creating random coordinated svg circles with distance between them

I am trying to create randomly placed SVG circles, but I don’t want them to be too close to each other. I am using firestore for the backend and d3.js to create circles. Each circle is placed due to its “xValue” and “yValue” in firebase, which are generated using Math.random. These values (coordinates) should be created in a special different way to avoid too close circles.

My first approach was to use Math.random again but check all existing xValues and yValues to find the distance between the circle that I am about to create, then if the distance is lower than 80, increase Math.random value 100. It doesn’t work

function createRandomCoordinates() {
  
  var coordinates = [];

  getDocs(collection(db, "circles")).then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      coordinates.push({ ...doc.data() });
    })
 }); 
  
   
  let randomXValue = Math.floor(Math.random()*1200);
  let randomYValue = Math.floor(Math.random()*1200);

  var distances = [];
  
  for (let i = 0; i < coordinates.length; i++) {
    var a = coordinates[i].xValue - randomXValue;
    var b = coordinates[i].yValue - randomYValue;
    var distance = Math.sqrt(a * a + b * b);
    distances.push(distance);
    
    if(distances.some((e) => e < 80)){
    return {
       randXVal: randomXValue + 100,
       randYVal: randomYValue + 100
}
   }else {
    return {
      randXVal: randomXValue,
      randYVal: randomYValue
    }
  }
}
} 
console.log(createRandomCoordinates().randXVal,createRandomCoordinates().randYVal )

Filtering Images of Array in Javascript

I am trying to filter the photos as well as some other variables within my array on my website. I have the function below, but my photos are still not displaying. Any advice on what to do? I am fairly new to Javascript!

For some more background information, I am trying to display certain images of archived magazine covers. These covers will displayed through a filter chosen by the user. (i.e. specific year, brand, cover from the magazine). This is a project for my university class. You can copy the API link to inspect what my array looks like and the properties within it!

Any help would be so so gratefully recieved!

HTML:

<div class="data_display">

  <ul id="data_brand">

  </ul>

  <ul id="data_datePublished">

  </ul>

  <ul id="data_printCovers">

  </ul>

  <ul id="data_imgs">

  </ul>

  <!-- <img id="data_img" src="" alt=""> -->

</div>

CSS:

.data_display {
    display: grid;
    grid-column: 1 / -1;
    grid-row-start: 12;
    /* align-content: space-between; */
    width: 70vw;
  }
  
  ul {
    list-style-type: none;
   }
  
   li {
     margin-top: 2vh;
     margin-bottom: 2vh;
   }
  
  img {
     margin-left: 2vh;
     height: auto;
  
   }

Javascript:

console.log("hello!");
const ul1 = document.getElementById('data_brand');
const ul2 = document.getElementById('data_datePublished');
const ul3 = document.getElementById('data_printCovers');
const ul4 = document.getElementById('data_imgs');

async function getPeople() { 
  let response = await fetch('https://api.airtable.com/v0/appi4i01ehJf6jzVP/Table%201?api_key=keyOInlFujAUpPC0f'); 
  let data = response.json(); 
  return data; 
}

getPeople().then(data => {
  console.log(data.records);
  makeList(data.records)
});

function makeList(records) {
  for(let i = 0; i < records.length; i++) {

    let brand = records[1].fields.Brand;
    let dataDatePublished = records[1].fields.DatePublished;
    let dataPrintCovers = records[1].fields.PrintCovers;
    let dataLinks = records[1].fields.Attachments[0].thumbnails.full.url;

    let listItem1 = document.createElement('li');
    let listItem2 = document.createElement('li');
    let listItem3 = document.createElement('li');
    let listItem4 = document.createElement('li');

    let imgZ = document.createElement('img');

    listItem1.appendChild(document.createTextNode(name));
    listItem2.appendChild(document.createTextNode(dataBrand));
    listItem3.appendChild(document.createTextNode(dataDatePublished));
    listItem4.appendChild(imgZ);

    imgZ.src = dataLinks;

    imgZ.style.width = 20 + "px";
    

  //   listItem4.src = dataLinks;

    // ul4.src = "https://" + dataLinks;

    ul1.appendChild(listItem1);
    ul2.appendChild(listItem2);
    ul3.appendChild(listItem3);
    ul4.appendChild(listItem4);
  }
}

how do i get the role data from a guild using an API call

i have this code in JS however it always returs a 403 error. I have tried to run the same request with python and in postman and it gave me the data i wanted so the API is definitly not the problem.

const url="https://discord.com/api/v9/guilds/792895591255769098/members/search"

function callAPI() {
  var xhttp = new XMLHttpRequest();
  xhttp.open('GET', url);
  xhttp.setRequestHeader('Authorization', 'Bot <my bots token>');
  xhttp.send();
  console.log("sent request")
  console.log(xhttp)
}
callAPI.call() 

I also tried this code too but it returns the same result

async function getGuildRoles(){
  const response = await fetch('https://discord.com/api/guilds/792895591255769098/members',{
    method:'GET',
    headers: {
      Authorization: 'Bot <my bots token>'

    }
  });
  console.log(response.text());
  return response;
}
getGuildRoles.call()

Can’t set button’s onclick callback to a function in a string [duplicate]

I’m making an app that lets users upload stuff. I am trying to set the onclick callback of an upload button to a function by doing this inside one of my classes:

this.uploadMusicButton.onclick = "upload('music' + this.frameNum)"; 

// ^ this code is inside of a custom class
// the code below is outside of any js class

function upload(purpose)
{
  alert("made it here");
  uploadPurpose = purpose;                 
  document.getElementById("openFile").click();
}

But when I try clicking the button, nothing happens. Can someone please help me?

GoogleMapReact not loading

I’m trying to load google maps into my project but get the following errors:

google_map.js:1135 GoogleMap: center or defaultCenter property must be defined
Google Maps already loaded outside @googlemaps/js-api-loader.This may result in undesirable behavior as options and script parameters may not match.

import React, { useState, useEffect } from 'react';
import { CssBaseline, Grid } from '@material-ui/core';

import { getPlacesData, getWeatherData } from './api/index'
 
import Header from './components/Header/Header';
import List from './components/List/List';
import Map from './components/Map/Map';



const App = () => {
    const [type, setType] = useState('restaurants');
    const [rating, setRating] = useState('');
  
    const [coords, setCoords] = useState({});
    const [bounds, setBounds] = useState(null);
  
    const [weatherData, setWeatherData] = useState([]);
    const [filteredPlaces, setFilteredPlaces] = useState([]);
    const [places, setPlaces] = useState([]);
  
    const [autocomplete, setAutocomplete] = useState(null);
    const [childClicked, setChildClicked] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        navigator.geolocation.getCurrentPosition(({ coords: {latitude, longitude} }) => {
            setCoords({ lat: latitude, lng: longitude});

        });

    }, []);

    useEffect(() => {
        const filtered = places.filter((place) => Number(place.rating) > rating);

        setFilteredPlaces(filtered);
    }, [rating]);
     
    useEffect(() => {
        if(bounds) {
        setIsLoading(true);

        getWeatherData(coords.lat, coords.lng)
        .then((data) => setWeatherData(data));

        getPlacesData(type, bounds.sw, bounds.ne)
        .then((data) => {
            setPlaces(data.filter((place) => place.name && place.num_reviews > 0));
            setFilteredPlaces([]);
            setRating('');
            setIsLoading(false);
        });
    }

    },[bounds, type]);

    const onLoad = (autoC) => setAutocomplete(autoC);
    
    const onPlaceChanged = () => {
        const lat = autocomplete.getPlace().geometry.location.lat();
        const lng = autocomplete.getPlace().geometry.location.lng();

        setCoords({ lat, lng });
    };


    return (
     <>
     <CssBaseline />
     <Header onPlaceChanged={onPlaceChanged} onLoad={onLoad} />
     <Grid container spacing ={3} style={{ width: '100%' }}>
         <Grid item xs={12} md={4}>
             <List 
             places={filteredPlaces.length ? filteredPlaces : places}
             childClicked={childClicked}
             isLoading={isLoading}
             type={type}
             setType={setType}
             setRating={setRating}
             rating={rating}
             
             />

         </Grid>
         <Grid item xs={12} md={8} style={{display: 'flex', justfiyContent: 'center', alignItems: 'center' }}>
             <Map 
             setChildClicked={setChildClicked}
             setCoordinates={setCoords}
             setBounds={setBounds}
             coordinates={coords}
             places={filteredPlaces?.length ? filteredPlaces : places}
             weatherData={weatherData}
             />
             
         </Grid>

     </Grid>

     
     </>
    );
};

export default App;