mardi 26 octobre 2021

Changing pages disables navbar menu on Ruby on Rails

I have this problem. When the screen width goes below 1024px, the navbar changes to a responsive navbar that activates when a burger menu is clicked, this is made using javascript (it is being correctly compiled, the file is imported in application.js). This functionality works fine, but when I change pages (from home to store for example) it stops working, and I can't find the reason. Here's the code:

/* Javascript file */


document.addEventListener('DOMContentLoaded', () => {
  let responsiveMenu = document.querySelector('.responsive-navbar');
  let body = document.querySelector('body');
  let burgerBtn = document.querySelector('.burger-menu');
  let responsiveLinks = document.querySelectorAll('.responsive-menu-links')
  burgerBtn.addEventListener('click', () => {
    burgerBtn.classList.toggle('cross')
    responsiveMenu.classList.toggle('menu-open');
    body.classList.toggle('disable-scroll');
    responsiveLinks.forEach(link => {
      link.classList.toggle('trigger-anim')
    })
  })
})

/* _navbar.html.erb partial */

<div class="navbar-header">
  <div class="navbar-menu">
    <%=link_to 'Inicio', root_path%>
    <a href="">ustedes</a>
    <a href="">contacto</a>
    <a href="">sobre mi</a>
    <%=link_to 'Tienda', store_path%>
  </div>
  <div class="burger-menu">
    <span></span>
    <span></span>
    <span></span>
  </div>
  <div class="responsive-navbar">
  <div class="menu-background"></div>
  <div class="menu-links">
     <%=link_to 'Inicio', root_path, class: 'responsive-menu-links'%>
      <a href="" class="responsive-menu-links">ustedes</a>
      <a href="" class="responsive-menu-links">contacto</a>
      <a href="" class="responsive-menu-links">sobre mi</a>
      <%=link_to 'Tienda', store_path, class: 'responsive-menu-links'%>
  </div>
</div>
  <div class="navbar-items">
    <div class="logo">
    </div>
  </div>
</div>

/* styles */

.trigger-anim {
  animation: scaleIn .2s forwards;
}
.menu-open {
  width: 100vw !important;
  a {
    opacity: 1 !important;
  }
}

.disable-scroll {
  overflow: hidden;

  .home-container {
    height: 100vh !important;
    overflow: hidden !important;
  }
}

.cross {
  span {
    &:nth-of-type(1) {
      transform: rotate(40deg) translateY(20px);
    }
    &:nth-of-type(2) {
      transform: translateX(500px);
      opacity: 0;
    }
    &:nth-of-type(3) {
      transform: rotate(-40deg) translateY(-20px);
    }
  }
}



What's the key code of the magnifying button on Android phones?

I'm trying to handle the key press event of the magnifying icon. It seems to be like "Enter" and "NumbpadEnter" key code isn't working for that highlighted icon in the screenshot.

enter image description here




FileReader. readAsArrayBuffer(fileObject) for getting binary form of image

I'm trying to upload an image from the front end and send it to the API in binary format(only binary is accepted by API). But when I try to send the binary form, the file is uploaded but is corrupted and the image size in the server is always 2B instead of the original size. Below is my code:

<input type="file" accept="image/*" @change="handleImage" />
<button @click="submit()">Submit</button>

function handleImage(e) {
  const selectedImage = e.target.files[0]
  createBase64Image(selectedImage)
},
function createBase64Image(fileObject) {
  const reader = new FileReader()
  reader.onload = (e) => {
    const binaryImage = e.target.result
  }
  reader.readAsArrayBuffer(fileObject)
  }

The binaryImage will hold the raw binary data from the file and upon submit, I'm sending this binaryImage to the API. Please let me know if anyone experienced a similar issue and got this fixed.

Thanks




Implementing a RESTful login for a website

I've been reading a lot of threads about how to properly implement a RESTful login but I am not fully convinced yet, so far this is what i've come up with:

  1. Fill username and password in my login form
  2. When the user hits the login button, build an authorization basic header with username + password
  3. Hit an endpoint (e.g /token, i guess this should be a GET?)
  4. Generate the JWT token and send it back to the client (if it's a GET, i guess it will go as a json body)
  5. Client then uses localStorage or whatever to save the token and then hit the authenticated endpoints by building the bearer header

Would this be considered fully restful? If so, which http method would you use for retrieving the token? If it isn't, what would be the best way of achieving this (using JWT)




How to connect my android application to my website cpanel backend

I want to link my android app to my websites cpanel to store and edit information. I wanna be able to use my own website as a backend instead of firebase. Any tips on where to start?




TypeError: Cannot read properties of undefined (reading 'app') (Flutter web app)

For more than 3 days I tried to connect my web app to firestore and try to run my web app but i can't. Please help me to solve my problem and grow my start-up faster. Showing error like this: TypeError: Cannot read properties of undefined (reading 'app') How can I fix this problem?

My Flutter (index.html) code blew.

  <!DOCTYPE html>
    <html>
    <head>
      <!--
        If you are serving your web app in a path other than the root, change the
        href value below to reflect the base path you are serving from.
    
        The path provided below has to start and end with a slash "/" in order for
        it to work correctly.
    
        For more details:
        * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
    
        This is a placeholder for base href that will be replaced by the value of
        the `--base-href` argument provided to `flutter build`.
      -->
      <base href="$FLUTTER_BASE_HREF">
    
      <meta charset="UTF-8">
      <meta content="IE=Edge" http-equiv="X-UA-Compatible">
      <meta name="description" content="A new Flutter project.">
    
      <!-- iOS meta tags & icons -->
      <meta name="apple-mobile-web-app-capable" content="yes">
      <meta name="apple-mobile-web-app-status-bar-style" content="black">
      <meta name="apple-mobile-web-app-title" content="jaitun_admin">
      <link rel="apple-touch-icon" href="icons/Icon-192.png">
    
      <title>jaitun_admin</title>
      <link rel="manifest" href="manifest.json">
    </head>
    <body>
      <!-- This script installs service_worker.js to provide PWA functionality to
           application. For more information, see:
           https://developers.google.com/web/fundamentals/primers/service-workers -->
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js"></script>
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js"></script>
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-firestore.js"></script>
      <script src="https://www.gstatic.com/firebasejs/9.0.1/firebase-auth.js"></script>
      
    
      <script>
    
    const firebaseConfig = {
      apiKey: "AIzaSyDmv2oj8958mbUg07FW316IxOAiOdYhPTg",
      authDomain: "jaituncustomaer.firebaseapp.com",
      databaseURL: "https://jaituncustomaer-default-rtdb.firebaseio.com",
      projectId: "jaituncustomaer",
      storageBucket: "jaituncustomaer.appspot.com",
      messagingSenderId: "771594380318",
      appId: "1:771594380318:web:aa0a3b61483d19dc2bfa0f",
      measurementId: "G-B064R6Q9GJ"
    };
    
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    </script>
      <script>
        var serviceWorkerVersion = null;
        var scriptLoaded = false;
        function loadMainDartJs() {
          if (scriptLoaded) {
            return;
          }
          scriptLoaded = true;
          var scriptTag = document.createElement('script');
          scriptTag.src = 'main.dart.js';
          scriptTag.type = 'application/javascript';
          document.body.append(scriptTag);
        }
    
        if ('serviceWorker' in navigator) {
          // Service workers are supported. Use them.
          window.addEventListener('load', function () {
            // Wait for registration to finish before dropping the <script> tag.
            // Otherwise, the browser will load the script multiple times,
            // potentially different versions.
            var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
            navigator.serviceWorker.register(serviceWorkerUrl)
              .then((reg) => {
                function waitForActivation(serviceWorker) {
                  serviceWorker.addEventListener('statechange', () => {
                    if (serviceWorker.state == 'activated') {
                      console.log('Installed new service worker.');
                      loadMainDartJs();
                    }
                  });
                }
                if (!reg.active && (reg.installing || reg.waiting)) {
                  // No active web worker and we have installed or are installing
                  // one for the first time. Simply wait for it to activate.
                  waitForActivation(reg.installing || reg.waiting);
                } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
                  // When the app updates the serviceWorkerVersion changes, so we
                  // need to ask the service worker to update.
                  console.log('New service worker available.');
                  reg.update();
                  waitForActivation(reg.installing);
                } else {
                  // Existing service worker is still good.
                  console.log('Loading app from service worker.');
                  loadMainDartJs();
                }
              });
    
            // If service worker doesn't succeed in a reasonable amount of time,
            // fallback to plaint <script> tag.
            setTimeout(() => {
              if (!scriptLoaded) {
                console.warn(
                  'Failed to load app from service worker. Falling back to plain <script> tag.',
                );
                loadMainDartJs();
              }
            }, 4000);
          });
        } else {
          // Service workers not supported. Just drop the <script> tag.
          loadMainDartJs();
        }
      </script>
    </body>
    </html>



php action code not working with javascript confirmAction()

I have this php file which suppose to have a button to do some checkout functionally action by calling a JavaScript built-in function to do it

<a href="index.php" class="btn btn-danger btn-xs" > onclick="confirmAction()" <i class="icon-edit">Check out</a>

I used confirmAction() like this

<script>
                        // The function below will start the confirmation dialog
                        function confirmAction() {
                            let confirmAction = confirm("Dose the maintenance finished yet?");
                            
                            if (confirmAction) {
                                
                                alert("Action Done")
                        
                            } 
                            else {
                                alert("Action canceled");
                            }
                        }
                    </script>

if the user pressed ok I want to do php code which should do post action

controller.php?action=checkout&code=<?php echo $result->CONFIRMATIONCODE; ?>

but I wasn't successful in making it work inside the TRUE case in the javascript function

basically I tried to run the php code without the tag but I failed

any suggestion ? Thanks