Firebase wont return any information. This is for people to mark their search area on a Google Maps

Long story short we are putting together a website page for a kid that’s missing. Basically, someone can go on this page, enter their address and then it will mark an area to show they have checked their web cams. I have set up an API through Google cloud, set the permissions to what they need to be, set up my database in Firebase nd then coded that in however when the person picks their house it doesn’t retain that marker. So you refresh and its gone. In the console on Firebase I can see that no information is being logged so of course nothing is there to return to the site. Below is my code. Please help!

type here<!DOCTYPE html>
<html>
<head>
    <title>Community Search Map</title>
    <style>
        /* Style to ensure the map uses the full width and a fixed height */
        #map {
            height: 400px;
            width: 100%;
        }
        /* Style the input boxes and button for better alignment and visibility */
        .input-field, button {
            margin-top: 10px;
            width: 300px; /* Adjust width as necessary */
            padding: 10px;
            display: block; /* Stack the input fields vertically */
        }
    </style>
    <script src="https://www.gstatic.com/firebasejs/10.11.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.11.0/firebase-database.js"></script>
    <script>
      const firebaseConfig = {
        apiKey: "AIzaSyDY1hBVloKhVCIylwNlzwBqPBbhWzKnkHY",
        authDomain: "zayden-421218.firebaseapp.com",
        databaseURL: "https://zayden-421218-default-rtdb.firebaseio.com",
        projectId: "zayden-421218",
        storageBucket: "zayden-421218.appspot.com",
        messagingSenderId: "44335894652",
        appId: "1:44335894652:web:ecdc053194782b4655f9f9",
        measurementId: "G-W925JW9SDF"
      };

      firebase.initializeApp(firebaseConfig);
      const db = firebase.database();
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDwGs-tc3ujSE5ajOrmVr1pvlNORfIVAr8&libraries=places&callback=initMap" async defer></script>
    <script>
        let map;
        let geocoder;
        let autocomplete;

        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 12,
                center: {lat: 27.8503, lng: -82.135} // Centers the map on Fish Hawk, Florida
            });
            geocoder = new google.maps.Geocoder();

            // Setup the Autocomplete
            autocomplete = new google.maps.places.Autocomplete(
                document.getElementById('address'),
                {types: ['geocode']}
            );

            fetchMarkers();
        }

        function fetchMarkers() {
            const markersRef = firebase.database().ref('markers');
            markersRef.on('value', (snapshot) => {
                const markers = snapshot.val();
                if (markers) {
                    Object.keys(markers).forEach((key) => {
                        const markerData = markers[key];
                        const marker = new google.maps.Marker({
                            position: {lat: markerData.lat, lng: markerData.lng},
                            map: map,
                            title: markerData.note
                        });
                        const infoWindow = new google.maps.InfoWindow({
                            content: `<h3>Note:</h3><p>${markerData.note}</p>`
                        });
                        marker.addListener('click', () => {
                            infoWindow.open(map, marker);
                        });
                    });
                }
            });
        }

        function geocodeAddress() {
    const address = document.getElementById('address').value;
    const note = document.getElementById('note').value;

    geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            map.setCenter(results[0].geometry.location);
            const marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            // Create an info window to display the note
            const infoWindow = new google.maps.InfoWindow({
                content: `<h3>Note:</h3><p>${note}</p>`
            });

            // Add listener to marker to show info window when marker is clicked
            marker.addListener('click', function() {
                infoWindow.open(map, marker);
            });

            // Save the marker in Firebase
            const markersRef = firebase.database().ref('markers').push();
            markersRef.set({
                lat: results[0].geometry.location.lat(),
                lng: results[0].geometry.location.lng(),
                note: note
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

    </script>
</head>
<body>
    <div>
        <input type="text" id="address" class="input-field" placeholder="Enter Address Here">
        <input type="text" id="note" class="input-field" placeholder="Enter a note for this location">
        <button onclick="geocodeAddress()">Mark Searched Area</button>
    </div>
    <div id="map"></div> <!-- The map will appear here -->
</body>
</html>

I’ve tried the search bar

Hover over image and get zoom effect on another image using javascript?

Code breakdown:

This code has a main image (the big picture at top), and then smaller preview pictures under than main image. (Ignore the big picture at bottom as this is used to help visually troubleshoot the code).

  // Preview-img change on hover

  function setURL(newUrl) {
    var url = newUrl;
    return function () {
      document.getElementById('main-img').setAttribute('src', url);
    }
  }
  document.getElementById('preview-img-one').addEventListener('mouseover', setURL('https://rb.gy/1jca3j'));
  document.getElementById('preview-img-two').addEventListener('mouseover', setURL('https://rb.gy/st92i9'));
  document.getElementById('preview-img-three').addEventListener('mouseover', setURL('https://rb.gy/ntzcbd'));
  document.getElementById('preview-img-four').addEventListener('mouseover', setURL('https://shorturl.at/pJPX1'));
  document.getElementById('preview-img-five').addEventListener('mouseover', setURL('https://shorturl.at/lMUX6'));

  // Magnify glass

  function zoomIn(event) {
    var element = document.getElementById("mag-overlay");
    element.style.display = "inline-block";
    var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
    var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
    element.style.backgroundPosition = (-posX * .9) + "px " + (-posY * .9) + "px";
 
    var element = document.getElementById("mag-overlay-two");
    element.style.display = "inline-block";
    var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
    var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
    element.style.backgroundPosition = (-posX * .9) + "px " + (-posY * .9) + "px";
  }
  .product-preview-imgs-container-center {
    display: flex;
    justify-content: center;
    margin-top: 16px;
    width: 545.4px;
    height: 64px;
  }

  .preview-imgs-wrap {
    display: flex;
    justify-content: space-evenly;
    width: 352px;
    height: 64px;
  }

  #preview-img-one,
  #preview-img-two,
  #preview-img-three,
  #preview-img-four,
  #preview-img-five {
    width: 62.5667px;
    height: 62.5667px;
  }

  #preview-img-one:hover,
  #preview-img-two:hover,
  #preview-img-three:hover,
  #preview-img-four:hover,
  #preview-img-five:hover {
    border: 1px solid #191919;
    border-radius: 6px;
    width: 62.5667px;
    height: 62.5667px;
  }

  /* Magnifying Glass CSS */
  .main-img-container {
    width: 450.217px;
    height: 450.217px;
  }

  #main-img {
    width: 450.217px;
    height: 450.217px;
  }

  #main-img:hover {
    opacity: 0;
  }

  #mag-overlay {
    position: relative;
    left: -1px;
    bottom: 455px;
    width: 450.217px;
    height: 450.217px;
    display: inline-block;
    background-image: url("https://shorturl.at/qDN03");
    background-repeat: no-repeat;
    background-size: 175%;
    z-index: -1;
  }

  #mag-overlay-two {
    position: relative;
    left: -1px;
    bottom: 355px;
    width: 450.217px;
    height: 450.217px;
    display: inline-block;
    background-image: url("https://shorturl.at/qDN03");
    background-repeat: no-repeat;
    background-size: 175%;
    z-index: -1;
  }
  <div class="main-img-preview-img-wrap">
    <div class="main-img-container">
      <img id="main-img" onmousemove="zoomIn(event)" src="https://rb.gy/1jca3j">
      <div id="mag-overlay" onmousemove="zoomIn(event)"></div>
      <div id="mag-overlay-two" onmousemove="zoomIn(event)"></div>
    </div>
    <div class="product-preview-imgs-container-center">
      <div class="preview-imgs-wrap">
        <img id="preview-img-one" src="https://rb.gy/1jca3j" />
        <img id="preview-img-two" src="https://rb.gy/st92i9" />
        <img id="preview-img-three" src="https://rb.gy/ntzcbd" />
        <img id="preview-img-four" src="https://shorturl.at/pJPX1" />
        <img id="preview-img-five" src="https://shorturl.at/lMUX6" />
      </div>
    </div>
  </div>

What I want to accomplish:

What I want to happen is when the mouse hovers over each of the smaller preview pictures, the top main picture changes to the preview picture that has the mouse over it. I want to do this WITHOUT taking off the zoom effect, as the zoom effect is supposed to zoom in on each preview picture.

Sounds simple enough, but I’ve been struggling with this for days now.

What might work:

I’m assuming this part of the code needs a conditional statement like if..else to make it this work, which I’ve tried but have failed:

  function zoomIn(event) {
    var element = document.getElementById("mag-overlay");
    element.style.display = "inline-block";
    var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
    var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
    element.style.backgroundPosition = (-posX * .9) + "px " + (-posY * .9) + "px";
  }

  function zoomIn(event) {
    var element = document.getElementById("mag-overlay-two");
    element.style.display = "inline-block";
    var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
    var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
    element.style.backgroundPosition = (-posX * .9) + "px " + (-posY * .9) + "px";
  }

A visual of what I’m trying to implement:

I’m basically trying to copy the same effect aliexpress has on their website, which you can visually see here: https://shorturl.at/dkwKY

How can I achieve this with the code I have, or any other way using javascript? THANK YOU!

how to implement render in view controller after get request Django

I have the following template in which I added a get request

function openProject(projectId) {
        fetch(`/segmentation/test/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            },
            mode: 'same-origin',
        })
        .then(response => {
            if (response.ok) {
                console.log("Всё супер");
            } else {
                console.error('Ошибка при открытии проекта');
            }
        })
        .catch(error => {
            console.error('Произошла ошибка:', error);
        });
    }

and the next view
in it I collect all the information about images and tags that relate to this project

def test(request):
    projectId = request.GET.get('projectId')
    if projectId:
        project = Project.objects.get(pk=projectId)
        _tags = project.tags.all()
        _images = project.images.all()
        print(_images)
        polygons = []
        colorPol = []
        for i in range(len(_images)):
            polygons.append([])
            colorPol.append([])

        for i in range(len(_images)):
            for rect in Rect.objects.all().filter(inImage=i+1):
                tempArr = []
                colorPol[i].append(rect.tag.Name)
                for p in rect.points.all():
                    tempArr.append([p.x, p.y])
                polygons[i].append(tempArr)
    else:
        _tags = []
        _images = []
        polygons = []
        colorPol = []

    return render(request,
                  'segmentation/testDraw.html',
                  {'tags': _tags, 'images': _images, 'title': 'Test Draw', 'rectForImage': polygons,
                   'colorPolArr': colorPol})

My urls:

app_name = 'segmentation'

urlpatterns = [
    path('test/', test, name='testDraw'),
    path('projects/', project_show, name='project_show'),
]

please help me solve this problem

I tried changing the request to post, but as far as I understand it doesn’t matter

Making flutter app to detect incoming server.js request and ring/vibrate the device

I have wrote the code for server.js and main.dart.

Functionality which I am trying to achieve is very simple but somehow I cannot make it work.

server receives an incoming request, app fetches that request from server and ring/vibrate the device.

**main.dart code
**

void main() {
  runApp(MyApp());
}

String receiverDeviceId =
    ''; // Define and declare the receiverDeviceId variable

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      themeMode: ThemeMode.dark,
      home: MyHomePage(),
    );
  }
}

Future<String> fetchReceiverDeviceId(String serverUrl) async {
    final response =
        await http.get(Uri.parse('$serverUrl/getReceiverDeviceId'));

    if (response.statusCode == 200) {
      final result = jsonDecode(response.body);
      return result['receiverDeviceId'];
    } else {
      throw Exception(
          'Failed to fetch receiverDeviceId from the server. Status code: ${response.statusCode}');
    }
  }

void sendSlap(String serverUrl, String senderDeviceId,
      Function(String) onServerResponse) async {
    try {
      String receiverDeviceId = await fetchReceiverDeviceId(serverUrl);

      final response = await http.post(
        Uri.parse('$serverUrl/notifySlap'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(
            {'deviceId': senderDeviceId, 'receiverDeviceId': receiverDeviceId}),
      );

      if (response.statusCode == 200) {
        final result = jsonDecode(response.body);

        if (result['success']) {
          print(
              'Slap notification sent from $senderDeviceId to $receiverDeviceId');
          showSnackbar(
              'Slap notification sent from $senderDeviceId to $receiverDeviceId');

          // Notify the app that the server received the slap request
          onServerResponse('Server received slap notification');
        } else {
          print('Error sending slap notification: ${result['message']}');
          showSnackbar('Error sending slap notification: ${result['message']}');
        }
      } else {
        print('Slap notification request failed. Please try again.');
        showSnackbar('Slap notification request failed. Please try again.');
      }
    } catch (e) {
      print('Error sending slap notification: $e');
      showSnackbar('Error sending slap notification. Please try again.');
    }
  }

  void receiveSlap(String senderDeviceId, String receiverDeviceId) {
    // Logic to handle receiving a slap notification
    print(
        'Slap notification received from $senderDeviceId on $receiverDeviceId');
    showSnackbar(
        'Slap notification received from $senderDeviceId on $receiverDeviceId');

    // Vibrate the device
    vibrateDevice();

    // Play the notification sound
    playNotificationSound();
  }

  void playNotificationSound() async {
    AudioCache player = AudioCache();
    await player.load('noti/notification_sound.mp3');
  }

  void vibrateDevice() {
    Vibration.vibrate(duration: 500); // Vibrate the device for 500 milliseconds
  }

ElevatedButton(
                    onPressed: () async {
                      print('Slap button pressed'); // Add this debug statement
                      final response = await http
                          .get(Uri.parse('$serverUrl/getReceiverDeviceId'));
                      if (response.statusCode == 200) {
                        receiverDeviceId =
                            jsonDecode(response.body)['receiverDeviceId'];
                        print(
                            'Receiver Device ID: $receiverDeviceId'); // Add this debug statement
                        sendSlap(serverUrl, deviceId!, (String serverResponse) {
                          print(
                              serverResponse); // This will notify the app that the server has received the slap request
                        });
                      } else {
                        print(
                            'Failed to fetch receiverDeviceId from the server. Status code: ${response.statusCode}'); // Add this debug statement
                      }
                    },
                    child: Text('Slap!'),
                  ),

**server.js code
**

fastify.post('/notifySlap', (request, reply) => {
  const deviceId = request.body.deviceId;
  const receiverDeviceId = request.body.receiverDeviceId;

  const connectedDevicesToNotify = connectedDevices.filter(id => id !== deviceId);

  if (connectedDevicesToNotify.length > 0) {
    console.log(`Slap notification sent to devices: ${connectedDevicesToNotify.join(', ')}`);
    sendNotificationCommandToDevices(connectedDevicesToNotify); // Send command to devices to play sound or vibrate
  }

  if (deviceId === receiverDeviceId) {
    console.log(`Slap notification sent to device: ${deviceId}`);
    // Add logic here to handle the slap received by the same device
    // For example, you can play a sound or vibrate the device
  }

  reply.send({ success: true });
});

fastify.get('/getReceiverDeviceId', (request, reply) => {
  const receiverDeviceId = generateReceiverDeviceId();
  reply.send({ receiverDeviceId });
});

function sendNotificationCommandToDevices(devices) {
  devices.forEach(deviceId => {
    if (connectedDevices.includes(deviceId)) {
      console.log(`Sending slap notification to device: ${deviceId}`);
      if (isVibratingDevice(deviceId)) {
        console.log(`Vibrating device: ${deviceId}`);
        // Add code here to trigger device vibration
      } else {
        console.log(`Sending sound notification to device: ${deviceId}`);
        // Add code here to play a sound notification
      }
    } else {
      console.log(`Device ${deviceId} is not connected.`);
    }
  });
}

function isVibratingDevice(deviceId) {
  // Add logic here to determine if the device should vibrate upon receiving a slap notification
  // For example, you can check a database or a list of vibrating devices
  return true; // Return true if the device should vibrate, false otherwise
}

// Add a new endpoint to fetch server logs
fastify.get('/serverLogs', (request, reply) => {
  // Implement logic to fetch and return server logs here
  // You can return an array of log messages from the server
  const serverLogs = ['I/flutter (3471): Server received slap notification', 'Vibrating device: '];
  reply.send(serverLogs);
});

I have tried to fetch the server log and make the app ring/vibrate by matching the server logs, but nothing happens.

Custom Firefox addon – cannot inspect

I’m working on a custom firefox addon. It works fine, but when I go on Debugging -> This Firefox -> Load temporary addon -> Inspect, I see:

<body><h1>Your addon does not have any document opened yet.</h1></body>

and on Console Tab I see none of the console.log I put on my js code.

Do I have to enable anything in order to make my addon inspectable?

Issue with Embedding Chatbot iframe on iOS Devices

Problem Description:

I am encountering an issue with embedding the iframe of the Promium AI chatbot on iOS devices (iPhone and iPad). The chat widget works perfectly fine on various devices including Mac, Linux, Windows, and Android, but fails to send messages on iOS systems.

The iframe is generated by the script for embedding the Promium AI chatbot, accessible at https://promium-embed.s3.amazonaws.com/promium_embed/index.html.

Possible Causes:

I suspect that this issue might be related to CORS (Cross-Origin Resource Sharing) or SSL certificate problems. However, after checking our servers thoroughly, everything seems to be in order, and no errors are reported.

Technologies Used:

Backend: Flask
Frontend: HTML, JavaScript, CSS

Request for Community Assistance:

I would like to ask the Stack Overflow community if anyone has encountered similar issues with embedding iframes, on iOS devices, and if so, how they resolved it.

Any insights, suggestions, or experiences shared would be greatly appreciated.

We tried using BrowserStack, but we didn’t encounter any visible issues from the console logs. It appears to be a genuine problem with iOS itself.

Thank you in advance for your assistance.

function botResponse() {
  //ENABLE
  enableloader()


  fetch('/api/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'referer': window.location.href
    },
    body: `q=${encodeURIComponent(msgerInput.value)}&ip=${encodeURIComponent(ipAddress)}`
  })
  .then(response => {
    if (response.headers.get('content-type').includes('application/json')) {
      return response.json();
    } else {
      return response.text(); // Tratta il corpo della risposta come testo
    }
  })
  .then(AIreply => {
      console.log('%cReply:', 'font-weight: bold');
      console.log(AIreply.message);
      console.log('%cSource documents:', 'font-weight: bold');
      console.log(AIreply.source_documents);
      var botMessage = AIreply.message;
      if(botMessage=="<p>Agent stopped due to iteration limit or time limit.</p>"){
        botMessage="Please redefine the question."
      }
      appendMessage(BOT_NAME, BOT_IMG, "left", botMessage);
      //DISABLE
      disableloader()
      msgerInput.value = "";
    })
    .catch(error => {
      console.error(error);
      appendMessage(BOT_NAME, BOT_IMG, "left", "Sorry an error occurred, <a href='#' onClick='window.location.reload(true);'>Click here to refresh</a>");
      msgerInput.value = "";
    });
}

Radio buttons and labels in same line

I saw post in there “https://stackoverflow.com/questions/2306117/radio-buttons-and-label-to-display-in-same-line” and i tried to but still i can not fix that. I can not display radio buttons in same line in proper way. button and label too far from each other. How to solve that.

body{

  text-align: center;
  background-color: lightgrey;
}
#box-icon {
  font-size: 72px;
}
.header h2 {
  display: inline-block;
  color: #228B22;
font-size: 44px;
}
h1{
  color: #228B22;
  text-align: center;
 
}

.some-class {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px; /* Butonlar ile diğer input alanları arasında boşluk bırakmak için */
}

.some-class label {
  margin-left: 5px; /* Label ile input arasında boşluk bırakmak için */
}

.some-class input[type="radio"] {
  margin-right: 5px; /* Butonlar arası boşluk bırakmak için */
}

.form-signup input {
  background-color: #70e000;
  border-radius: 10px;
  margin: 10px;
  width: 300px;
height: 30px;
border: none;
}
#signup-button{
  margin: 10px;
  background-color: #228B22;
  width: 300px;
height: 30px;
border-radius: 10px; 
}
.form-signup{

  text-align: center;

}

.form-signup input{
  margin-top: 15px;
  border-radius: 10px;
  padding: 3px;
}

.form-signup button{
  margin-top: 15px;
  border-radius: 10px;
  padding: 3px;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>No Waste - Sign Up</title>
  <link rel="stylesheet" href="signupstyle2.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
  <div class="header">
    <i class="fa-solid fa-recycle fa-2xl" style="color: #228b22;" id="box-icon"></i>
        <h2>No Waste</h2>
      
  </div>
  <hr>
  <h1>Sign-Up</h1>
  <form class="form-signup">

      <div class="some-class">
        <input type="radio" class="radio" name="x" value="y" id="y" />
        <label for="y">Thing 1</label>
        <input type="radio" class="radio" name="x" value="z" id="z" />
        <label for="z">Thing 2</label>
      </div>


  <div>  <input placeholder="Email" required type="email"> </div>
   <div> <input placeholder="Name" required> </div>
<div>    <input placeholder="Surname" required ></div>
 <div>   <input placeholder="Password" required type="password"> </div>
 <div>   <input placeholder="Repeat Password" required> </div>
    <button id="signup-button">Sign-Up</button>
  </form>
  <script src="signup.js"></script>
</body>
</html>

I saw post in there “https://stackoverflow.com/questions/2306117/radio-buttons-and-label-to-display-in-same-line” and i tried to but still i can not fix that. I can not display radio buttons in same line in proper way. button and label too far from each other. How to solve that.

How to display dom elements through a function that works onsubmit?

I am making greeting cards with user input using Javascript and CSS. I need to be able to have the information that the user submits in the form populate as a card underneath. I have some CSS assigned though this isnt the issue currently. I have a lot of the javascript bones there but I cant figure out how to return those elements once submitted.

  let form = document.createElement('form');
form.setAttribute('id','card-form');



let nameInput = document.createElement('input');
nameInput.setAttribute('type','text');
nameInput.setAttribute('id','name-input');
nameInput.setAttribute('placeholder','Your Name');
nameInput.required = true;
form.appendChild(nameInput);





let messageTextArea = document.createElement('textarea');
messageTextArea.setAttribute('id','message-input');
messageTextArea.setAttribute('placeholder','Your Message');
messageTextArea.required = true;
form.appendChild(messageTextArea);


let imageInput = document.createElement('input');
imageInput.setAttribute('type','url');
imageInput.setAttribute('id','url-input');
imageInput.setAttribute('placeholder','Image or GIF URL');
imageInput.required = true;
form.appendChild(imageInput);



let submitButton = document.createElement('button');
submitButton.setAttribute('type','submit');
submitButton.innerText = 'Finish';
form.appendChild(submitButton);


document.body.appendChild(form);







let cardContainer = document.createElement('div');
cardContainer.setAttribute('id','card-container');
document.body.appendChild('cardContainer');
document.body.appendChild(form);
document.body.appendChild(div);

I tried simply returning the item on submit but this isnt returning anything

document.getElementById('card-form').addEventListener('submit', function (onSubmit) {
 document.getElementById('card-container');
 return div;
});

Using javascript template file, how can I check for a null or an undefined value?

I am using a Javascript HTML template engine. How do I check for null or undefined in my HTML?

If ctx.m.transferTicket is null or undefined, I want to treat that as being false.

SO I have this code

{% if (ctx.m.transferTicket===false || ctx.m.transferTicket=='') { %}
    <div>NOT TRANSFERRED</div>

{% } else { %}
    <div>TRANSFERRED</div>
{% } %}

But if ctx.m.transferTicket is null or undefined, it acts as if it’s true.

How can I fix this?

Thanks!

Content-Type was not one of “multipart/form-data” or “application/x-www-form-urlencoded”

I am attempting to build a static site with Astro, but I want to add a component that allows a user to sign up for a newsletter via an HTML form. Following Astro’s guides, I am using an API endpoint to accept the form data and process the logic. However, when submitting the form, I get an error, Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded" when calling await request.formData();. As far as I can see by looking at the headers in the request though, it is encoded as multipart/form-data:

Content-Type: multipart/form-data;boundary=---------------------------30448001245691757982165322994

And the payload:

-----------------------------30448001245691757982165322994
Content-Disposition: form-data; name="email"

[email protected]
-----------------------------30448001245691757982165322994--

The API endpoint code (from the Astro docs):

import type { APIRoute } from "astro";

export const POST: APIRoute = async ({ request }) => {
    const data = await request.formData(); // error is thrown here
    const email = data.get("email");
    
    // Validate the data - you'll probably want to do more than this
    if (!email) {
        return new Response(
            JSON.stringify({
                message: 'Missing required fields',
            }),
            { status: 400 }
        );
    }
    
    // Do something with the data, then return a success response
    return new Response(
        JSON.stringify({
            message: "Success!"
        }),
        { status: 200 }
    );
}

And the javascript to send the request:

const formData = new FormData(event.currentTarget as HTMLFormElement);

const response = await fetch("/api/newsletter", {
    method: "POST",
    body: formData,
});

const apidata = await response.json();

How to dynamically add click handler to Ember Octane component – dynamic “on” modifier

I have a situation where I need to make a component and it has some logic to either render as a button or as a DIV depending on if it has a link.

{{#let
  (if
    this.hasLink
    (component "external-library-button$special-button")
    (element "div")
  )
  as |MaybeAButton|
}}
    <MaybeAButton
      {{on "click" this.onClick}} // can this be dynamically added?
    >
      ...lots of nested code
    </MaybeAButton>
{{/let}}

I tried to do add it dynamically but I get an error that “on” is not in scope.

{{(if this.hasLink (modifier on "click" this.onClick))}}

What’s a good way to dynamically add a click handler?
I’d like to not add a listener if it won’t be interactive.

How to correctly validate a stepper with Yup

I have a question about how to validate a step form correctly with Yup.

I have the following case:

const schema = Yup.object().shape({
  step1: Yup.object().shape({
    origin: Yup.string().required('Required...');
  }),
  step2: Yup.object().shape({
    code: Yup.string().when('step1.origin', (value, schema) => {
      console.log({value}); //  [undefined]
      // if(value === 'XX') ....
    });
  })
})

In the code above I would like to do the validation directly, but I cannot access the value of step1.origin

How I managed to do it, but in a bad way:

let origenValue = null;

const validationStep1 = Yup.object().shape({
  origin: Yup.string().transform((value, originalValue) => {
    // This code is the one I actually used for ORIGIN by the SELECT2 library
    if (originalValue && originalValue.value) {
        origenValue = originalValue.value;
        return originalValue.value;
    }
    return value;
  }).required('Required...')
});

const schema = Yup.object().shape({
  step1: validationStep1,
  step2: Yup.object().shape({
    code: Yup.string().when('step1', (_) => {
      return origenValue === 'XX'
        ? Yup.string().required('Required...')
        : Yup.string().nullable();
    }),
  })
})