Undefined index because of AJAX or PHP

I’m trying to send data to php by ajax but this don’t work. Here is the code :

index.php (code in html)

                    <div class="container mb-2 mt-2">
                        <form action="" id="LoopPosition" class="myPosition" method="post">
                            <span>Longitude :</span><!--<span id="displayLong"></span>--> <input id="displayLong" name="displayLong" type="text" style="width: 400px;"> <br>
                            <span>Latitude: </span><!--<span id="displayLat"></span>--> <input id="displayLat" name="displayLat" type="text" style="width: 400px;"> <br>
                            <span>Accuracy : </span><!--<span id="displayAccu"></span>--><input id="displayAccu" name="displayAccu" type="text" style="width: 400px;"> <br>
                            <?php if (isset($_GET['DeliveryCourse'])) : ?>
                                <button type="submit" name="submitPositionForLivreur" class="btn btn-info" id="clicAuto">Clic automatique</button>
                            <?php endif; ?>
                            <!-- <button type="button" name="submitPositionLivreur" class="btn btn-info" id="getFixed">Partage Automatique</button> -->
                        </form>

ajaxPostToDatabase.js (inside of index.php)

            $("#LoopPosition").submit(function(e) {
                const lng_forAjax = $("#displayLong").val();
                const lat_forAjax = $("#displayLat").val();
                const accuracy_forAjax = $("#displayAccu").val();


                $.ajax({
                    method: 'POST',
                    url: 'updateLivePosition.php',
                    data: {
                        'lng_forAjax': lng_forAjax,
                        'lat_forAjax': lat_forAjax,
                        'accuracy_forAjax': accuracy_forAjax

                    },
                    success: function(msg) {
                        var msg = lng_forAjax + " " + lat_forAjax;
                        alert(msg);
                    },

                });
            })

ToTheDatabase.php

<?php
        require_once("functions/db_connexion.php");
        require_once("functions/displayLivreur.php");

        if(isset($_POST['submitPositionForLivreur'])){
            echo $_POST['lng_forAjax']." ".$_POST['lat_forAjax']." ". $_POST['accuracy_forAjax'];
        } 
    }

With all of that, i still get an Undefined index : lng_forAjax; Undefined index : lat_forAjax; Undefined index : accuracy_forAjax

highcharts yAxis datetime start from 0

Why highcharts yAxis type datetime start from 1 jan always?

I need to show only time there but first value is always 1 jan. How to change this to start from 00:00 or 00:00:00 or just 0 whatever? If i remove datetime from yAxis in that case i have just value from data which is not what i need because i need to show averange time in chart as you can see on example belowe

[![enter image description here][1]][1]

Here is demo

function seconds2timeRich(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? "h, " : "h ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? "m, " : "m ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? "s" : "s") : "0s";
     
        return hDisplay + mDisplay + sDisplay;
     
}

var options = {
            chart: {
                height:200,
                animation: true         
            },
            title: {
                text: null,
            },
            global : {
                useUTC : false
            },
            tooltip: {
                outside: true,
                shared: true,
                formatter: function() {
                    var h = '0'+this.x;
                     return '<b>'+h.slice(-2)+' h</b><br>Avg. time on site on  '+seconds2timeRich(this.point.y/1000);
          
                }

            },
            xAxis: [{
                 minorTickLength: 0,
                 tickLength: 0,
                 labels: {
                    style: {
                        color: 'var(--trock-gray-400)',
                        fontSize:'0.6944444444rem',
                        fontWeight: '500',
                    }
                },
                lineWidth: 0,
                visible:true,
                type: 'category',
                crosshair: {
                    width:2,
                    color: "rgba(58, 125, 238, 0.1)" 
                },
            }],
            yAxis: {
               type: 'datetime',
                softMin: 0,
                softMax: 1,
                min:0,
                minTickInterval:1,
                gridLineColor: 'var(--trock-gray-200)',
                labels: {
                    style: {
                        color: 'var(--trock-gray-400)',
                        fontSize:'0.6944444444rem',
                        fontWeight: '500'
                    }
                },
                opposite: true,
                title: null,
            },
            accessibility: {enabled: false},
            legend:false,
            credits:false,
            plotOptions: {
                area: {
                    stacking: 'normal',    
                    marker: {
                        radius: 0,
                    },
                    lineWidth: 1,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    },
                    threshold: null
                }
            },
            series: [
                {
                    type: 'area',
                    data: [["00",0],["01",20000],["02",0],["03",0],["04",0],["05",0],["06",0],["07",0],["08",0],["09",0],["10",0],["11",26548],["12",0],["13",35000],["14",0],["15",0],["16",0],["17",0],["18",0],["19",0],["20",0],["21",10000],["22",0],["23",0]],
 
                } 
            ]
        };
var AvgChart = Highcharts.chart('container',options);
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>

Web deployment on Railway or any at all

I’m relatively new to full stack web development and I’m currently working on my first mern stack project.

My question is; does your client and server side of a project have to be in the same folder?

I put my client and server side of the project in different folders and it works perfectly in development stage but for some reason not when I try to deploy it.

How to treat array made in function in js like moving another js file

I am trying to change csv file to js array. so I use code as below

const fs = require("fs");
const { parse } = require("csv-parse");


fs.createReadStream("./contentsOfDictionary.csv")
.pipe(parse({ delimiter: ",", from_line: 1, to_line: 1 }))
.on("data", function (row) {
        console.log(row)
})


fs.createReadStream("./contentsOfDictionary.csv")
.pipe(parse({ delimiter: ",", from_line: 2, to_line: 2 }))
.on("data", function (row) {
        console.log(row)
})

and It is working very well by operating at the terminal [~~~~~~~~~~](by function one), [~~~~~~~~~~](by function two)

But I want to use that array in another js file.
Thus What i don’t know is how to use array made by function and how to use that array in another js file

I haved tried like

const a = fs.createReadStream("./contentsOfDictionary.csv")
.pipe(parse({ delimiter: ",", from_line: 1, to_line: 1 }))
.on("data", function (row) {
        return row
})

console.log(a);

It does not work

Im trying to implement a matching question in react.js, I cant seem to get it done

Im working on a quiz app using react.js, the customer asked me to do a matching question but I cant seem to get it done, luckily I found someone who has already done it, but he did it using js/jQuery, and I cant seem to convert the code to jsx, here is the codesandbox link.

Any help would be appreciated, Thanks

function drawLinks(){
  var canvas = $('#canvas').get(0);
  var ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  linkList.forEach(link => drawLink(link.dragId,link.dropId,link.color));
}
function drawLink(obj1,obj2,pColor){  

  var canvas = $('#canvas').get(0);
  var ctx = canvas.getContext('2d');

  var $obj1 = $("#"+obj1);
  var $obj2 = $("#"+obj2);
  var parent = $('#dragQuestion').offset();
  var p1 = $obj1.offset();
  var w1 = $obj1.width();
  var h1 = $obj1.height();
  var p2 = $obj2.offset();
  var w2 = $obj2.width();
  var h2 = $obj2.height();
  var  wc =$('#canvas').width();
  ctx.beginPath();
  ctx.strokeStyle = pColor? pColor : color;
  ctx.lineWidth = 3;
  ctx.moveTo(0,p1.top-parent.top+(h1/2)-20-2);
  ctx.bezierCurveTo(wc/2,p1.top-parent.top+(h1/2)-20-2,
                    wc/2,p2.top-parent.top+(h2/2)-20-2,
                    wc-4,p2.top-parent.top+(h2/2)-20-2);
  ctx.stroke();

  $obj1.children().css( "color", pColor? pColor : color );
  $obj1.children().css( "font-weight", "900" );
  $obj2.children().css( "color", pColor? pColor : color );
  $obj2.children().css( "font-weight", "900" );
  $obj2.children().addClass('linked');
}
function clearPath(event){  
  var ident = event.currentTarget.id;  
  linkList = linkList.filter(obj => {
    return obj.dropId != ident    
  });
  $( "#dragQuestion" ).find( "i" ).removeClass('linked');
  $( "#dragQuestion" ).find( "i" ).css( "font-weight", "400" ); 
  $( "#dragQuestion" ).find( "i" ).css( "color", "black");  
  drawLinks();
}

/****Draw path mouse line****/
function drawLinkTemp(obj1,coordPt){
  var canvas = $('#canvasTemp').get(0);
  var ctx = canvas.getContext('2d');

  var $obj1 = $("#"+obj1);
  var parent = $('#dragQuestion').offset();
  var p1 = $obj1.offset();
  var w1 = $obj1.width();
  var h1 = $obj1.height();
  var p2 = coordPt;
  var  c =$('#canvasTemp').offset();

  ctx.beginPath();
  ctx.strokeStyle = color;
  ctx.lineWidth = 3;
  ctx.moveTo(0,p1.top-parent.top+(h1/2)-20-2);

  ctx.bezierCurveTo((p2.left - c.left)/2,p1.top-parent.top-19-2,
                    (p2.left - c.left)/2,p2.top-parent.top-19-2,
                    p2.left - c.left,p2.top-parent.top-19-2);
  clearPathTemp();  
  ctx.stroke();
}
function clearPathTemp(){
  var canvas = $('#canvasTemp').get(0);
  var ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

Django Rest Framework custom api.html throws warnings on OPTIONS request ajax form

I’m building my custom api.html template for Django Rest Framework api project (based on the official base.html template to customize mine), but I’m facing some issues implementing the OPTIONS button. Here it is my code:

{% load static %} {% load i18n %} {% load rest_framework %}
<!DOCTYPE html>
<html lang="en" id="myHtml">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My project title</title>
    <link rel="shortcut icon" href="{% static 'assets/compass-fill.ico' %}" />

    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      id="theme-link"
      rel="stylesheet"
      href="https://bootswatch.com/5/darkly/bootstrap.min.css"
      type="text/css"
    />

    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"
    />

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>

  </head>
  <body>
    <div class="container">
      ...
      {% if options_form %}
      <form
        class="button-form"
        action="{{ request.get_full_path }}"
        data-method="OPTIONS"
      >
        <button
          type="submit"
          class="btn btn-primary"
          data-bs-toggle="tooltip"
          data-bs-title="Make an OPTIONS request on the {{ name }} resource"
          data-bs-custom-class="tooltip-success"
        >
          OPTIONS
        </button>
      </form>
      {% endif %}
      ...
    </div>
    ...
    <script type="application/json" id="drf_csrf">
      {
        "csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}",
        "csrfToken": "{% if request %}{{ csrf_token }}{% endif %}"
      }
    </script>
    <script src="{% static 'rest_framework/js/ajax-form.js' %}"></script>
    <script src="{% static 'rest_framework/js/load-ajax-form.js' %}"></script>
    <script src="{% static 'rest_framework/js/csrf.js' %}"></script>
    <script> other scripts </script>
  </body>
</html>

I created the OPTIONS button like in the original template base.html and in the end of the body I loaded js functions without them the button function not works.
Unfortunately if clicked it will throw the error inside the console repeating this for every script used in the document:

...
A parser-blocking, cross site (i.e. different eTLD+1) script, https://code.jquery.com/jquery-3.7.0.min.js, is invoked via document.write. 
The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. 
If blocked in this page load, it will be confirmed in a subsequent console message. 
See https://www.chromestatus.com/feature/5718547946799104 for more details.
...

Seems like the ajax call is causing all this troubles, but I just created functions, copied from the official repo branch files (load-ajax-form.js, ajax-form.js, csrf.js) and put them inside my static/rest_framework/js folder.

Where I’m wrong on customize the template ?

How to create a basketball matchmaking system in js

I need to create a matchmaking app for a project in javascript. The app should take an even or not even number of teams.

Τhe problem is that the teams should not play (obviously) themselves, also the same teams should not play each other twice and if a team is left over then that team will get the week off. At the end, all teams must have taken a day off (if the total number of teams is not an even number).And finally a team cannot play twice the same week.

So for example if we have an array of teams [‘A’,’B’,’C’] (not even), then i should get something like this:

[[[A,B],[C]],[[A,C],[B]],[[B,C],[A]]]

And the same for even teams [‘A’,’B’,’C’,’D’] with the only difference that none of the teams have a day off.

Sorry for my english, i hope i was clear enough 😀

The only thing ive tried is this
https://stackoverflow.com/questions/63224352/how-to-dynamically-generate-possible-encounters-between-teams

but i couldnt make it work as i wanted

Why does Electron’s desktopCapturer return nothing (under the JSON tree), which causes a crash on my program?

I tried to use desktopCapturer in Electron, but when I tried to fetch all available sources, it returns a null value in all of those sources. Here, I got an example of 4 sources displaying in the JSON tree, but it came up with no name. Here is the image of the JSON tree from the console.

enter image description here

As you can see, the name field is empty. When this happens, I often get a crash that I couldn’t find the name of the sources. Here is the code when it’s handy to solve the problem.

const { desktopCapturer } = require('@electron/remote');

const StartCapture = async () => {
  const AppSources = await desktopCapturer.getSources({ types: ['screen', 'window'] });
  console.log(AppSources)
  const SelSource = AppSources.find(Source => Source.name === 'Screen Name');
  
  if (!SelSource) {
    console.error('Screen source not found');
    return;
  }
  
  const VideoRenderer = document.createElement('video');
  VideoRenderer.srcObject = await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: {
      mandatory: {
        chromeMediaSource: 'desktop',
        chromeMediaSourceId: SelSource.id,
        minWidth: 960,
        maxWidth: 2560,
        minHeight: 480,
        maxHeight: 1440
      }
    }
  });
  
  VideoRenderer.play();
  
  const CanvasRenderer = document.getElementById('canvas-renderer');
  const CanvasCTX = CanvasRenderer.getContext('2d');
  
  setInterval(() => {
    CanvasCTX.drawImage(VideoRenderer, 0, 0, CanvasRenderer.width, CanvasRenderer.height);
  }, 1000 / 60);
};

document.getElementById('ui-start-capture').addEventListener('click', StartCapture);

In the entry side, I have already enabled the @electron/remote module. Here is a snippet.

require('@electron/remote/main').initialize()
    require('@electron/remote/main').enable(UIWindow.webContents)

Can anyone please help me on how to fix this problem? Thanks.

I have object admins in my react native component I extract it from state but after mapping names are show but image is not shown?

I try to making an app in school manegment system.In which currently I am working on a module manageadmin.So I setup a redux store in it where i create the action and reducer.I dispatch my action in useEffect which gets the data of all admins.

I extracted the admins from my state in this form
const {admins,loading}=useSelector((state)=>state.getAllAdminInfo)

so on console.log(admins) the output it

{“success”: true, “users”: [{“__v”: 0, “_id”: “64a8f81b7d3960bfbccacd1b”, “address”: “37 gn housing society,joher town,Lahore”, “createdAt”: “2023-07-08T05:46:03.311Z”, “email”: “[email protected]”, “image”: [Object], “name”: “Mirza”, “phone”: “04567447043”, “role”: “admin”}, {“__v”: 0, “_id”: “64a8ffc391f2d6c9f7943587”, “address”:
“37 gn housing society joher town,Lahore”, “createdAt”: “2023-07-08T06:18:43.390Z”, “email”: “[email protected]”, “image”: [Object], “name”: “Mirzaammar”, “phone”: “03124119378”, “role”: “admin”}, {“__v”: 0, “_id”: “64a90024da8a1dee5c1a097f”, “address”: “37 gn housing society joher town,Lahore”, “createdAt”: “2023-07-08T06:20:20.678Z”, “email”: “[email protected]”, “image”: [Object], “name”: “Mirzaammar”, “phone”: “03124119378”, “role”: “admin”}, {“__v”: 0, “_id”: “64a92893d63b25433d94ec0a”, “address”: “37 gn housing society,joher town,Lahore”, “createdAt”: “2023-07-08T09:12:51.905Z”, “email”: “[email protected]”, “image”: [Object], “name”: “Ammar”, “phone”: “03124119378”, “role”: “admin”}, {“__v”: 0, “_id”: “64a9297fd63b25433d94ec13”, “address”: “37 gn housing society,jiher town,Lahore”, “createdAt”: “2023-07-08T09:16:47.226Z”, “email”:
[email protected]”, “image”: [Object], “name”: “Ammar”, “phone”: “03124119378”, “role”: “admin”}, {“__v”: 0, “_id”: “64a929d2d63b25433d94ec18”, “address”: “37 gn hosuing society,joher town.Lahore”, “createdAt”: “2023-07-08T09:18:10.469Z”, “email”: “[email protected]”, “image”: [Object], “name”: “Azeem”, “phone”: “03124119378”, “role”: “admin”}]}

So on mapping other information are shown but image is not shown I can’t able to understand what the reason behind that so I share the code of my component here so please help me to understand that

Here is the code of my component

import React, { useEffect, useState } from 'react';
import { View, Text, TextInput, Button, Image, TouchableOpacity, Modal, StyleSheet, Animated } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { useDispatch, useSelector } from 'react-redux';
import { addAdmin,getAdmins } from '../../actions/adminAction';
import Loader from '../Loader';
import { FlatList, ScrollView } from 'react-native-gesture-handler';
import { userReducer } from '../../reducers/userReducer';
const RegisterAdminForm = () => {
  const dispatch = useDispatch();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [password, setPassword] = useState('');
  const [image, setImage] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const [modalOpacity] = useState(new Animated.Value(0));
  const [modalScale] = useState(new Animated.Value(0));
 
  
  const {admins,loading}=useSelector((state)=>state.getAllAdminInfo)
  


  
  const handleRegister = () => {
    dispatch(addAdmin(name, email, phone, address, password, image));
    // Close the modal after registering
    setShowModal(false);
  };

  useEffect(()=>{
    dispatch(getAdmins());
    console.log("admins is");
    console.log(admins);
   },[dispatch])
   

  const handleSelectImage = async () => {
    try {
      const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
  
      if (!permissionResult.granted) {
        alert('Permission to access media library is required!');
        return;
      }
  
      const pickerResult = await ImagePicker.launchImageLibraryAsync();
  
      if (!pickerResult.cancelled) {
        const selectedAssetUri = pickerResult.assets[0].uri;
        setImage(selectedAssetUri);
      }
    } catch (error) {
      console.log('Error selecting image:', error);
    }
  };
  
  const handleModalOpen = () => {
    setShowModal(true);
    Animated.parallel([
      Animated.timing(modalOpacity, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }),
      Animated.spring(modalScale, {
        toValue: 1,
        friction: 8,
        tension: 40,
        useNativeDriver: true,
      }),
    ]).start();
  };

  const handleModalClose = () => {
    Animated.parallel([
      Animated.timing(modalOpacity, {
        toValue: 0,
        duration: 300,
        useNativeDriver: true,
      }),
      Animated.spring(modalScale, {
        toValue: 0,
        friction: 8,
        tension: 40,
        useNativeDriver: true,
      }),
    ]).start(() => setShowModal(false));
  };

  const modalAnimationStyles = {
    opacity: modalOpacity,
    transform: [{ scale: modalScale }],
  };
  
  if (loading) {
    // Show loader while loading is true
    return <Loader />;
  }

  return (
    loading ? <Loader /> :(
    <View style={styles.container}>
      <View style={styles.containerManageAdmin}>
      <TouchableOpacity onPress={handleModalOpen}>
        <Text style={styles.manageAdminText}>Manage Admin</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={handleModalOpen}>
        <Text style={styles.plusText}>+</Text>
      </TouchableOpacity>
      </View>
      <ScrollView style={styles.adminsContainer}>
      {admins && admins.users ? (
    admins.users.map(admin => (
      <View key={admin._id} style={styles.adminCard}>
{admin.image && admin.image.url ? (
    <Image source={{ uri: admin.image.url }} style={styles.adminImage} />
  ) : null}
        <Image source={{ uri: admin.image.url }} style={styles.adminImage} />
        <Text>Name: {admin.name}</Text>
        <Text>Email: {admin.email}</Text>
        <Text>Phone: {admin.phone}</Text>
        <Text>Address: {admin.address}</Text>
        <Image
            source={{ uri: admin.image.url }}
            style={styles.ProfileImageIneer}
          />
        
        {admin.image && admin.image.uri && (
          <Image source={{ uri: admin.image.url }} style={styles.adminImage} />
        )}
      </View>
    ))
  ) : (
     <Loader/>
  )}          
      </ScrollView>
      <View></View>
      
      <Modal visible={showModal} animationType="none" transparent>
        <View style={styles.modalContainer}>
          <Animated.View style={[styles.modalContent, modalAnimationStyles]}>
          <Text>Name:</Text>
          <TextInput
            value={name}
            onChangeText={setName}
            placeholder="Enter your name"
          />
          <Text>Email:</Text>
          <TextInput
            value={email}
            onChangeText={setEmail}
            placeholder="Enter your email"
          />
          <Text>Phone:</Text>
          <TextInput
            value={phone}
            onChangeText={setPhone}
            placeholder="Enter your phone"
          />
          <Text>Address:</Text>
          <TextInput
            value={address}
            onChangeText={setAddress}
            placeholder="Enter your address"
          />
          <Text>Password:</Text>
          <TextInput
            value={password}
            onChangeText={setPassword}
            secureTextEntry
            placeholder="Enter your password"
          />
          {image && <Image source={{ uri: image }} style={{ width: 100, height: 100 }} />}
          <TouchableOpacity onPress={handleSelectImage}>
            <Text>Select Image</Text>
          </TouchableOpacity>
            <View style={styles.buttonContainer}>
            <Button title="Register" onPress={handleRegister} />
            <Button title="Cancel" onPress={handleModalClose} color="red" />
              
            </View>
          </Animated.View>
        </View>
        
      </Modal>
    </View>
    )
  )
  
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  containerManageAdmin: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  manageAdminText: {
    fontSize: 20,
    padding: 10,
    marginRight: 10,
  },
  plusText: {
    fontSize: 40,
    padding: 10,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 20,
    minWidth: 300,
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  
 
});

export default RegisterAdminForm;

I share you the code so please kindly check the code.

handling a get 400 (bad request) console error in promise.race()

I have a function that runs on submitting a form

const displayRecipeList = async search => {
  try {
    renderSpinner();
    const recipeList = await getJSON(
      `https://forkify-api.herokuapp.com/api/search?q=${search}`
    );
    renderRecipeList(recipeList.recipes);
  } catch (err) {
    clearResultList();
    clearSearchInput();
    searchResults.insertAdjacentHTML(
      `beforeend`,
      `
      <div class="error">
        <div>
          <svg>
            <use href="${icons}#icon-alert-triangle"></use>
          </svg>
        </div>
        <p>No recipes found for your query. Please try again!</p>
      </div>`
    );
  }
};

the function will call getJSON() function and try to fetch API with the search term, if it’s right it will render RecipeList and display it. if it’s wrong it should display an error.

const getJSON = async url => {
  const fetchRecipeList = await Promise.race([timeout(5), fetch(`${url}`)]);
  if (!fetchRecipeList.ok) throw new Error(`Something Went Wrong`);
  return await fetchRecipeList.json();
};

everything works ok but I get a
GET https://forkify-api.herokuapp.com/api/search?q=asd 400 (Bad Request)
logged into the console when i’m trying to search something that don’t exist on purpose

why does my error handling doesn’t replace this error? and how can I do that? I’m assuming that I need to add the try catch blocks to the getJSON as well but it’s not working for me after trying couple of options, is it because it’s in a promise.race() that it can’t catch this error?

How do fetch data in react without using proxy?

I’m currently working on a flight management system web application using React, and I’m having trouble fetching data from my API. The application runs perfectly on my local server when I use the proxy configuration in the package.json file, but when I host the website and manually provide the API URL, the fetching process doesn’t work as expected.

I have a UserApi module that contains various functions for interacting with the API endpoints. Initially, I used the fetch API for making the HTTP requests, and it worked fine when I used the proxy configuration. However, when I removed the proxy and provided the API URL directly in the fetch calls, the data is not being fetched properly. It seems that the requests are not reaching the API endpoints.

To troubleshoot the issue, I tried using the Axios library instead of the fetch API, hoping it would resolve the problem. I updated the UserApi module to use Axios for making the HTTP requests. However, the issue persists, and I’m unable to fetch the required data.

I have checked the API endpoints separately using tools like Postman, and they return the expected data. The problem only occurs when I try to fetch the data from my React application.

I have also verified that there are no CORS-related issues because the proxy configuration worked fine during development. It seems to be a problem with the actual URL when not using the proxy.

I would appreciate any guidance or suggestions on how to resolve this issue and successfully fetch data from my API in the hosted React application.

Thank you in advance for your help.

Here is my code that is working

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "prettier --write ."
  },


  "proxy" : "https://devrev-fms.onrender.com",


  "dependencies": {
    "@emotion/react": "^11.9.3",
    "@emotion/styled": "^11.9.3",
    "@mui/icons-material": "^5.8.4",
    "@mui/material": "^5.9.1",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.4.0",
    "bootstrap": "^5.3.0",
    "dayjs": "^1.11.4",
    "highcharts": "^10.2.0",
    "highcharts-react-official": "^3.1.0",
    "localforage": "^1.10.0",
    "react": "^18.2.0",
    "react-bootstrap": "^2.8.0",
    "react-dom": "^18.2.0",
    "react-notifications": "^1.7.4",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "devDependencies": {
    "prettier": "^2.7.1"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

User.js

import axios from "axios";

export const UserApi = {
  borrowFlight: async (flightNo, userId) => {
    try {
      const res = await axios.post(
        "/v1/user/borrow",
        { flightNo, userId },
        { headers: { "Content-Type": "application/json" } }
      );
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  returnFlight: async (flightNo, userId) => {
    try {
      const res = await axios.post(
        "/v1/user/return",
        { flightNo, userId },
        { headers: { "Content-Type": "application/json" } }
      );
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  getBorrowFlight: async () => {
    try {
      const res = await axios.get("/v1/user/borrowed-flights");
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  login: async (username, password) => {
    try {
      const res = await axios.post(
        "/v1/user/login",
        { username, password },
        { headers: { "Content-Type": "application/json" } }
      );
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  getProfile: async () => {
    try {
      const res = await axios.get("/v1/user/profile");
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  logout: async () => {
    try {
      const res = await axios.get("/v1/user/logout");
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
};

But I can’t use proxy in production so this is what I did

User.js

import axios from "axios";

export const UserApi = {
  borrowFlight: async (flightNo, userId) => {
    try {
      const res = await axios.post(
        "https://devrev-fms.onrender.com/v1/user/borrow",
        { flightNo, userId },
        { headers: { "Content-Type": "application/json" } }
      );
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  returnFlight: async (flightNo, userId) => {
    try {
      const res = await axios.post(
        "https://devrev-fms.onrender.com/v1/user/return",
        { flightNo, userId },
        { headers: { "Content-Type": "application/json" } }
      );
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  getBorrowFlight: async () => {
    try {
      const res = await axios.get("https://devrev-fms.onrender.com/v1/user/borrowed-flights");
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  login: async (username, password) => {
    try {
      const res = await axios.post(
        "https://devrev-fms.onrender.com/v1/user/login",
        { username, password },
        { headers: { "Content-Type": "application/json" } }
      );
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  getProfile: async () => {
    try {
      const res = await axios.get("https://devrev-fms.onrender.com/v1/user/profile");
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
  logout: async () => {
    try {
      const res = await axios.get("https://devrev-fms.onrender.com/v1/user/logout");
      return res.data;
    } catch (error) {
      // Handle the error
      console.error(error);
      throw error;
    }
  },
};

HTML input Javascript to detect enter/return key not working

I have been calling this script from a DOS batch file to input data into a variable.

It works but I have two problems.

Firstly it does not detect the return/enter keypress in Chrome. I only have a return key, but I presume Enter returns the same code.

Secondly when the input box appears is there a way to make it active, with the cursor already in the box?

Thanks

<!-- :
::
@echo off
setlocal EnableDelayedExpansion

if "%~1" equ "/?" (
    echo Creates an input value window and output
    echo   the result to console or assign it to variable
    echo   if variable name is passed
    (echo()
    echo Usage:
    (echo()
    echo %~0nx [storeInputTo]
)
for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
    set "input=%%p"
)


if "%~1" equ "" (
    echo "%input%"
    endlocal
) else (
    endlocal & (
        set "%~1=%input%"
    )
)
exit /b
-->

<html>
<head><title>Enter Album Name</title></head>
<body>

    <script language='javascript' >
        window.resizeTo(650,250);
        window.moveTo((screen.width/2)-325, (screen.height/2)-125);
        function enterPressed(e){
                if (e.keyCode == 13) {
                    pipePass();
                }
        }
        function pipePass() {
            var pass=document.getElementById('input').value;
            var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
            close(fso.Write(pass));

        }
    </script>

    <input type="text" id="input" value="" size="50">
    <hr>
    <button onclick='pipePass()'>Submit</button>

</body>
</html>

Ideally I would like:

Return/Enter to be detected instead of having to click Submit.

Cursor to be active in input box so no need to click before typing.

Thank you for any assistance.

Cannot read properties of undefined (reading ‘push’) in next js

“next”: “13.0.7”
pages version

I’ve got this error in console production mode :

TypeError: Cannot read properties of undefined (reading 'push')

while this message shows on the screen :

Application error: a client-side exception has occurred (see the browser console for more information).

I can’t find the problem

this is how I used router :

    import React from 'react';
import {useSelector} from "react-redux";
import {ALL_VENDORS, PANEL, PUBLIC_PANEL, SIGNAL, VENDORS} from "/navigation/CONSTANS";
import {useRouter} from "next/router";

const Item = () => {
    const {myService} = useSelector(state => state.service);
    const [openBuy, setOpenBuy] = React.useState(false);

    const router = useRouter();

    console.log("test:", router)

    const changePage = () => {
        if (router.isReady)
            router.push((myService.service_owner?.id === detail.service_owner?.id)
                ?
                `${PANEL}${SIGNAL}`
                :
                `${PUBLIC_PANEL}${VENDORS}/${detail?.id}/${detail.service_owner?.id}`)
    };


    return (
        <>
           <div onClick={changePage}>check</div>
        </>
    );
};

export default Item;

enter image description here

enter image description here

How to add space between elements in JavaScript (react)?

Let me start by saying I am very new to javascript and react. I am making a page that has a title and a MUI table underneath it which currently looks like this:
(https://i.stack.imgur.com/znHio.png)

However I want to add space between the title and the table but can’t figure out how to.

This is what the code looks like:

return (
    <div className="dates" >
        <div>
        <h1 style={{ fontSize: 40 }}>Upcoming Import Dates</h1>
        </div>
        <div>
            <TableContainer component={Paper} style={{ width: 900, backgroundColor: "#dbdbdb"}}>
            <Table>
            <TableHead>
                <TableRow >
                <TableCell align="left" style={{ width: 200 }}>Date</TableCell>
                <TableCell align="left">Time</TableCell>
                <TableCell align="left">Event</TableCell>
                <TableCell align="left" style={{ width: 350 }}>Location</TableCell>
                </TableRow>
            </TableHead>
            <TableBody>
                {dates.map((dates) => (
                <TableRow key={dates.number}>
                    <TableCell align="left">{dates.EventDate}</TableCell>
                    <TableCell align="left">{dates.StartTime}</TableCell>
                    <TableCell align="left">{dates.Description}</TableCell>
                    <TableCell align="left">{dates.Location}</TableCell>
                </TableRow>
                ))}
            </TableBody>
            </Table>
            </TableContainer>
        </div>
   </div>
 );

I have tried adding margin-bottom to a css class and adding it to the div but that did not work. I’ve looked online and can’t seem to find anything so any help would be appreciated.

Error sending POST request to SendGrid using React and Express

I’m developing a website that includes a contact form, and I’m using the SendGrid module to send the form data via email to ****@gmail.com. However, when I click the send button, the POST request does not work, and I receive the following error: “xhr.js:210 POST http://localhost:3000/send-email 404 (Not Found)”.

I have checked the console to see if the values for the contact data have been correctly inputted, and it appears to be working fine. Here is the client-side code for my contact form in card.tsx:

import React, { useState, useEffect, useRef } from "react";
import cardcss from "./Card.module.css";
import axios from "axios";

interface CardProps {
  imageUrl: string;
  title: string;
  body: string;
}

function Card(props: CardProps) {
  const [message, setMessage] = useState("");
  const nameInputRef = useRef<HTMLInputElement>(null);
  const emailInputRef = useRef<HTMLInputElement>(null);
  const messageInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (messageInputRef.current) {
      messageInputRef.current.focus();
      messageInputRef.current.setSelectionRange(0, 0);

      // Delay setting the cursor position
      setTimeout(() => {
        messageInputRef.current?.setSelectionRange(0, 0);
      }, 0);
    }
  }, []);

  const handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
    event.target.setSelectionRange(0, 0);
  };

  const submitHandler = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (
      nameInputRef.current &&
      emailInputRef.current &&
      messageInputRef.current
    ) {
      const nameInput = nameInputRef.current.value;
      const emailInput = emailInputRef.current.value;
      const messageInput = messageInputRef.current.value;

      const contactData = {
        Name: nameInput,
        Email: emailInput,
        Message: messageInput,
      };
      console.log(contactData);

      axios
        .post("http://localhost:3000/send-email", contactData)
        .then((response) => {
          console.log("Received email request");
          // Handle success response
        })
        .catch((error) => {
          console.error(error);
          // Handle error response
        });
    }
  };

  return (
    <div className={cardcss.cardcontainer}>
      <div className={cardcss.imagecontainer}>
        <img src={props.imageUrl} alt="" />
      </div>

      <div className={cardcss.cardtitle}>
        <h3>{props.title}</h3>
      </div>

      <div className={cardcss.cardbody}>
        <p>{props.body}</p>

        <form onSubmit={submitHandler}>
          <div>
            <label className={cardcss.namelabel} htmlFor="name">
              Name:
            </label>
            <input
              className={cardcss.nameinput}
              type="text"
              id="name"
              name="name"
              ref={nameInputRef}
            />
          </div>

          <div className={cardcss.emailcontainer}>
            <label className={cardcss.emaillabel} htmlFor="email">
              Email:
            </label>
            <input
              className={cardcss.emailinput}
              type="text"
              id="email"
              name="email"
              ref={emailInputRef}
            />
          </div>

          <div className={cardcss.messagecontainer}>
            <label className={cardcss.messagelabel} htmlFor="message">
              Message:
            </label>
            <input
              ref={messageInputRef}
              className={cardcss.messageinput}
              type="text"
              id="message"
              name="message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onFocus={handleFocus}
            />

            <button className={cardcss.sendbutton} type="submit">
              Send
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default Card;

And here is the server-side code in server.js:

const express = require("express");
const sgMail = require("@sendgrid/mail");
const { resolve } = require("path-browserify");

// Set up SendGrid API key
sgMail.setApiKey(
  "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"
);

// Create Express app
const app = express();

// Middleware to parse JSON requests
app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello, server!");
});
// Route to handle sending emails
app.post("/send-email", (req, res) => {
  const { Name, Email, Message, submitbutton } = req.body;

  const msg = {
    to: "[email protected]",
    from: "[email protected]",
    subject: "Example Subject",
    text: `Name: ${Name}nEmail: ${Email}nMessage: ${Message}nSubmit Button: ${submitbutton}`,
    html: `<p>Name: ${Name}</p><p>Email: ${Email}</p><p>Message: ${Message}</p><p>Submit Button: ${submitbutton}</p>`,
  };

  sgMail
    .send(msg)
    .then(() => {
      res.status(200).json({ message: "Email sent successfully" });
    })
    .catch((error) => {
      console.error(error.toString());
      res.status(500).json({ error: "Failed to send email" });
    });
});

// Set up fallback for path module
resolve.fallback = { path: require.resolve("path-browserify") };

// Start the server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

I’m wondering why I’m getting this POST request error and how to fix it. Any help would be greatly appreciated.