PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label frontend. Show all posts
Showing posts with label frontend. Show all posts

Saturday, November 19, 2022

[FIXED] How to add Bootstrap to React app and use classes inside

 November 19, 2022     bootstrap-4, frontend, reactjs     No comments   

Issue

Can someone please explain how to add bootstrap to react app and how to use them inside react components since we can not add CDN links and "class" attribute inside a react app. Would you kindly please explain how to use bootstrap components inside react app. This will really helpful for me since i'm a very beginner to react developer..


Solution

Read this https://react-bootstrap.github.io/getting-started/introduction

     1. install react-bootstrap

                npm install react-bootstrap bootstrap


     2. import css file in your index.js or app.js

                import 'bootstrap/dist/css/bootstrap.min.css';

             <link
              rel="stylesheet"
              href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
              crossorigin="anonymous"
             />

      3. import components like

                import { Button } from 'react-bootstrap';

You can use normal bootstrap classes like className="row"



Answered By - CraZyDroiD
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 19, 2022

[FIXED] How to assign ‘author’ role to User in strapi.io?

 October 19, 2022     admin, frontend, mongodb, node.js, strapi     No comments   

Issue

In the user table when I am trying to assign a role to a user, it is showing public and authenticated options only. How to select ‘author’/‘editor’ or any other to the user through the admin panel and also through API?


Solution

First of all, you need to understand that the Editor, Author & Super Admin are roles for admin panel users only. So basically, it will only control/limit what the user can do after logging in into the admin panel (http://localhost:1337/admin). Additionally, these roles can only be assigned to the admin panel users which can be created by visiting the following module:

http://localhost:1337/admin/settings/users.

Now coming to your question, as to why we can't assign Editor/Author to users in the users collection, it's because the roles assigned to these users are in a separate module:

http://localhost:1337/admin/settings/users-permissions/roles

The roles created in this module are basically assigned to API consumers. So you could create roles of your own choice in this module and then:

  1. Limit the set of APIs this role can access
  2. Define whether the route will be public or private to this role
  3. Set rate limiting

Once you create the roles of your choice in this module, then you can go to users collection module.

http://localhost:1337/admin/plugins/content-manager/collectionType/plugins::users-permissions.user?page=1&pageSize=10&_sort=username:ASC

You could then create users (API consumers/users) who will have their own set of credentials (email & password) which can then be used for acquiring the bearer token.

So, to sum up, just create the roles you want to assign to users in this module and then use the user with that role for acquiring bearer token, following which you can call the APIs with that token. Simple!

P.S: Bearer Token is used on the headers for accessing private routes enabled for that particular user role.



Answered By - Salvino D'sa
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 17, 2022

[FIXED] Why is this :class="{}" not working? vueJs

 October 17, 2022     css, frontend, javascript, vue.js, vuejs3     No comments   

Issue

I made a really simple file which have a reactive Array of objects. ⇒ all objects have a property called checked, which is a boolean and toggles based on a checkbox. I'm iterating with a v-for="" the array of employees and rendering them on a <ul/ li. I'm trying to make a :class just for the ones who got checked, but it's throwing me a syntax error, and I'm not sure where I'm wrong and which would be the best approach. Every comment, advice will be appreciated, here's the code:

<template>
    <div class="contaier">
        <h1>Employees view</h1>
        <ul class="list">
            <li
             class="li-item"
            v-for="employee in employees" :key="employee.id" 
            :class="{employee.checked: isChecked}"
            >
                <input class="checkbox" v-model="employee.checked" type="checkbox" @click="checkEmployee">
                {{ employee.name }}           
            </li>
        </ul>

    </div>
</template>

<script>

import { reactive, ref } from 'vue'
export default {
    setup() {
    const checked = ref(false)
    
    const employees = reactive([
    {id: 1, 
    name:'Terry Lawrence',
    username:'TerryLaw',
    email: 'TerryLaw@gmail.com',
    address: 'whateverStreet 258',
    checked: checked.value
    },
    {id: 2, 
    name:'MartyClFly',
    username:'MartyMac',
    email: 'MartyMac@gmail.com',
    address: 'George Junior 300',
    checked: checked.value
    },
    {id: 3, 
    name:'Nancy Pelosi',
    username:'Drunk ho',
    email: 'drunkHo@gmail.com',
    address: 'Velbedere 400',
    checked: checked.value
    },
    {id: 4, 
    name:'Jonh Doe',
    username:'Jonny',
    email: 'JonhDoe@gmail.com',
    address: 'NobodyKnows 129',
    checked: checked.value
    },
    {id: 5, 
    name:'Candace Owens',
    username:'the greate black hope',
    email: 'Candace@gmail.com',
    address: 'Washington Str 777',
    checked: checked.value
    },
    {id: 6, 
    name:'Charles Dickens',
    username:'Charlie',
    email: 'CharlieDick@gmail.com',
    address: 'chickenNutso 678',
    checked: checked.value
    }
])

const checkEmployee = (event) => {
  try {
      for (const employee of employees) {
      if (event.target.id !== employee.id) {
           checked.value = true
      }}    
  } catch (error) {
      console.error(error)
      
  }            
}

return {
  employees,
  checkEmployee,
}

    
}}
</script>

<style scoped>
.list {
  width: 60%;
  margin-inline: auto;
  padding: 1em;
  list-style: none;
}
.li-item {
  padding: .5em;
  border: 1px solid black;
}
.checkbox {
  float: left;
}

.isChecked {
  background-color: rgb(191, 236, 122);
}
</style>

the error is here exactly ⇒ <li / element: enter image description here


Solution

Replace

<li class="li-item"
    v-for="employee in employees" :key="employee.id"
    :class="{employee.checked: isChecked}">

with

<li class="li-item"
    v-for="employee in employees" :key="employee.id"
    :class="{isChecked: employee.checked}">


Answered By - Eddy Gangloff
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 16, 2022

[FIXED] why is this Vuex state syntax throwing error?

 October 16, 2022     frontend, javascript, vue.js, vuex     No comments   

Issue

I'm quite new with Vuejs & Vuex, I created a local project just to practice, so I have a file called: employeeList with an Array of objects. I'm trying to pass that same Array as state in Vuex, but is throwing me errors. I assume the syntax is wrong, please tell what would be the correct approach and if the problem is in fact the syntax. Thank you & here's the code :

export const employeesModule = {
    namespaced: true,
    state : {
        [
            {
            id: 1, 
            name:'Terry Lawrence',
            username:'TerryLaw',
            email: 'TerryLaw@gmail.com',
            address: 'whateverStreet 258',
            checked: checked.value
            },
            {
            id: 2, 
            name:'MartyClFly',
            username:'MartyMac',
            email: 'MartyMac@gmail.com',
            address: 'George Junior 300',
            checked: checked.value
            },
            {
            id: 3, 
            name:'Nancy Pelosi',
            username:'Drunk ho',
            email: 'drunkHo@gmail.com',
            address: 'Velbedere 400',
            checked: checked.value
            }
]
            
    }, 

The actual file is longer, but there's no purpose to add the mutations, actions, etc...


Solution

Your syntax is wrong on your object "state". If you want it to be an object that contains an array, you need to set it a value like so:

state: {
  newArray: [...]
}

You can't just have an object that contains an array and is not set with a key.



Answered By - Jet.B.Pope
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why is this Vuex state syntax throwing error?

 October 16, 2022     frontend, javascript, vue.js, vuex     No comments   

Issue

I'm quite new with Vuejs & Vuex, I created a local project just to practice, so I have a file called: employeeList with an Array of objects. I'm trying to pass that same Array as state in Vuex, but is throwing me errors. I assume the syntax is wrong, please tell what would be the correct approach and if the problem is in fact the syntax. Thank you & here's the code :

export const employeesModule = {
    namespaced: true,
    state : {
        [
            {
            id: 1, 
            name:'Terry Lawrence',
            username:'TerryLaw',
            email: 'TerryLaw@gmail.com',
            address: 'whateverStreet 258',
            checked: checked.value
            },
            {
            id: 2, 
            name:'MartyClFly',
            username:'MartyMac',
            email: 'MartyMac@gmail.com',
            address: 'George Junior 300',
            checked: checked.value
            },
            {
            id: 3, 
            name:'Nancy Pelosi',
            username:'Drunk ho',
            email: 'drunkHo@gmail.com',
            address: 'Velbedere 400',
            checked: checked.value
            }
]
            
    }, 

The actual file is longer, but there's no purpose to add the mutations, actions, etc...


Solution

Your syntax is wrong on your object "state". If you want it to be an object that contains an array, you need to set it a value like so:

state: {
  newArray: [...]
}

You can't just have an object that contains an array and is not set with a key.



Answered By - Jet.B.Pope
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 15, 2022

[FIXED] Why is TypeScript not letting me do a single comparison condition?

 October 15, 2022     dom, frontend, javascript, typescript, vue.js     No comments   

Issue

The error is straightforward: Operator '>' cannot be applied to types 'number' and 'Ref<number>'. But the fact that I cannot make a comparison between 2 numbers is absurd, here's the code, I'm quite new with Typescript, so some help would be very appreciated:

  // Scroll logic:
    let lastScroll = ref<number>(0)

    const handleScroll = () => {
      const body = document.body
      window.addEventListener('scroll', () => {
        const currentScroll = window.scrollY

        if (currentScroll <= 0) {
          body.classList.remove('scroll-up')
        }

        if (
          currentScroll > lastScroll &&
          !body.classList.contains('scroll-down')
        ) {
          body.classList.remove('scroll-up')
          body.classList.add('scroll-down')
        }
        if (
          currentScroll < lastScroll &&
          body.classList.contains('scroll-down')
        ) {
          body.classList.remove('scroll-down')
          body.classList.add('scroll-up')
        }

        lastScroll = currentScroll
      })
    }

the error is in the if() comparison: enter image description here


Solution

A ref is not a number. Calling ref returns an object. See here:

Takes an inner value and returns a reactive and mutable ref object, which has a single property .value that points to the inner value.

const count = ref(0)
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

For clarity, rename lastScroll to lastScrollRef. Then change all references of lastScroll to lastScrollRef.value. For example

currentScroll > lastScroll &&

should change to

currentScrollRef.value > lastScroll &&

and so on.



Answered By - CertainPerformance
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 14, 2022

[FIXED] How to get data from axios call in computed method to manipulate them?

 October 14, 2022     axios, computed-properties, frontend, javascript, vue.js     No comments   

Issue

I do a call with axios to get data like this:

  export default {
      name: 'TaxesSection',
      data () {
        return {
          isFormShown: false,
          isLoading: false,
          isOpen: false,
          info: null,
          dist: null,
          tableauDistance: [],
          tableauGeneral: {},
          tabName: [],
          tabProrataDist: [],
          tabPriceHt: [],
          voyages: {},
          id: null,
          amount: null,
          errors: []
        }
      },
      // Fetches posts when the component is created.
      async created() {
        try {
          const response = await axios.get(`/cruise/${this.cruise.id}/vat_info`)
          this.info = response.data
        } catch (e) {
          this.errors.push(e)
        }
      },
      props: ['agreementId'],
      computed: {
        getTotalDistance () {
          return this.info
        },

When I display the data in HTML by calling {{getTotalDistance}} I got this:

{ "disembs_vat": [ { "profile": { "address_country": { "iso": "FR", "name": "France" }, "company_name": null, "company_reg_country": null, "date_of_birth": null, "full_name": "Paul Sernine", "id": 3, "initials": "PS", "is_new": false, "locked": false, "passport_country": { "iso": "FR", "name": "France" }, "profile_name": "Alt Profile #1", "version": 0, "write_access": true }, "voyages": [ { "country": "FRA", "distance": 15.916673872587964, "vat": 0.1 }, { "country": "international", "distance": 80.3050348237542, "vat": 0 }, { "country": "COR", "distance": 18.244668116382755, "vat": 0.021 } ] }, { "profile": { "address_country": null, "company_name": null, "company_reg_country": null, "date_of_birth": null, "full_name": "Robert Neverconnected", "id": 9, "initials": "RN", "is_new": false, "locked": false, "passport_country": null, "profile_name": null, "version": 0, "write_access": true }, "voyages": [ { "country": "FRA", "distance": 9.13255133078821, "vat": 0.1 } ] }, { "profile": { "address_country": null, "company_name": null, "company_reg_country": null, "date_of_birth": null, "full_name": "test ttete", "id": 11, "initials": "tt", "is_new": false, "locked": false, "passport_country": null, "profile_name": "Created by Arsène Lupin", "version": 0, "write_access": true }, "voyages": [ { "country": "international", "distance": 1001.8276448564677, "vat": 0 } ] } ], "qualifying_voyages": [ { "end_wp_id": 23, "qualifying": false, "start_wp_id": 1 }, { "end_wp_id": 26, "qualifying": true, "start_wp_id": 23 }, { "end_wp_id": 32, "qualifying": true, "start_wp_id": 26 } ], "total_distance": 1125.4265729999809, "vat_prorata": [ { "distance": 25.049225203376174, "vat": 0.1 }, { "distance": 1082.1326796802218, "vat": 0 }, { "distance": 18.244668116382755, "vat": 0.021 } ] }

But I want to manipulate the data on computed fonction "getTotalDistance" and when I tried to return this.info.disembs_vat or manipulate the data I got this error:

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of null (reading 'disembs_vat')
    at VueComponent.getTotalDistance (TaxesSection.vue?b2b5:43:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at Watcher.evaluate (vue.runtime.esm.js?2b0e:4597:1)
    at VueComponent.computedGetter [as getTotalDistance] (vue.runtime.esm.js?2b0e:4851:1)
    at Object.get (vue.runtime.esm.js?2b0e:2081:1)
    at Proxy.render (TaxesSection.vue?ec96:7:1)
    at Vue._render (vue.runtime.esm.js?2b0e:3569:1)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4081:1)
    at Watcher.get (vue.runtime.esm.js?2b0e:4495:1)
    at new Watcher (vue.runtime.esm.js?2b0e:4484:1)

And I can't figure it out... When I reload the html by modifying something and save it works but when I relaod the page with F5 it doesn't.

Thanks a lot!


Solution

Before your request returns (and populates this.info), this.info is null.

The error is telling you null does not have a disembs_vat property. Which is true.

Use optional chaining to return the value of this.item.disembs_vat when item is not falsy and undefined when item is falsy:

<script>
export default {
  // ...
  computed: {
    vat() {
      return this.item?.disembs_vat
    }
  }
  // ...
}
</script>
<template>
  <pre v-text="{ vat }" />
</template>

If you don't want undefined when the item is null, provide a default value like this:

   this.item?.disembs_vat || 'default value here'


Answered By - tao
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 30, 2022

[FIXED] how to make navbar only on 75% of header

 September 30, 2022     bootstrap-5, css, frontend, html, web-frontend     No comments   

Issue

Hello i am working on some project and i want to deploy navbar looks like this:

I have been working with many CSS scenarios and i cannot get to it. I was working with everything at bootstrap docs and found nothing.

Last idea which comes to my mind is to put this navbar as image and then images on it.

<nav class=""> </nav>

Do you guys have any ideas?

##edit

this is navbar for full size of page

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
    <div class="container">
        <img src="~/images/logo.png" width="65" height="55" />
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="navbar-collapse collapse d-sm-inline-flex justify-content-end">
            <ul class="navbar-nav flex-grow-1 justify-content-end">
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Kursy</a>
                </li>
                 <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Pomoc</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Mój profil</a>
                </li>
            </ul>
            <form class="d-flex" role="search">
                <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                
            </form>

        </div>
    </div>
</nav>

Solution

Here you go...

It's very easy. Set width: 75vw !important; to the collapse and apply the style you want.

See the snippet below.

#logo {
  width: 5%;
}

.collapse {
  width: 75vw !important;
  border: 1px solid red;
  border-radius: 40px;
  background-color: red;
}

.navbar-collapse {
  flex-grow: 0 !important;
}

.nav-item {
  padding: 0 16px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg">
  <div class="container-fluid">
    <img id="logo" src="https://images.unsplash.com/photo-1547721064-da6cfb341d50?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8Mnx8fGVufDB8fHx8&w=1000&q=80">
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse py-1 pe-3" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0 w-100 d-flex justify-content-between">
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
      </ul>
      <form class="d-flex" role="search">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>



Answered By - Cervus camelopardalis
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, September 10, 2022

[FIXED] How would I render data from a Django model with a React frontend?

 September 10, 2022     ajax, django, frontend, javascript, reactjs     No comments   

Issue

I'm currently working on a personal portfolio website using Django for the backend and database, and React for all the frontend stuff.

In this program, I have various fields that I would like to update every once in a while; I have Django tables for my education history, my work experiences, my skills, and a table to hold portfolio entries. I'd like to display this information on my React frontend, where I could display a page containing cards with all the portfolio projects I've created, and a page where my work experience, skills, and education history is all displayed.

Using plain Django, I would have simply selected the items from the table in views.py and passed it to the context, rendering the items as needed. With React, I don't know how I would handle such a request.

The way my code currently works, in the React components, I declare objects with the required fields such as

const myExperiences = [{
        name: "Company name",
        title: "job title",
        description: "job description",
        startDate: "start", 
        endDate: "end",
        location: "city, country",
    }]

and I display them by using the map function to put them in the desired format.

This is not ideal as it'd require me to change my source code any time I'd like to add more entries, where I would rather do it from Django admin console.

My other idea was to fetch the data from a Django API, but that seems inefficient, and having to fetch information from 3 different tables every time the page feels like it'd be slow for the user for no reason.

What is the right course of action here? What would you guys suggest?


Solution

As requested please find below a basic common approach with a React / Django setup:

  1. Make an (async) API request in React to your Django endpoint/view (in this case I'm using standard fetch API)
  2. Map the returned JSON to create DOM elements for rendering
import PayrollRuns from "./PayrollRuns";
import PayrollDetails from "./PayrollDetails";
import {useEffect, useState} from "react";
import moment from "moment";


const PayrollWrapper = () => {

    // Set State for Payroll data
    const [payrollRuns, setPayrollRuns] = useState([])

    // Fetch data --> 1.)
    useEffect(() => {

        // Fetch the Payroll Data related to the logged in User
        fetch(`http://127.0.0.1:8000/api/lastpayrollruns/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                 Authorization: `Token ${localStorage.getItem('token')}`
            },
        })
        .then(res => res.json())
        .then(data => {
          setPayrollRuns(data)
          });
    }, []);

    // --> 2.)
    const runItems = props.payrollRuns.map((run) =>
        <div key={run.id} className="flex justify-between p-2 text-lg text-base">
            <div>
                {moment(run.month.period).format('YYYY MMMM')}:
                Paid {run.payroll_run_items.length} talents
            </div>

            <div>
                {run.payroll_run_items.reduce((acc, value) => {
                  return parseFloat(value.amount.toFixed(2)) + acc; // Add 'value.amount' to 'acc'
                }, 0)}
            </div>
        </div>
    );

    return (
        <div className="runs-wrapper bg-white rounded-xl h-full w-48 shadow-sx-shadow p-4 flex flex-col">
            <h1 className="border-b-2 pb-4">Payroll Runs</h1>
            <div className="grow overflow-auto p-4">{runItems}</div>
        </div>
    )
}

export default PayrollWrapper

Django API endpoint/view for the given example:

class PayrollRun(APIView):
    """
    Retrieve payroll runs including line items for a company
    """
    def get(self, request):
        company = Company.objects.get(userprofile__user=request.user)
        payroll_runs = Payroll.objects.filter(company=company).order_by('-month')
        serializer = PayrollSerializer(payroll_runs, many=True)

        return Response(serializer.data)

Note:

One key concept of this setup is to provide the authentication header (token) for the API request as you will want to access the Django authenticated user (request.user) object in your views to make the database queries according to the user on client side.



Answered By - JSRB
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 2, 2022

[FIXED] How to protect backend from being accessed by other unauthorised apps

 September 02, 2022     authentication, backend, frontend, security     No comments   

Issue

How to protect my backend from being accessed by other unauthorised front-end apps? I googled and couldn't find a solution that gives complete solution. How companies like Instagram,Facebook block unauthorised requests ? I read SSL keys can be found by reverse-engineering the front-end. I am a noob and building a social network for a project.Please guide me.


Solution

I'll try to get you started in the right direction.

How to protect my backend from being accessed by other unauthorised front-end apps?

You can protect your server by issuing access tokens. The only way a user can get a valid token is by authenticating with a valid username and password.

Typically, tokens are set to expire after a period of time. If you are looking for a turn key solution, JSON web tokens are a good place to start. More info here: https://jwt.io/

I googled and couldn't find a solution that gives complete solution. How companies like Instagram,Facebook block unauthorised requests ?

Facebook uses access tokens. https://developers.facebook.com/docs/facebook-login/access-tokens/

I read SSL keys can be found by reverse-engineering the front-end.

Access tokens can't be reverse engineered because they are not 'hard-coded' into the front-end. The access tokens are retrieved from the back-end via authentication. Additionally, tokens typically expire after a period of time. If the token has expired, then the user must re authenticate to receive a new (valid) token.



Answered By - bsheps
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 22, 2022

[FIXED] How to extend galley.phtml in Magento2?

 August 22, 2022     catalog, customization, frontend, magento, magento2     No comments   

Issue

I want to add custom code in gallery.phtml in the PDP section on my custom module. I tried this=> called default the block in catalog_product_view.xml

<referenceBlock name="product.info.media.image">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Ajith_Mymodule::product/view/gallery.phtml</argument>
            </action>
        </referenceBlock>

loaded gallery.phtml with and without default code, nothing works well for me. Am I'm trying the correct method or did anybody give me the idea to do this?


Solution

This method is working properly

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Product media data template
 *
 * @var $block \Magento\Catalog\Block\Product\View\Gallery
 */
?>

<?php
$images = $block->getGalleryImages()->getItems();
$mainImage = current(array_filter($images, function ($img) use ($block) {
    return $block->isMainImage($img);
}));

if (!empty($images) && empty($mainImage)) {
    $mainImage = $block->getGalleryImages()->getFirstItem();
}

$helper = $block->getData('imageHelper');
$mainImageData = $mainImage ?
    $mainImage->getData('medium_image_url') :
    $helper->getDefaultPlaceholderUrl('image');

?>

<div class="gallery-placeholder _block-content-loading" data-gallery-role="gallery-placeholder">
    <img
        alt="main product photo"
        class="gallery-placeholder__image"
        src="<?= /* @noEscape */ $mainImageData ?>"
    />
</div>

<script type="text/x-magento-init">
    {
        "[data-gallery-role=gallery-placeholder]": {
            "mage/gallery/gallery": {
                "mixins":["magnifier/magnify"],
                "magnifierOpts": <?= /* @noEscape */ $block->getMagnifier() ?>,
                "data": <?= /* @noEscape */ $block->getGalleryImagesJson() ?>,
                "options": <?= /* @noEscape */ $block->getGalleryOptions()->getOptionsJson() ?>,
                "fullscreen": <?= /* @noEscape */ $block->getGalleryOptions()->getFSOptionsJson() ?>,
                 "breakpoints": <?= /* @noEscape */ $block->getBreakpoints() ?>
            }
        }
    }
</script>

call this in our custom template



Answered By - Ajith
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how can i edit this layout in magento 2.4.3

 August 22, 2022     frontend, javascript, magento, magento2, php     No comments   

Issue

{{layout handle="sales_email_order_items" order_id=$order_id area="frontend"}

I want to remove this line form email confirmation but I don't know where this html located. enter image description here


Solution

  • From handle="sales_email_order_items"

{{layout handle="sales_email_order_items" order_id=$order_id area="frontend"}

  • you'll see this layout "sales_email_order_items"
<block class="Magento\Sales\Block\Order\Email\Items" name="items" template="Magento_Sales::email/items.phtml" cacheable="false">
<block class="Magento\Sales\Block\Order\Totals" name="order_totals" template="Magento_Sales::order/totals.phtml">
</block>

Maybe, you'll find it in file

vendor/magento/module-sales/view/frontend/templates/email/items.phtml

or

vendor/magento/module-sales/view/frontend/templates/order/items.phtml

have a nice day !!



Answered By - alan.D
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 16, 2022

[FIXED] How to see html result built with reactjs

 August 16, 2022     browser, frontend, html, output, reactjs     No comments   

Issue

I'm building reactjs app. I want to grab full html output but when I try to view page source I see only template from index.html. How can I see HTML built by the app?

I believe it is possible because I can see HTML tree in developer tools in Elements tab, but I need it in plain text.


Solution

In Chrome one can use Developer tools to achieve this. Go to Elements and in context menu choose Edit as HTML.

enter image description here



Answered By - Yola
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 3, 2022

[FIXED] How to disable a button until all the fields are filled in a textfield

 August 03, 2022     frontend, html, html-table, react-hooks, reactjs     No comments   

Issue

I have a table in a modal whose code looks like this.

  <div>
        <Table>
              <tbody>
                {props.data.map((p) => <>
                  <tr>
                    <th> STC </th>
                    <th> Edit Text</th>
                  </tr>
                  <tr index={p}>
                  <td key={p.stc}><h3>{p.stc}</h3></td>
                  <td >
                    <TextField name={p.stc} type="text"  value={p.readValue}  onChange={handleChange} required={true} size="small" label="Required" variant="outlined" />
                  </td>
                  </tr>
                </>)}
                </tbody>
        </Table>
        <div >
          <Button disabled={inputState.disable} className="buttonStyle" onClick={(e) => submit()}>SUBMIT</Button>
          <Button onClick={handleClose}>CANCEL</Button>
          </div>
      </div>

And their corresponding functions and declarations as below -

  const [formInput, setFormInput] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
  );
  const [inputState, setInputState] = useState({disable: true});
  const handleOpen = (e) => {
    setOpen(true);
  };

  const handleClose = () => {
    window.location.reload(false);
    setOpen(false);
  };
  const [readValue, writeValue] = useState("");

  const submit = (e) => {
    console.log("Submitted!")
    handleClose();
  }

  const handleChange = (event) => {
    const newValue = event.target.value;
    writeValue(event.target.value)
    setInputState({disable: event.target.value===''}) 
  }

I want to -

  1. disable the buttons until and unless all the TextFields are filled.
  2. In handleClose(), is there any alternate solution for clearing the values of TextFields in stead of window.reload?

The format looks like the picture I'm attaching below- enter image description here


Solution

import React, { useState } from "react";
import "./style.css";

export default function App() {
  const textFields = ["field1", "field2"];
  const [inputValue, setInputValue] = useState({});
  const [buttonDisabled, setButtonDisabled] = useState(true);

  const validateButton = accInputs => {
    let disabled = false;
    textFields.forEach(field => {
      if (!accInputs[field]) {
        disabled = true;
      }
    });
    return disabled;
  };
  const handleChange = ({ currentTarget }) => {
    const { name, value } = currentTarget;
    const inputObj = {};
    inputObj[name] = value;
    const accInputs = { ...inputValue, ...inputObj };
    setInputValue(accInputs);
    setButtonDisabled(validateButton(accInputs));
  };

  const handleSubmit = () => {
    console.log("submit clicked");
  };

  const handleCancel = () => {
    const inputObj = {};
    textFields.forEach(field => {
      inputObj[field] = "";
    });
    setInputValue(inputObj);
  };
  return (
    <div>
      <table border="1px">
        <tr>
          <th> STC </th>
          <th> Edit Text</th>
        </tr>
        {textFields.map(field => {
          console.log("rendered");
          return (
            <tr>
              <td>
                <h3>p.stc</h3>
              </td>
              <td>
                <input
                  placeholder="required *"
                  value={inputValue[field]}
                  name={field}
                  onChange={handleChange}
                />
              </td>
            </tr>
          );
        })}
      </table>
      <input type="submit" disabled={buttonDisabled} onClick={handleSubmit} />
      <input type="submit" onClick={handleCancel} value="cancel" />
    </div>
  );
}

can be easily achieved with the above code. Please refer working example here

updated to add second point aswell.



Answered By - anees rehman
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 23, 2022

[FIXED] How to remove MDBootstrap a class defult selecte color

 July 23, 2022     frontend, html, mdbootstrap, twitter-bootstrap     No comments   

Issue

I'm using MDBootstrap for my project. I have used list of <a href> tags for a list as below

<a  class="list-group-item list-group-item-action text-right  hoverlist "
 id="list-1"
 data-toggle="list"
 href="#list-1"
 role="tab"
 aria-controls="cat01">cat01<i class="fa fa-home"></i> </a>

This is the final preview

SNAP

What I wants to do is to remove this blue color and then change color in to red. So I have tried below code

.hoverlist{
background-color:red;
}

But nothings get changes. Could anyone please tell me why is that?

Thanks


Solution

Well, there are two ways;

css properties are overridden from top to bottom:

The first is: I don't understand whether the css implemented resides in an external file or not. But if it is place the link to the css file under the link for mdbootstrap. Like this:

<html>
<head>
<link href="mdbootsstrap.css" rel="stylesheet">
<link href="your css file" rel="stylesheet">
</head>
</html>

or secondly, use the following code:

<a  class="list-group-item list-group-item-action text-right  hoverlist "
id="list-1"
data-toggle="list"
href="#list-1"
role="tab"
aria-controls="cat01" style="background-color: red">cat01<i class="fa fa-home"></i> </a>

Here, i have added style attribute to the link which will override all other css implementations.

See this pen: https://codepen.io/MansoorAhmed/pen/yLBKppw



Answered By - user11484655
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change the underline color of the input component in MD Bootstrap

 July 23, 2022     css, frontend, mdbootstrap, reactjs, web-frontend     No comments   

Issue

So I'm using the Input Group Component from MDBootstrap.

I was wondering if there's a way around for changing the color of the blank of the input field component in MD Bootstrap. Like at the moment, it looks like this (without focus):

Input Field Componentme without focus

When I click on this input field, it looks like this (with focus, the color of the input field blank changes to green):

Input Field Component with focus

The code for the this component is as follows:

<div class="input-group input-group-lg">
  <div class="input-group-prepend">
    <span class="input-group-text" id="inputGroup-sizing-lg">Name</span>
  </div>
  <input type="text" class="form-control" aria-label="Large" aria-describedby="inputGroup-sizing-sm">
</div>

I was wondering if there's a way around for changing the color of the input field blank to black instead of green when we click on it. Thanks!


Solution

Set backgroundImage style with <input /> would work

Try it in-text:

const style = {
  backgroundImage: `linear-gradient(0deg, black 2px, rgba(0, 150, 136, 0) 0),
    linear-gradient(0deg, rgba(0, 0, 0, 0.26) 1px, transparent 0)`
};
const App = () => {
  return (
    <div className="App">
      <div class="input-group input-group-lg">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroup-sizing-lg">
            Large
          </span>
        </div>
        <input
          type="text"
          class="form-control"
          aria-label="Large"
          style={style}
          aria-describedby="inputGroup-sizing-sm"
        />
      </div>
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<link
  rel="stylesheet"
  href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css"
  integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX"
  crossorigin="anonymous"
/>


The step to achieve it:

If you check the style in the browser,

You would find that color with animation, copy it and change that color, and that's it.

enter image description here



Answered By - keikai
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change the font and border color of the Button Component in MD Bootsrap React

 July 23, 2022     css, frontend, mdbootstrap, reactjs, web-frontend     No comments   

Issue

So I'm using a button component from MDBootrap. To be specific I'm using an Outline Button Component which looks like this:

enter image description here

The code that's given on the website for this particular component is as follows:

<button type="button" class="btn btn-outline-warning">Warning</button>

I was wondering if there's a way around to change the font color as well as the border color of this button component since at the moment it's not matching well with the theme of my website. Thanks!


Solution

If you want to reuse styles, create a new css class:

.btn.my-cusomized-button {
    border-color: pink;
    color: pink;
    background-color: transparent;
    border: 1px solid pink;
}
<button
  type="button"
  class="btn my-cusomized-button"
>
  Primary
</button>

n.b. css class my-cusomized-button and pink as color are just an example. Use your colors and class which better suits your need



Answered By - Danko
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 15, 2022

[FIXED] How to change the "selected" text to "bold / unbold" which is present in input tag "using html and JavaScript" only

 July 15, 2022     css, frontend, html, javascript, web-deployment     No comments   

Issue

I am trying to select a text/character from an input tag and when i press a bold button, selected text should change to bold and when the button is pressed again the selected text should change to normal.

here is my code but its not working.

<body>
<input type="text" name=inp id="inp">

<button onclick="getSelectedText();"><b>B</b></button>


<script>
    document.getElementsByTagName('input').mouseup(function(){
    getSelectedText().style.fontWeight="bold";
});

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
</script>


Solution

i think: the function returns a string, it is not an element in the document and has no style attribute



Answered By - 6fa
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 14, 2022

[FIXED] How can i use/ call maps api in my search box using javascript code to show list of cities

 July 14, 2022     api, frontend, javascript, rest, web-deployment     No comments   

Issue

enter image description here

i m trying to use Rapiapi in my webapplication and trying to use the javascript code to get the name of cities and country by autocomplete but im getting error when i try to search. will anyone be able to help me please.

please find the detail code below

var settings = {
"async": true,
"crossDomain": true,
"url": "https://countries-cities.p.rapidapi.com/location/country/GB/geojson?format=json",
"method": "GET",
"headers": {
    "x-rapidapi-host": "countries-cities.p.rapidapi.com",
    "x-rapidapi-key": "65a1b9fb01mshdd797ad52c65502p1489acjsna4edfe314956"
}

}

$.ajax(settings).done(function(response) {
    console.log(response);
});

function search() {
    var input = document.getElementById('search-bar');
    var allcities = new cities(input);
}

im trying to get the details of cities and country name as the user type in. T

Please help Thanks


Solution

I would suggest using their SDKs.

They provide the following snippet:


var request = require('request');

var options = {
  method: '{{HTTP_METHOD}}',
  url: '{{API_URL}}',
  headers: {
    'x-rapidapi-key': '{{API_KEY}}'
  }
};

request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
});


Answered By - Createdd
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to scale a website so that it show same visible area for all viewports?

 July 14, 2022     css, frontend, html, javascript, web-deployment     No comments   

Issue

I made an website for an viewport 1366px*768px . Now I want that when I resize my browser then it should show same website in mobile or bigger screen without breaking design,I don't want responsive website .

Example :

  1. when I open website in 360px420px viewport then my website get scale down and show exact visible area as in 1366px768px without any scroll bar .
  2. when I open website in 2000px1000px viewport then my website get scale up and show exact visible area as in 1366px768px without any extra space .

I tried

<meta name="viewport" content="width=1366, initial-scale=1" />

 const siteWidth = 1366;
      const scale = screen.width / siteWidth;
      document
        .querySelector('meta[name="viewport"]')
        .setAttribute(
          'content',
          'width=' + siteWidth + ', initial-scale=' + scale + ''
        );
    }

By using above code I am able to scale website according to the width i.e 1366px on mobile device but on changing height it is showing extra space or scroll bar at the bottom. Also it is not working in desktop.

Any good solution so that I can scale my website correctly for all viewports?


Solution

The solution down below works, but you need to consider removing scrollbars or make fine adjustments to add scrollbars to scale.

<body>
  <div class="container">
    <!-- All other elements should be here -->
  </div>
</body>
body {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.container {
  width: 1366px;
  height: 768px;
}
const siteWidth = 1366;
const scale = window.innerWidth / siteWidth;

document.querySelector(".container").style.transform = `scale(${scale})`; 


Answered By - Bulent
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing