Why is event.target.files[0].name showing error in my code?

I have this JS code (given below) which converts a JSON file to XML file. Everything works perfectly (I get the contents of the file), but now I want to fetch the filename of the uploaded file.

function onChange(event) {
        var reader = new FileReader();
        reader.onload = (event)=>{
          let data = JSON.parse(event.target.result);
          $("#jsonArea").val(event.target.result);
          var finalXML = '<root>' + x2js.json2xml_str($.parseJSON(event.target.result)) + '</root>';
          var finalName = event.target.files[0].name; //setting it here
          $("#xmlArea").val(finalXML);

          finalXML = finalXML.split('FORM3CA').join('FORM3CB');
          finalXML = finalXML.split('F3CA').join('F3CB');
          finalXML = finalXML.split('<CreationInfo>')[0] + '<CreationInfo><SWVersionNo>1.0</SWVersionNo><SWCreatedBy>SW20000</SWCreatedBy><JSONCreatedBy>SW20000</JSONCreatedBy><JSONCreationDate>2021-11-21</JSONCreationDate><IntermediaryCity>311</IntermediaryCity></CreationInfo>' + finalXML.split('</CreationInfo>')[1]
          finalXML = finalXML.split('I_We1').join('I_We');
          
          console.log(finalName); //here
        }
        reader.readAsText(event.target.files[0]);
    }
 
document.getElementById('file').addEventListener('change', onChange);

I was suggested to use event.target.files[0].name in order to get the filename of the uploaded file (by @HeryKurniawan in comments of this post). But, when I try to console.log()the finalName variable (as you can see in above code), it shows me this error –

enter image description here

What is wrong in my code? I have also tried using event.target.file.name & event.target.file[0].name, but that doesn’t work either. Kindly guide… Thanks! 🙂

How can I set default checked in Ag-Grid React.js?

I use react ag-grid and I have checkboxSelection on row. I want to default checked some rows, not checked some rows. How can I do that ?

columnDefinationVoucherList: [
                { headerName: "", cellRenderer: countCellIndex, width: 50, minWidth: 40, maxWidth: 50, editable: false, },
                { headerName: "Belge Kodu", field: "ApplicationVoucher.Voucher.VoucherCode", width: 50, minWidth: 50, maxWidth: 80, suppressSizeToFit: true, sortable: true },
                { headerName: "Belge Adı", field: "ApplicationVoucher.Voucher.VoucherName", width: 120, minWidth: 50, suppressSizeToFit: true },
                { headerName: "Seç", field: "", width: 90, minWidth: 10, suppressSizeToFit: true, maxWidth: 50, checkboxSelection: true, },
            ],

                                          <AgGridReact
                                            columnDefs={this.state.columnDefinationVoucherList}
                                            headerHeight={30}
                                            rowHeight={20}
                                            rowData={this.state.documentList}
                                            onColumnResized={true}
                                            enableCellChangeFlash={true}
                                            enableCellTextSelection={true}
                                            enableCellExpressions={true}
                                            enableSorting={true}
                                            enableFilter={true}
                                            enableGroupEdit={true}
                                            enableRangeHandle={true}
                                            defaultColDef={this.state.shortGridDefaultColDef}
                                            rowSelection={'multiple'}
                                            onSelectionChanged={this.GetSelectedVouchers}
                                        >
                                        </AgGridReact>

Also I use enterprise mode. So I am open every solutions.

When Focus done on input field, fields remove the data

I am trying to input data using this function. this function is fetching data and doing formfilling but when the form focus on the input field or I try to submit from all, data disappears from all the fields and all input fields become red.

 if (Data[key].formname) {   
          $("[formcontrolname='"+Data[key].formname+"']").focus(); 
          $("[formcontrolname='"+Data[key].formname+"']").val(Data[key].value);
                        
                        await wait (1000)                        
                    }

specific item from an object in local storage is not removing

let cartItems = localStorage.getItem("ProductsinCart");
cartItems = JSON.parse(cartItems);
Object.values(cartItems).map(item => {

    let productNumbers2 = localStorage.getItem('cartNumbers2');
    productNumbers2 = parseInt(productNumbers2);
    let cartcost = localStorage.getItem('totalCost');
    cartcost = parseFloat(cartcost);
    let inCart = item.inCart;
    if (item.id === id)
    {

        localStorage.removeItem(cartItems[item.tag]);
        console.log(cartItems);
   
    }

CodingAllInOne:
description: “notNow”
id: 4
imgSrc: “./imagesForCart/programmingBooks/CodingAllInOne.jfif”
inCart: 1
inStock: 39
name: “Coding All In One”
price: 29.99
tag: “CodingAllInOne”
[[Prototype]]: Object
DesignPatterns:
description: “notNow”
id: 6
imgSrc: “./imagesForCart/programmingBooks/DesignPatterns.jfif”
inCart: 1
inStock: 39
name: “Design Patterns”
price: 9.99
tag: “DesignPatterns”
[[Prototype]]: Object

how to map a json object into another new object

i have a payload response which goes like:

"requirementDetails": {
            "requirementId1": "A",
            "requirementId2": "B",
            "requirementId3": "C",
            "requirementId4": "D",
            "requirementId5": "E",
            "requirementId6": "",
            "requirementId7": "",
            "requirementId8": "",
            "requirementId9": "",
        }

and i want to create new array of the requirements which will not take the blank requirements using javascript map function and i want the resultant array to look like this:

data = [ "A","B","C","D","E"]

can anybody please help me out.

Chrome Extension “Uncaught Type Error: Cannot read properties of undefined (reading ‘query’) error”. querry property there was a mistake

I am trying to develop an extension for chrome. I did the necessary operations in the Process.js file. The codes worked but I got an undefined query error. This error did not prevent the code. There was a problem only in the share part in Google Slides. what do you think is the reason?
The system is working, but how can i prevent that warning ?
Please help me ?

Share google slides button not working. It works when I remove the plugin.

process.js

chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
    let url = tabs[0].url;
    url = url.replace('//', ';;').replace(/[/]/g, ';');
    let pageTitle = tabs[0].title;
    pageTitle = pageTitle.replaceAll("'", '*');
    pageTitle = pageTitle.replaceAll('"', '**');
    pageTitle = pageTitle.replace('//', '__').replace(/[/_]/g, '_');

});

google Slides and chrome extension image

chrome extension error log image

manifest.json

{
  "name": "DergiPark",
  "description": "This is a DergiPark Product. Powered by DergiPark.",
  "content_scripts": [
    {
      "js": [
        "/js/jquery.min.js",
        "/js/alert_util.js",
        "process.js"
      ],
      "css": [
        "/css/bootstrap.css"
      ],
      "matches": [
        "http://*/*",
        "https://*/*"
      ]
    }
  ],
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "icons": {
    "48": "icons/DP-02.png",
    "128": "icons/DP-02.png"
  },
  "action": {
    "default_icon": {
      "16": "icons/DP-02.png",
      "24": "icons/DP-02.png",
      "32": "icons/DP-02.png"
    },
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab", "tabs"
  ]
}

FormData not sending File object through Post request

I am making an axios.post() request in my Vue component to send some formData holding a media File to upload through a PHP script. I know the file object is being appended correctly as I log the data before the request here:

// this.postMedia is a Vue array holding any post media objects to be uploaded
this.postMedia.forEach((mediaObj, index) => {
    formData.append('media[' + index + ']', mediaObj.media);
    formData.append('mediaType[' + index + ']', mediaObj.mediaType);
});

// Logging formData
for (let p of formData.entries()) {
    console.log(p);
}

This logs the information of the file object and the corresponding media type as expected.

// This is the media data
File {
    lastModified: 1627299857401
    lastModifiedDate: Mon Jul 26 2021 07:44:17 GMT-0400 (Eastern Daylight Time) {}
    name: "test-image.jpg"
    size: 12295
    type: "image/jpeg"
    webkitRelativePath: ""
}

// This is the mediaType data
1

I am then passing this data through an axios request and logging the response data as follows:

// Vue.js file
axios.post('/api/createPostV2', formData, config)
.then(success => {
    console.log(success.data);
})
.catch(function(err) {
    console.log(err.response);
});


// PHP file being requested (/api/createPostV2)
public static function createPostV2(Request $request)
{
    // Just return request to check data
    return $request->all();
}

Here is what gets logged:

media: Array(1)
    0: {}
    length: 1
    [[Prototype]]: Array(0)
mediaType: ['1']

So it is passing the media array, but the actual file is not being passed as you can see by the empty object at index 0. As you can see the mediaType is passed correctly, keep in mind both ‘media’ and ‘mediaType’ are arrays to support uploading multiple files. Am I missing something here? Why is the file data being lost when I am passing it through formData?

jquery ajax header sending error Access to XMLHttpRequest at https://discord.com/api/guilds/1234567890

<script>
    const URL = "https://discord.com/api/guilds/899175503565553714";
    $.ajax({
        url: URL,
        type: "GET",
        headers: { Authorization: 'Bot ' + token } })
</script>

Here is my code

index.html:1 Access to XMLHttpRequest at 'https://discord.com/api/guilds/899175503565553714' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I send headers and receive values ​​successfully with jquery ?

Get data from google firebase’s firestore, put into global object/array javascript, react

I am trying to read from firestore and push that data into a global variable. I am able to push however the array acts differently outside the function (I’ve attached a screenshot from the console showing the dif). For example I can call data[0] or data[1] inside the function just fine but outside it returns “undefined“. Can anyone help with this?
This is for a react project, so if there is a way to do it using react hooks or something like that, I can implement no problem.

let fbData = [];

const GetData = async () => {
    const q = query(collection(db, "surveys"), where("surveyComplete", "==", true));
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
        fbData.push({
            [doc.data().surveyId]: {
                "name": doc.data().surveyName,
                "id": doc.data().surveyId
            }            
        });
    }, 
    function (error) {
        console.log("Error getting documents: ", error);
    });
}

And yes I know the way I structure my data is weird, I’m planning on fixing it once I figure this issue out.

thanks

image of console log outside function and inside function

Devskiller Angular test questions [closed]

Angular Interview Questions from Devskiller?

  1. In Angular 2+, the method bypassSecurityTrustResourceUrl marked value as ____
    (a) Low Risk
    (b) trusted
    (c) Compatible
    (d) acceptable
2. Which of the following are proper ways to create an interface/type Point3D which would include all properties of Point and additionally z: number?
(a) type Point3D = Point <{
             z: number
        }>
(b) type Point3D = Record<"x" | "y" | "z", number>
(c) type Point3D = Point & {z: number}
(d) interface Point3D extends Point {
        z:number
      }

3. Which of the following statements are correct about relations between observables and promises?
(a) The promises can return to their pending state, contrary to observables.
(b) Observables can be cancelled, there is no way to cancel promise
(c) A promise can easily be converted to an observable using from pipeable operator
(d) They are the same and such can be used interchangeably
(e) A promise changes state only once, an observable can receive several events

Decrement the value of a variable at every function call

I am creating a slot machine program using JavaScript, and want to decrement the value of coins at every function call. For example, coins = 20. It should decrement after every time the casino() function is called. Basically the function can be called as many times until coins = 0.
Is this a situation where the application of let vs var comes into play?
Here is a snippet of my code:

let reel1 = ["cherry", "lemon", "apple", "lemon", "banana", "banana", "lemon", "lemon"]
let reel2 = ["lemon", "apple", "lemon", "lemon", "cherry", "apple", "banana", "lemon"]
let reel3 = ["lemon", "apple", "lemon", "apple", "cherry", "lemon", "banana", "lemon"]
let slotReel = []
let coins = 20

function casino(r1, r2, r3) {
    coins = coins - 1
    let random1 = reel1[Math.floor(Math.random() * reel1.length)]
    let random2 = reel2[Math.floor(Math.random() * reel3.length)]
    let random3 = reel3[Math.floor(Math.random() * reel3.length)]
    slotReel.push(random1, random2, random3)
    //.....some logic
}

casino(reel1, reel2, reel3)

set Dynamic Default Value for select dropdown in react

I have a form, where I need to set the default value of the select dropdown in formik.

SelectDropDown.js

{props.options.map((option) => {
    return (
        <option key={option.id} value={option.id} title={option.title}>
            {option.name}
        </option>
    );
})}

Code Sandbox LINK

App.js

<SelectDropdown
    control="select"
    name="episodeType"
    data-testid="episodeType"
    id="episodeType"
    label="Episode Type"
    options={dropDownValues} // how to pass defualt a props
/>

How to pass the default values as props so the page is loaded the values is selected.

Thank you.