How to get an image from user on webpage and store this image in sql server database using asp.net?

I am making a website with profiles of users and there they can upload their avatar. And I need to get a photo from user and store this in users database. First got an image from user and send information to server:

    saveButton.onclick = (() => {
        const file = photoInput.files[0];
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = (async () => {
            const bytes = reader.result;
            const description = descriptionInput.value;
            const data = JSON.stringify({
                photo: bytes,
                description
            });

            await fetch("[username]/changedata", {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json"
                },

                body: data
            });

            window.location.reload();
        });
    });

Then tried to store this image in users database:

        app.MapPut("{username}/changedata", async (string username, HttpContext context) =>
        {
            var data = await context.Request.ReadFromJsonAsync<UserDataChange>();
            using var con = new SqlConnection(connection);
            await con.OpenAsync();
            var command = new SqlCommand();
            command.Connection = con;
            command.CommandText = "UPDATE [users] " +
                                  "SET description=@description, picture=@picture " +
                                  "WHERE username=@username";
            command.Parameters.AddWithValue("username", username);
            command.Parameters.AddWithValue("description", data.Description);
            command.Parameters.AddWithValue("picture", data.Photo);
            await command.ExecuteNonQueryAsync();
            await con.CloseAsync();
        });

UserDataChange class:

public class UserDataChange
{
    public byte[] Photo { get; set; }
    public string Description { get; set; }
}

But byte[] is invalid type for this situation.

How to add sliding effect for accordion menu in Javascript?

I am creating an accordion menu which slides up and down on clicking on it. I am able to get the functionality but couldn’t get the animation effect that slides smoothly from top to bottom and bottom to top while showing and hiding the menu content.

I’ve tried jQuery functions like slideUP() and slideDown() but I want to achieve it through javascript.
Here is my code..

<div class="accordian-wrapper">
    <div class="accordian-hover d-flex flex-row justify-content-center align-items-center container">
      <div id="accordian-question-div">
        <h5>How to use this product ?</h5>
      </div>
      <div>
        <i class="fa fa-solid fa-arrow-down"></i>
      </div>
    </div>
    <div class="accordian-content">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Deserunt iste est sunt? Excepturi quas, sunt recusandae laboriosam eligendi cum autem. Tempora nulla, at sequi minima praesentium, explicabo ullam eius odio corporis optio autem pariatur consequuntur, rem voluptate soluta exercitationem natus quod repudiandae. Reprehenderit vitae, iste facere aspernatur minima modi repellat!</p>
    </div>

  </div>
let k=0;
let rightArrow=$(".fa-arrow-down");
$(".accordian-hover").click(() => {

  if (k==0) {
    $(".accordian-content").show();
    k=1;
    rightArrow.toggleClass("fa-arrow-down fa-arrow-up");
  }
  else{
    $(".accordian-content").hide();
    k=0;
    rightArrow.toggleClass("fa-arrow-up fa-arrow-down");

  }



});

JS: build object based on given object parent’s property?

I am trying to create a JS object that hold all the urls.

I am trying to achieve this so I have a data() part:

export default defineComponent({
  name: 'MyPage',
  data() {
    backendUrls: {...}
  }
})

In a more simple way it would look like this:

backendUrls: {
  baseUrl: "http://localhost:8080",
  baseUrlWithPrefix: function() { return this.baseUrl + "/ver1"; }
  userAdd: function() { return this.baseUrlWithPrefix() + "/user/add"; }
}

I could use the this keyword since it pointed to the same object where the given property also exists.

But I would like to split a bit more and create objects in the object:

backendUrls: {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: ...
  },
  socketUrls: {
    messageUrls: {
      userAdd: ...
    }
  }
}

Here if I try generalUrls: { baseUrlWithPrefix: function() { return this.baseUrl + "/ver1"; }}, it won’t work because it does not find the baseUrl since the this keyword points on the generalUrls object and not the backendUrls object where the baseUrl exists.

I’d need something like this:

backendUrls: {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: function() { return {goBackToParentObject}.this.baseUrl + "/ver1"; }
  },
  socketUrls: {
    messageUrls: {
      userAdd: function() { return {goBackToParentObject}.this.generalUrls.baseUrlWithPrefix() + "/user/add"; }
    }
  }
}

Change the color of a button, if at least one option of a form is selected

I have a form with three options, by default the button is disabled in gray, I want that if the user just chooses an option, this button changes to blue.

<div id="openModal" class="modalDialog" data-modalorder="1">
<div>
<a href="#close" title="Close" class="close">X</a>
<h1 style="text-align: center; font-weight: 600">Gender</h1>
<form id="form_gender">
    <div class="hungry">
        <div class="selection">
            <input id="man" value="Man" name="gender" type="radio" /> 
            <label for="man">Man</label>
        </div>
        <div class="selection">
            <input id="woman" value="Woman" name="gender" type="radio" />
            <label for="woman">Woman</label>
        </div>
        <div class="selection">
            <input id="other" value="Other" name="gender" type="radio" />
            <label for="other">Other</label>
        </div>
    </div>
    <input id="btn_genero" class="getAssignment" type="button" onclick="btnGenero()" value="Siguiente">   
    </form>
</div>

I have the following function to add the new class with the new color, but it doesn’t work correctly. When I select an option the color does not change to blue

<script>
const btnGenero = () =>{
            
            try{
              const value = document.querySelector('input[name="gender"]:checked').value;
              var element = document.getElementById("btn_genero");
              if(value != ''){
                element.classList.remove("getAssignment");
                element.classList.add("getAssignment2");
                alert('success')
              }else{
                alert('required')
              }
            }catch(err){
              alert('required')
            }
            
          }
</script>

And this is my css code

<style>
.getAssignment {
cursor: pointer;
background: gray;
border: none;
border-radius: 25px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
padding: 5px 30px;
margin-top: 10px;
width: 259px;
height: 34px;
}
.getAssignment2 {
cursor: pointer;
background: red;
border: none;
border-radius: 25px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
padding: 5px 30px;
margin-top: 10px;
width: 259px;
height: 34px;
}

Removing fixed height makes the slider collapse intially when it loads

I have created a very simple responsive slider with vanilla JavaScript. It works great but has one issue which I am not able to figure it out. I am hoping someone from this community can help me.

Below is the slider demo I have in CodePen

CodePen Link

What I am trying to do is to remove the fixed height I have on .pc-mslider container, if I remove the fixed height the slider is collapsed when is it loaded due to the fact the height is not set. If I set the height and resize the window, it looks whacked either with huge space at the bottom or the content is hidden.

I am looking a way to fix this.

Thanks

I tried removing the height and calculating the height based on first slide using the code below

// Set the initial height based on the first slide
const slider = document.querySelector('.pc-mslider');
const firstSlideHeight = slides[0].offsetHeight;
slider.style.height = `${firstSlideHeight}px`;

But this is not working as it adds inline style height:0px .pc-mslider

JS function to append an external icon and how to position it

I’m trying to create a JS function that appends an icon(from font-awesome(I got it linked to the html file)) to the far-right side of the “li” row when the mouse hovers on it. But something seems off that it doesn’t work.

The list itself. It has hover properties.

The JS function in question.

const liElement = document.querySelectorAll("li")

   function appendIconToLi(liElement) {

    const iconDOM = document.createElement('icon');
    iconDOM.classlist = `<i class="fa-thin fa-house"></i>`

    liElement.addEventListener('mouseenter', () => {
      liElement.appendChild(iconDOM);
    });
    liElement.addEventListener('mouseleave', () => {
      liElement.removeChild(iconDOM);
    });
   }

HTML section looks like this

    <ul id="DadsList">
      <li>3 liters of Milk</li>
      <li>Bread</li>
    </ul>

CSS for ul.

  ul {
    margin: 0;
    padding: 0;
  }
  
  ul li {
    cursor: pointer;
    position: relative;
    padding: 12px 8px 12px 40px;
    background: #eee;
    font-size: 18px;
    transition: 0.2s;
    list-style-type: none;
  
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  
  ul li:nth-child(odd) {
    background: #f9f9f9;
  }
  
  ul li:hover {
    background: #ddd;
  }
  
  ul li.checked {
    background: #276678;
    color: #fff;
    text-decoration: line-through;
  }
  
  ul li.checked::before {
    content: "";
    position: absolute;
    border-color: #fff;
    border-style: solid;
    border-width: 0 2px 2px 0;
    top: 10px;
    left: 16px;
    transform: rotate(45deg);
    height: 15px;
    width: 7px;
  }

I’m slightly lost on how to style an element in JS. Example is to position it to the far right of the “li” element as mentioned above.

My webapp cannot leave a page in Chrome – it stays on the same page no matter how often you click the exit-button [duplicate]

I explained the same problem 2 days ago, but I probably made it too opaque, so here is a demo in clear code:
The program consists of 4 files: groups.php, editgroup.php, editgroup.js and save.php.

It was supposed to work like this:

  1. The user starts groups.php, select a group (there aren’t any actual editing in the demo) and press the edit-button.
  2. The editgroup.php starts, the user edits the group and press Save.
  3. The editgroup.php then starts save.php using an XMLHttpRequest-request. save.php does the update of the database and are supposed to return to groups.php.
    But it doesn’t.
    I’ve cut everything that is not basic out, so the problem must be in the remaining code.

Two files, a help-file and the mainmenu, are not used and so not included.
Oops. I just noticed I’ve forgotten Systemfejl-function. It is a function that logs the errormessages. I will put it in tomorrow.
I’ve been told to use use fetch instead of XMLHttpRequest, so I will look into it tomorrow.

I’m using PHP Version 7.4.29 and Javascript Version 1.15 and VS Code version 1.77 with some extensions, like PHP Debug v1.32.1.

The four files can be found at the bottom.

Hope someone can see anything. Because I sure can’t.

Poul

groups.php

<?php
  function Controls() {
    $S = '
    <form id="Targeter" action="/Help/Grupper.htm" target="_blank" method="post">
    </form>
    <form style="position:relative;left:10px;top:15px;" method="post">
      <button name="gId" formaction="/editgroup.php" method="post" id="Edit" type="submit" class="btn btn-primary" >Edit</button>
      <button name="gId" formaction="/mainmenu.php" method="post" id="Return" type="submit" class="btn btn-primary" >Return</button>
      <button form="Targeter" class="btn btn-primary" >Help</button>
    </form>';

    return $S; 
  } // Controls()

 function ShowControls($Controls) {
  // Displaying the Controls..
    $S = '
  <div id="Tools" style="width:100%;height:7vh;margin:1vh 1vh 1vh 0;border-radius:10px;
    background-color:darkgray;">';
    $S = $S.$Controls.PHP_EOL.'
  </div id="Tools">';
    echo($S); 
  } // ShowControls()

  try {
    ShowControls(Controls());
  }
  catch(Exception $e) {
    SystemFejl($e->getMessage());
  }  
  finally {
  }
?>

</body>
</html>

editgroup.php

<?php

$Controls = "
  <form style='position:relative;left:10px;top:15px;' method='post'>
    <button id='Save' onclick='SaveNow(this)' class='btn btn-primary' name='gId' 
      value='8'>Save
    </button>
    <button onclick='ExitNow(this)' id='Cancel' class='btn btn-primary'>Cancel</button>
  </form>";

function ShowControls($Controls) {
// Her den kode der viser Controls..
  $S = '
<div id="Tools" style="width:100%;height:7vh;margin:1vh 1vh 1vh 0;border-radius:10px;
  background-color:darkgray;">';
  $S = $S.$Controls.PHP_EOL.'
</div id="Tools">';
  echo($S); 
} // ShowControls()

ShowControls($Controls);
?>        
<script src="editgroup.js?newversion" type="text/javascript"></script>
</body>
</html>
function ExitNow(o) {
  if (window.confirm("Are you sure?")) 
    window.location.assign('groups.php');  
} // ExitNow()

function SaveNow(o) {
  const xhttp = new XMLHttpRequest();
  xhttp.open("POST", "save.php"); 
  xhttp.send();  
} // SaveNow()

save.php

<?php
  echo('<meta http-equiv="Refresh" content="0; url='groups.php'" />');
?>

How to switch between two players in tic tac toe game?

When i call the getActivePlayer method, it returns “player one”, and when i call switchPlayerTurn, it returns “player two”, however when i call getActivePlayer or even try to console log activePlayer after switching the turns, it still returns “player one”.

Ive tried using an if…else statement opposed to a ternary operator. Ive tried writing return statements in different parts of the if…else statement. Ive also searched these forums and while there are posts that are very similar to mine, ive already tried their solutions. Could it be an issue of scope? The switchPlayerTurn method is contained within a gaemController function, however, the activePlayer variable should be accessible from the method and should be able to change its value, correct?

I wrote a simple version at the bottom of my code changing the variable x and that works, but when i apply that above, it doesnt change anything.

function gameController(
    playerOneName = "Player One",
    playerTwoName = "Player Two"
) {
    const players = [
        {
            name : playerOneName,
            token : 1
        },
        {
            name : playerTwoName,
            token : 2
        }
    ];

    let activePlayer = players[0];


    const switchPlayerTurn = () => {  
        activePlayer = activePlayer === players[0] ? players[1] : players[0];
        console.log(activePlayer);
    };

    /*  if...else statement alternative 

    function switchPlayer() {
        if (activePlayer === players[0]) {
           activePlayer = players[1];
        } else if (activePlayer === players[1]) {
            activePlayer = players[0];
        }

    };

    */

    const getActivePlayer = () => activePlayer;

    const printNewRound = () => {
        gameBoard.printBoard();
        console.log(`${getActivePlayer().name}'s turn'`);
    };

    const playRound = (row, column) => {
        gameBoard.playMove(row, column, getActivePlayer().token);
        switchPlayer();
        printNewRound();
    }

    return {
        activePlayer,
        switchPlayerTurn,
        getActivePlayer,
        players,
        printNewRound,
        playRound
    };            
}

const gc = gameController();
console.log(gc.getActivePlayer());
gc.switchPlayerTurn();
console.log(gc.getActivePlayer());
// test
let x = 1;
function switchX() {
    if (x === 1) {
        x = 2;
    } else if (x === 2) {
        x = 1;
    } 
    console.log(x);
}
switchX();
switchX();

validating the length of phone field

I have several phone fields on my web page like this:

$("#HomePhoneInput").inputmask({
  "mask": "(999) 999-9999"
});
$("#WorkPhoneInput").inputmask({
  "mask": "(999) 999-9999"
});
$("#CellPhoneInput").inputmask({
  "mask": "(999) 999-9999"
});
<input type="text" asp-for="HomePhone" id="HomePhoneInput" placeholder="(___) ___-____" />
<input type="text" asp-for="CellPhone" id="CellPhoneInput" placeholder="(___) ___-____" />
<input type="text" asp-for="WorkPhone" id="WorkPhoneInput" placeholder="(___) ___-____" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>

I’m using this library to mask the fields.

I want to put the restriction on the length of the phone fields. If the user keys in less than 10 characters then as soon as the user tabs out of the phone field, an error message is displayed underneath the field saying “Phone field needs to be 10 character long.” This is what I tried:

<input type="text" asp-for="HomePhone" id="HomePhoneInput" placeholder="(___) ___-____" minlength="10" maxlength="10" data-msg="Phone field needs to be 10 character long."  />

Above does not work on chrome browser.

This is something, I want when the user tabs out of the phone field:

enter image description here

‘react-google-maps’ Markers keeps showing although the array is empty

I am using react-google-maps within my GoogleMapComponent.js. This component should render multiple markers based on a prop called similarLocations. At initial render, the array is empty, and no markers are shown on the map. Inside the parent component, when the user inputs any character, a fetch request is triggered, which responds with an array of similar locations that is passed to the GoogleMapComponent, and the markers are successfully displayed on the map.

However, when the user inputs another character that results in an empty array response, the previous markers continue to be displayed on the map, even though I have confirmed that the prop is being passed with an empty array. How can I remove the markers when the array is empty?
Here’s the parent component CreateLocation.js :

            import React, { useEffect, useState } from 'react'
            import Input from '../../../components/input'
            import { checkLocationMatches} from '../api'
            import GoogleMapComponent from './GoogleMapComponent'


            const CreateLocation = ({
                isEdit,
            }) => {
                const [locationData, setLocationData] = useState({
                    id: null,
                    client: null,
                    locationName: '',
                    googleLocationDetails: '',
                    nameAr: '',
                    nameEn: '',
                    street: '',
                    description: '',
                    category: null,
                    clientCode: '',
                    tags: [],
                    lat: 0,
                    lang: 0,
                    gov: '',
                    city: '',
                    area: ''
                })
                const [similarLocations, setSimilarLocations] = useState([])

                const matchArabicName = async () => {
                    try {
                        const data = {
                            lat: locationData.lat,
                            lang: locationData.lang,
                            clientId: locationData.client.value,
                            matcher: 'name_ar',
                            name: locationData.nameAr
                        }
                        const response = await checkLocationMatches(data)
                        response.data ? setSimilarLocations(response.data) : setSimilarLocations([])
                    } catch (err) {
                        console.log(err.response, 'match err')
                    }
                }


                useEffect(() => {
                    if (locationData.lat !== 0 && locationData.nameAr.length > 0 && !isEdit) {
                        matchArabicName()
                    }
                    // eslint-disable-next-line react-hooks/exhaustive-deps
                }, [locationData.lat, locationData.nameAr])

                return (
                    <Container>
                        <Body>
                            <Form>
                                <Input
                                    disableWithBorder={false}
                                    label="Client Location Name (Arabic)"
                                    name="nameAr"
                                    placeholder="EX: Hyper one"
                                    type="text"
                                    value={locationData.nameAr}
                                    onChange={e => handleLocationDetailsChange(e)}
                                    required
                                    isEditable
                                />
                            </Form>

                            <MapContainer>
                                <GoogleMapComponent
                                    isMarkerShown
                                    containerElement={
                                        <div style={{ height: '100%', width: '100%' }} />
                                    }
                                    setMapLocationData={handleSetMapLocationData}
                                    lat={locationData.lat}
                                    lang={locationData.lang}
                                    isOpen={true}
                                    similarLocations={similarLocations}
                                />
                            </MapContainer>
                        </Body>

                    </Container>
                )
            }

            export default CreateLocation

GoogleMapComponent.js:

      /* eslint-disable eqeqeq */
  import React, { useEffect, useState } from 'react';
  import { compose, withProps } from 'recompose';
  import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from 'react-google-maps';
  import MapMarker from '../../../assets/icons/map-marker.svg'
  import SimilarMarkerIcon from '../../../assets/icons/similar-marker.svg'

  const GoogleMapComponent = compose(
    withProps({
      googleMapURL:
        'https://maps.googleapis.com/maps/api/js?key=AIzaSyC8BSY4LG_gLmgrWTU6HqzxaKhC7hM_uH8&region=EG&language=ar&v=3.exp&libraries=geometry,drawing,places',
      loadingElement: <div style={{ height: `100%` }} />,
      mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
  )(({
    isMarkerShown,
    multipleMarkers,
    similarLocations,
    readOnly
  }) => {


    useEffect(() => {
      console.log(similarLocations, 'Similar locations')
      console.log(similarLocations.length, 'Similar locations length')
    }, [similarLocations])


    const onMarkerDragEnd = (coord) => {
      const { latLng } = coord;
      const lat = latLng.lat();
      const lng = latLng.lng();
      setCurrentPosition({ lat: lat, lang: lng });
      getReverseGeocodingData(lat, lng);
    };

    return (
      <GoogleMap
        defaultZoom={zoom || 12}
        zoom={zoom || 12}
        center={{ lat: currentPosition.lat, lng: currentPosition.lang }}
        onClick={(e) => onMarkerDragEnd(e)}>

        {isMarkerShown && !multipleMarkers && (
          <Marker
            position={{ lat: currentPosition.lat, lng: currentPosition.lang }}
            defaultDraggable={!readOnly}
            onDragEnd={(e) => onMarkerDragEnd(e)}
            options={{
              icon: {
                url: MapMarker,
              },
            }}
          />
        )}
        {
          similarLocations.length > 0 &&
          similarLocations.map(marker => (
            <Marker
              key={marker.location.id}
              position={{ lat: +marker.location.latitude, lng: +marker.location.longitude }}
              onClick={() => {
                handleActiveMarker(marker.location.id)
              }}
              options={{
                icon: {
                  url: SimilarMarkerIcon,
                },
              }}
              visible={similarLocations.includes(marker)}
            >
              {activeMarker === marker.location.id ? (
                <InfoWindow onCloseClick={() => setActiveMarker(null)}>
                  <div>{marker.location.name_ar}</div>
                </InfoWindow>
              ) : null}
            </Marker>
          ))
        }
      </GoogleMap>
    );
  });

  export default GoogleMapComponent;

Check if a JavaScript variable type has keys

I want to pass some data through a for...in loop. I need to check if the data type of data (which is unknown until runtime) makes sense to run through that loop first. All of Array, Object, and String are valid, but if data instanceof String then data[i] is still valid and returns the character in data at position i. I only want to get entire values (i.e. other scalars and objects), not parts of strings. I’m not sure if there are data types other than Array and Object that can contain multiple values and therefore make sense to loop over.

What’s a good test for such an object? This is what I’ve got so far, but I don’t know if it covers all cases.

if (typeof data === "object" && (data instanceof Array || data instanceof Object)) {
  for (let i in data) {
    // ...
  }
}

I’ve also looked at iterable, but Objects aren’t iterable, only Arrays.

Flatten Tree Leaves Typescript (reversed)

I need help dealing with generics.
The function should “pick” leaves and in case of duplicates raise the branch.

const inputSchema = {
    playerResponse: {
        videoDetails: {
            title: 'pick',
            shortDescription: 'pick',
            thumbnail: {
                thumbnails: {
                    '4': {
                        url: 'pick',
                        height: 'pick',
                        width: 'pick',
                    },
                },
            },
        },
    },
    streamingData: {
        formats: {
            0: {
                url: 'pick'
            }
        }
    }
}
type output = {
    videoDetails: {
        title: string,
        shortDescription: string,
    },
    thumbnails: [
        null,
        null,
        null,
        null,
        {
            url: string,
            height: number,
            width: number,
        },
    ],
    formats: [
        {
            url: string,
        },
    ],
}

function flattenSchema<T>(input:T){
    return ...
}

I’ve tried using dot-prop to flatten the structure, but I’m having trouble with the types. Specifically, I’m not sure how to maintain the correct type information after flattening the structure.

for (const path of flattenedPaths) {
    try {
        let value = getProperty(schema, path)
        if (!value) {
            value = undefined // erase unknown values
        }

        const apiValue = getProperty(sourceOfTruth, path)

        const lastPath = path.split('.')?.splice(-2)?.join('.') || ''

        // modify by reference
        setProperty(outputSchema, lastPath, apiValue)
    } catch (error) {}
}
return Ok({ body: outputSchema })

I would appreciate any advice or guidance on how to properly flatten this data structure with generics in TypeScript. Thank you in advance for your help!