upload data using vanila javascript ajax and django1.11.17

using vanila javascript ajax and django1.11.17 , i wanna upload image with other data, and how to handle it in django.
using vanila javascript ajax and django1.11.17 , i wanna upload image with other data, and how to handle it in django.

     var name=document.querySelector('#name').value;        
     var lname=document.querySelector('#lname').value;
     var email=document.querySelector('#email').value;
     var password=document.querySelector('#password').value
     var CSRF=document.querySelectorAll('input')[5].value
     var file=document.querySelector('#file')
     var res=document.querySelector('.res')
     


     var formdata = new FormData();             
     formdata.append('image',file.files[0]);
     


     xhttp= new XMLHttpRequest();             
     xhttp.open('POST',"",true);
     xhttp.setRequestHeader("X-CSRFToken",pass);
     xhttp.setRequestHeader("content-type",'application/multipart/form-data');


     xhttp.onload=function(){

          if(this.status == 200){
               res.innerText=this.responseText
          }else{
               res.innerText='error'    
          }
     }
     
     var data = {fn:name,ln:lname,em:email,pw:password,img:formdata}
     
     xhttp.send(JSON.stringify(data))

Discord JS attachment

What im trying to do is basically let the bot upload the .db file on discord.

what i tried:

if(cmd == "backup"){
  message.channel.send(moment().format('YYYY/MM/D hh:mm:ss SSS'),{files:['./data/db.db']})
}

which would just send the formatted date without the file, and then i tried:

if(cmd == "backup"){
  const file = new MessageAttachment('./data/db.db')
  message.channel.send(file)
}

which would just give an error of an empty message.

Updating a state from another React component in ReactJS

I have an api call in App.js component and I am getting the username from here to show this in the navbar. You can see the navbar component has the name property passed as a parameter to it. This is how my App.js code looks like

function App() {

  const[name,setName] = useState(null);

  useEffect(()=> {

    (
        async () => {
          try{
            const res =  await fetch('https://localhost:44361/api/users/getuser', {
                headers: {"Content-Type": 'application/json;charset=UTF-8'},
                credentials: 'include',
            });
            const content = await res.json();
            console.log(content);
            setName(content[0].uFirstName); // has to be content[0]
          }
          catch(e){
            console.log(e);
          }
        }
    )();
  },[name])
return (
    
     <Router>
       <div className="App">

           <Navbar name = {name}/>

           <Routes>

            <Route exact path="/" element={ <Home />} />

            <Route path="/registration" element = {<Registration/>} />

            <Route path="/login" element = {<Login/>} />

           </Routes>
      </div>
     </Router>
  );
}

export default App;

Now I want to update the name property from Login.js component. Login.js looks something like this:

function Login() {
    
    // const[name,setName] = useState(null);
    const[UEmail,setEmail] = useState(null);
    const[UPassword,setPassword] = useState(null);
    const[navigate, setNavigate] = useState(false);

    const submitHandler = async (e) => 
    {
        e.preventDefault(); // Prevent from being refreshed. Because User will not re-put every field if some field is wrong
        try{
            const res = await fetch('https://localhost:44361/api/users/login', {
                method: 'POST',
                headers: {"Content-Type": 'application/json;charset=UTF-8'},
                credentials: 'include',
                body : JSON.stringify({
                    UEmail,
                    UPassword
                })
            });

            var content = await res.json();

            if(res.status === 200)
            {
                  setNavigate(true);
                 //DO something
            }

            else if(res.status === 400){
                //DO something
            }
            
        }catch(err){
            console.log(err);
        }
    }
    if(navigate) // REDIRECT TO LOGIN PAGE AFTER BEING SUCCESSFULLY REGISTERED
    {
        return <Navigate to="/"/>
    }
    return (
        <div className="fullContainer">
            <div className="base-container">
                <div className="reg">Login</div>
                <div className="content">
                    <div className="form">
                        <div className="form-group">
                        
                            <input name="Email" type="email" placeholder="Email" required
                            onChange={e => setEmail(e.target.value)}
                            />
                        </div>
                        <div className="form-group">
                        
                            <input name="Password" type="password" placeholder="Password" required
                            onChange={e => setPassword(e.target.value)}
                            />
                        </div>
                    </div>
                </div>
                <div className="footer">
                    <button onClick={submitHandler} type="button" className="btn">Login</button>
                </div>
                <div className="toReg">
                <p>Don't have an account? 
                    <Link to="/registration">
                        <a> Register</a>
                    </Link>
                </p>
                </div>
            </div>
            </div>
    )
}

export default Login

How can I update the name in App.js after user click the login button after putting all credentials. I want to do this because, after navigating the user to homepage when the status code is 200 the user name is not changing in navigation bar. I need to do another reload to see the correct username in navbar.

Thank you.

How to render two const components in a conditional case in React JS?

I have declared 2 constant components in my React functional component.
I am trying to render them based on a condition,

      <Flex.Box w="90px" ml={1}>
        { mycondition
          ? ({ staticButton })
          : ((
            { staticButton })({ conditionalButton }))}
      </Flex.Box>

I am trying to render based on if mycondition is true or false. But, I am getting the below error in the console.

TypeError: {(intermediate value)} is not a function

Am I doing anything wrong?

String.replace() with regex is not replacing matched string – no, it’s not a duplicate question [duplicate]

I’ve been struggling with this for a bit and coming up short. I could use some quick guidance:

    let str = `
    value i'm trying to match
    `

    let regex = str.replace(`/^`+str+`.*n?/gm`, 'something else')
    console.log(str == regex) // true, why?

It is not a duplicate of that question. The same is true for:

    let str = 'value i'm trying to match'

    let regex = str.replace(`/^`+str+`.*n?/gm`, 'something else')
    console.log(str == regex) // true, why?

find all the combinations if I have a string value that equals another

if I have a string of “YYY” how would I return an array of all the possible values of YYY given all the possible values “Y” equals.

let sequence =  ["YYY"];
let nucleotides = {
    
    "R": ["G","A","R"],
    "Y": ["T","C","Y"],
    "K": ["G","T","K"],
    "M": ["A","C","M"],
    "S": ["G","C","S"],
    "W": ["A","T","W"],
    "B": ["G","T","C","B"],
    "D": ["G","A","T","D"],
    "H": ["A","C","T","H"],
    "V": ["G","C","A"],
    "N": ["A","G","C","T"],
    "A": ["R","M","W","D","V","N","A"],
    "C": ["Y","M","S","B","H","V","N","C"],
    "T": ["Y","K","W","B","D","H","N","T"],
    "G": ["R","K","S","B","D","V","N","G"]
}

How read value from uri key json

i have this object

{
  'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812',
  'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1',
  'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': 'User'
}

How read value for key ‘http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier’?

Trying to upload a file with fetch is faild but is working on postman

i was trying to upload a file with Fetch, apparently this working but the document is not upload.

I try to do the same on postman and the document is correctly upload, i dont know if I assume could be something about the format how i send the document on the Fetch, i changed to base64 but is faild anyway.

var formData = new FormData();

  formData.append("documento",valoresSubmit[0].value[0]);

  const url = 'myurl';

  options.body = formData;

  fetch(url, {
    method: 'POST', 
    body: formData, 
    headers:{
      'Content-Type': 'multipart/form-data',
      'X-VTEX-API-AppKey': 'imKey',
      'X-VTEX-API-AppToken': 'imAppToken'
    }
  }).then(res => console.log("hey!"))
  .catch(error => console.error('Error:', error))
  .then(response => console.log('Success:', response));

Thank you for any help or comment!!

Metamask accounts do not disconnect when connected from injected code via chrome extension

I am injecting some javascript into a page from a chrome extension. In my injected code, I am getting a list of accounts from metamask with:

ethereum.request({ method: 'eth_requestAccounts' })

The first time I ran this, it prompted me to connect through Metamask as expected. Now I am not able to disconnect or change my account though. I have disconnected through metamask, but when I run this request again, the account is still listed even though it’s disconnected. How can I force it to clear this disconnected account? It is still there even after reloading the extension I’m working on.

Everything works as expected when I debug from the console, so I’m not sure what’s going on. It seems like something funny due to the extension/injection.

Cordova 10 unable to post ajax to http url

I’m trying to send json data to an http url without success (I tried to send same data to an other https with success).
I have this settings:
config.xml

<access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />

AndroidManifest.xml

 android:usesCleartextTraffic="true"

html header

$.ajax({
                                    type: "GET",
                                    url: url,
                                    dataType: "jsonp",
                                    jsonp: 'callback',
                                    crossDomain: true,
                                    async: true,
                                    data: {id:results.rows.item(i).id, bolla:results.rows.item(i).bolla, anno:results.rows.item(i).anno, magazzino:results.rows.item(i). magazzino, articolo:results.rows.item(i).articolo, quantita:results.rows.item(i).quantita, term:terminale},
                                    success: function(data) {
                                        console.log(data)
                                    },
                                    error:function(xhr,textStatus,err)
                                    {
                                        alert("readyState: " + xhr.readyState);
                                        alert("responseText: "+ xhr.responseText);
                                        alert("status: " + xhr.status);
                                        alert("text status: " + textStatus);
                                        alert("error: " + err);
                                    }
                            });

If I use json it returns devicereadystate=0 and error if I use jsonp it returns devicereadystate=4 and error 404 (the url is correct if I paste to a browser it works)

Error : Operation users.insertMany() buffering timed out after 10000ms when using mongoose in the following code

I am having a hard time finding an error in this following code i wanted to connect to a database and add some data to it but iam getting an error whose info is specified below

**This is the code of Server.jswhich is the server of the application **

import userdata from './userdata.js';
import data from "./data.js"
import mongoose  from 'mongoose';
import userrouter from './routers/userrouter.js';


const app=express();

mongoose.connect('mongodb://localhost/purpleshades',{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true
})

app.use(express.json());
app.use(express.urlencoded({ extended: true }))

app.use('/api/users',userrouter)
app.use((err,req,res,next)=>{
    res.status(500).send({message:err.message})
})
const port=process.env.PORT || 5000
app.listen(5000,()=>{
    console.log(`serve at http://localhost:${port}`);
})

This is the code of the userserver.js which is the router file of the user router which handles the user many request

import userdata from "../userdata.js";
import User from "../models/usermodel.js";
import expressAsyncHandler from "express-async-handler";

const userrouter=express.Router()

userrouter.get('/seed',expressAsyncHandler( async(req,res)=>{
    const createdusers=await User.insertMany(userdata.users)
    res.send({createdusers})
}))

export default userrouter 

The data file is asfollows which is called userdata.js

const userdata={
    users:[
        {
            name:'Prashanth',
            email:'[email protected]',
            password:bcrypt.hashSync('1234',8),
            isadmin:true
        },
        {
            name:'ramesh',
            email:'[email protected]',
            password:bcrypt.hashSync('5678',8),
            isadmin:true
        },
        {
            name:'jhon',
            email:'[email protected]',
            password:bcrypt.hashSync('91011',8),
            isadmin:true
        },
        {
            name:'cristine',
            email:'[email protected]',
            password:bcrypt.hashSync('1213',8),
            isadmin:true
        }

    ]
}
export default userdata

Now the error is as follows
"message": "Operation `users.insertMany()` buffering timed out after 10000ms"

How do I get rid of this error.

How to replace image of SVG with inline SVG but keep dropdown-toggle class

How can I replace my current img of an SVG to use an inline SVG but ensure that I can apply a class to it in order to keep the dropdown toggle functionality and custom css styles?

Currently Using:

<img src="/assets/images/icons/close.svg" class="dropdown-toggle" alt="close" />

Want to use:

<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.875 1.95648L14.0435 0.125L8 6.16852L1.95648 0.125L0.125 1.95648L6.16852 8L0.125 14.0435L1.95648 15.875L8 9.83148L14.0435 15.875L15.875 14.0435L9.83148 8L15.875 1.95648Z" fill="black"/>
</svg>

but also keep a class applied to it, for JS and CSS purposes.

NuxtJS (VueJS) v-model issues

I have a parent component calling the textInput component:

<template>
  <TextInput
  v-model.lazy="fields.title"
  container-text="Hero Title"
  mobile-container-text="Hero Title Mobile"
  :mobile-text="fields.mobileTitle"
  inline="true" />
</template>

<script>
import TextInput from "@/components/core/inputs/TextInput"
import { libComponentMixin } from "@/shared/mixins"

export default {
  name: "test",
  components: {
    TextInput
  },
  mixins: [libComponentMixin],
  data: function () {
    return {
      fields: {
        title: "Hero Headline",
        mobileTitle: "Hero Headline Mobile"
      }
    }
  }
}
</script>

And within the TextInput component I have the following:

<template>
  <span
    v-if="$store.state.editMode && !$store.state.previewMode"
    class="edit"
    :class="{
      selected: $store.state.editingId === id,
    }"
  >
    <span @click="onShowControls" v-html="parsedValue"></span>
    <portal v-if="$store.state.editingId === id" to="controls">
      <div class="white-area">
        <h2>{{ containerText ? `${containerText}` : "Textarea" }}</h2>
        <slot></slot>
        <VueEditor
          ref="quillEditor"
          v-model="editorValue"
          :editor-options="editorSettings"
        />
      </div>
      <div v-if="mobileText">
        <h2>{{ mobileContainerText ? `${mobileContainerText}` : "Textarea" }}</h2>
        <slot></slot>
        <VueEditor
          ref="quillEditor"
          v-model="mobileText"
          :editor-options="editorSettings"
        />
      </div>
    </portal>
  </span>
  <span v-else v-html="parsedValue"></span>
</template>

<script>
import { VueEditor } from "vue2-editor"
import { debounce } from "lodash"
import { getUID } from "@/shared/utils"

export default {
  name: "TextInput",
  components: {
    VueEditor,
  },
  props: [
    "value",
    "itemIndex",
    "inline",
    "linkStyle",
    "supStyle",
    "containerText",
    "miniMode",
    "staticText",
    "mobileText",
    "mobileContainerText"
  ],
  data() {
    return {
      id: getUID(),
      editorSettings: {
        modules: {
          toolbar: !this.miniMode ? customToolbarConfig : false,
        },
      },
    }
  },
  computed: {
    editorValue: {
      get() {
        return this.itemIndex !== undefined
          ? this.value[this.itemIndex].text
          : this.value
      },
      set: debounce(function (newValue) {
        if (this.itemIndex !== undefined) {
          this.$emit(
            "input",
            this.value.map((item, i) =>
              this.itemIndex === i ? { ...item, text: newValue } : item
            )
          )
        } else {
          this.$emit("input", newValue)
        }
      }, 400),
    },
    editorValueMobile: {
      get() {
        return this.itemIndex !== undefined
          ? this.value[this.itemIndex].text
          : this.value
      },
      set: debounce(function (newValue) {
        if (this.itemIndex !== undefined) {
          this.$emit(
            "input",
            this.value.map((item, i) =>
              this.itemIndex === i ? { ...item, text: newValue } : item
            )
          )
        } else {
          this.$emit("input", newValue)
        }
      }, 400),
    }
  },
  methods: {
    insertMarkup(markup) {
      const quill = this.$refs.quillEditor.quill
      const pos = quill.getSelection(true).index
      this.$refs.quillEditor.quill.clipboard.dangerouslyPasteHTML(pos, markup)
    },
    onShowControls() {
      this.$store.commit("setEditingId", this.id)
    },
  },
}
</script>

<style lang="scss" scoped>
.edit {
  display: inline-block;
  border: 3px dashed transparent;
  &:hover {
    border: 3px dashed $button-secondary;
  }
  &.selected {
    border: 3px dashed $red;
  }
}
</style>

I am trying to update the mobileText data and have that show on the parent component. I think my problem is in the editorValueMobile method inside the computed object. Any help would be great thanks

jQuery $(window).on(“load”, function() only launches after refresh

I had some scripts running on 1.7.1 jQuery and now I am on WordPress’s 1.12.4. The code wouldn’t run. I had two errors running.
Uncaught TypeError: $ is not a function
https://grumans.ca/delicatessen/:1734

This line on the page is
$(window).load(function(){Grumans.deli.init();});

and this

Uncaught TypeError: $ is not a function
https://grumans.ca/js/script.js:1162

$(window).load(function(){

     //Grumans.deli.init();
});

I found what I thought was a solution. Someone had posted for a different article that you could do this.

jQuery(function($) {
    $(window).on("load", function() {
       Grumans.deli.init();
    });
});

This got rid of both errors when applied to the page and in the script code, and let my code run, but only if I refresh the page twice. When I first hit the page nothing happens. I am not a code writer. Does anyone know why and how to fix the code so that it runs as soon as the page loads?