How to retrieve child form values when parent form is submitted in Reactjs?

I’m currently working on a React project which is using Shadcn ui Form and React Form Hook to create the forms. I have a MainForm component responsible for rendering either an ArrivalForm or DepartureForm based on user selection.

How can I retrieve the values entered in both the MainForm and ArrivalForm components specifically when the user selects Arrival and submits the MainForm?

Here’s a simplified version of my code structure:

//this is mainform.tsx
export function MainForm() {
  const { toast } = useToast();
  const [formSelected, setFormSelected] = useState<string | null>('');
  // 1. Define your form using Schema define from z.
  const form = useForm<z.infer<typeof mainFormSchema>>({
    resolver: zodResolver(mainFormSchema),
    defaultValues: {
      fullname: '',
      email: '',
      formSelected: undefined,
    },
  });

  // 2. Define a submit handler.
  function onSubmit(values: z.infer<typeof mainFormSchema>) {
    console.log(values);
    toast({
      title: 'Submit Values is:',
      description: (
        <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
          <code className="text-white">{JSON.stringify(values, null, 2)}</code>
        </pre>
      ),
    });
  }

  // 3. Return a form
  return (
    <>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
          <FormField
            control={form.control}
            name="fullname"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Fullname</FormLabel>
                <FormControl>
                  <Input placeholder="Please input your full name" {...field} />
                </FormControl>
                <FormDescription>
                  This is your public display name.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Email</FormLabel>
                <FormControl>
                  <Input placeholder="Please input your email" {...field} />
                </FormControl>
                <FormDescription>
                  This is your public display name.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="formSelected"
            render={({ field }) => (
              <FormItem>
                <RadioGroup
                  onValueChange={field.onChange}
                  defaultValue={field.value}
                >
                  <div className="flex">
                    <div className="flex items-center space-x-2 px-2">
                      <RadioGroupItem
                        value="arrival"
                        id="arrival"
                        onClick={() => {
                          setFormSelected('arrival');
                        }}
                      />
                      <Label htmlFor="arrivalRadio">Arrival</Label>
                    </div>
                    <div className="flex items-center space-x-2 px-2">
                      <RadioGroupItem
                        value="departure"
                        id="departure"
                        onClick={() => {
                          setFormSelected('departure');
                        }}
                      />
                      <Label htmlFor="departureRadio">Departure</Label>
                    </div>
                  </div>
                </RadioGroup>
                <FormMessage />
              </FormItem>
            )}
          />

          {formSelected === 'arrival' ? <ArrivalForm /> : null}
          {formSelected === 'departure' ? <DepartureForm /> : null}

          <Button type="submit">Submit</Button>
        </form>
      </Form>
    </>
  );
}
// This is arrivalForm.tsx
export function ArrivalForm() {
  // 1. Define your form using Schema define from z.
  const form = useForm<z.infer<typeof arrivalFormSchema>>({
    resolver: zodResolver(arrivalFormSchema),
    defaultValues: {
      guestName: '',
      arrivalInfo: '',
    },
  });

  // 2. Define a submit handler.
  function arrivalFormSubmit(values: z.infer<typeof arrivalFormSchema>) {
    // pass form values to the parent form:
    console.log(values);
  }

  // 3. Return a form
  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(arrivalFormSubmit)}
        className="space-y-8"
      >
        <FormField
          control={form.control}
          name="guestName"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Guest Name</FormLabel>
              <FormControl>
                <Input placeholder="input Guest Name" {...field} />
              </FormControl>
              <FormDescription>Guest Name here</FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="arrivalInfo"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Arrival Infomation</FormLabel>
              <FormControl>
                <Input placeholder="input Arrival Info Here" {...field} />
              </FormControl>
              <FormDescription>Arrival Info here</FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
      </form>
    </Form>
  );
}
// mainFormSchema 
export const mainFormSchema = z.object({
  fullname: z.string().min(2, {
    message: 'Username must be at least 2 characters.',
  }),
  email: z.string().min(2, {
    message: 'Username must be at least 2 characters.',
  }),
  formSelected: z.enum(['arrival', 'departure'], {
    message: 'You need to select a booking type.',
  }),
});

// arrivalFormSchema
export const arrivalFormSchema = z.object({
  guestName: z.string().min(2, {
    message: 'Guest name must be at least 2 characters.',
  }),
  arrivalInfo: z.string().min(2, {
    message: 'Please enter arrival info',
  }),
});

how to check how many [] symbols array contain

So, I have an array like this
const array=[1,2,3,4,[5,6],[[[[7,8]]]]]. I know that I can make it flat by flat function like this.
array.flat(4) // [1,2,3,4,5,6,7,8]

But as you know we can to this when we know array external count of this [] symbols. However we can fetch
any data that we don’t know how many [] this symbols are there in array. My question is that how to check
how many [] – this symbols are there within array.

Character Text to HTML

So I have tried using jsPDF but I have tried fixing the errors but the code doesn’t recognise jsPDF

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Generate PDF jsPDF</title>
</head>

<body>
    <button id="button" onclick="pdf()">Create PDF</button>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
    function pdf() {
        var doc = new jsPDF()
        doc.text('hello, world!', 10, 10)
        doc.save('output.js')
    }
</script>

</html>

Tried changing where the function started but it still doesn’t wanna play ball.

How to encode audio buffer for mp4-muxer using only client side?

Running Vanligy mp4 muxer demo as shown on https://github.com/Vanilagy/mp4-muxer/tree/main/demo works fine on a desktop but produces an error on Android as follows:

“EncodingError: input audio buffer is incompatible with codec paramers.”

Any idea on how to set audioEncoder.configure on Android chrome?

if (audioTrack) {
    audioEncoder = new AudioEncoder({
        output: (chunk, meta) => muxer.addAudioChunk(chunk, meta),
        error: e => console.error(e)
    });
    audioEncoder.configure({
        codec: 'mp4a.40.2',
        numberOfChannels: 1,
        sampleRate: audioSampleRate,
        bitrate: 128000
    });

    // Create a MediaStreamTrackProcessor to get AudioData chunks from the audio track
    let trackProcessor = new MediaStreamTrackProcessor({ track: audioTrack });
    let consumer = new WritableStream({
        write(audioData) {
            if (!recording) return;
            audioEncoder.encode(audioData);
            audioData.close();
        }
    });
    trackProcessor.readable.pipeTo(consumer);
}

Expecting to be able to do MP4 Muxing audio and video on smartphone the same way as on a desktop. The audio buffer doesn’t seem to work on Android chrome using codec ‘mp4a.40.2’.

Response String not printing in HTML same as typescript file

I am using angular code to retrieve values of a string array called response.resultData this works for certain values but when I try to print the values ending with , it prints the values missing the part after the comma and space.

Hydrocephalus in infectious and parasitic diseases classified
elsewhere (A00-B94.9, B99+)

is being printed as

Hydrocephalus in infectious and parasitic diseases classified
elsewhere (A00-B94.9

this.problemListService.getVisitWisePomrActive(patientPomr).subscribe(response => {
    if (response != null && Array.isArray(response.resultData) && (response.resultData.length > 0)) {
        problems = response.resultData.map(diagnosis => diagnosis.selectedDisease).join(' ,');
        console.log(problems);
<tr>
    <td colspan="18" style="font-size:11pt !important;padding:1px 5px !important"> Diagnosis :
    </td>
    <td colspan="158"
        style="border-bottom:1px dotted black !important;font-size:11pt !important;padding:1px 5px !important;">
        {{narcoticObj.diagnosis}}</td>
    <td colspan="16" style="font-size:11pt !important;padding:1px 5px !important; text-align: right;">:
        لتشخيص
    </td>
</tr>

Printing not printing

    const articles = await page.$$eval('.SearchArticleResult_article__wIpzh', (elements, dateFilter) => {
        console.log("Articles before filtering:", elements.length); // Print number of articles before filtering
        const allArticles = elements.map(element => {
            const urlElement = element; // The element itself is the anchor containing the URL
            const titleElement = element.querySelector('h3.type__h5'); // Selector for the title
            const sourceElement = element.querySelectorAll('.SearchArticleResult_articleMeta__QpcRj')[0]; // First span for source
            const dateElement = element.querySelectorAll('.SearchArticleResult_articleMeta__QpcRj')[1]; // Second span for date
            const dateText = dateElement ? dateElement.textContent.trim() : null;
            const date = new Date(dateText); // Convert date text to Date object
            return {
                url: urlElement ? urlElement.href : null,
                title: titleElement ? titleElement.textContent.trim() : null,
                source: sourceElement ? sourceElement.textContent.trim() : null,
                date: date,
                dateText: dateText // Keep the original date text for reference
            };
        });
        const filteredArticles = allArticles.filter(article => article.date > new Date(dateFilter));
        console.log("Articles after filtering:", filteredArticles.length); // Print number of articles after filtering
        return filteredArticles;
    }, config.dateFilter); // Pass dateFilter as an argument

    log.info(`Found ${articles.length} articles.`);
    await Dataset.pushData(articles);
    log.info(`Saved articles from current page.`);        
    // log.info(`Processing ${JSON.stringify(articles)}`);

    // Insert articles after scraping
    await insertArticles(articles);

This section of code isn’t running. It works when I just have the articles variable without the allarticles variable inside of it.

Can’t style standard audio tag

I’m not very strong in the front. I tried for 2 hours to remove the volume control, to remove at least something from the standard styling, but all in vain.

    {% for audio in audios %}
    <div class="col-7 audio-player" style="margin-top:10px;">
    <span><b>{{ audio.audio.author }}</b> {{ audio.audio.title }}</span>
    <div style="display: flex;">
        <audio controls="false" class="audio-element" data-audio-id="{{ audio.audio.id }}">
            <source src="{{ audio.audio.audio_file.url }}" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
        {% comment %} <button class="btn btn-outline-primary play-audio" data-audio-id="{{ audio.audio.id }}">Play</button>
        <button class="btn btn-outline-primary pause-audio" data-audio-id="{{ audio.audio.id }}">Pause</button> {% endcomment %}
        <button class="btn btn-outline-danger delete-audio"
        data-audio-id="{{ audio.audio.id }}">-</button>
    </div>
</div>
{% endfor %}


.audio-player {
    width: 500px; /* Ширина плеера */
  }


    .audio-player audio {
     width: 100%;
     height: 40px;
     background-color: black;
  }

js if it need:

var audioElements = document.querySelectorAll('audio');

var successMessage = $("#jq-notification");

audioElements.forEach(audio => {
    audio.addEventListener('play', () => {
        audioElements.forEach(element => {
            if (element !== audio) {
                element.pause();
                element.currentTime = 0;
            }
        });
    });
});
audioElements.forEach((audio, index) => {
    audio.addEventListener('ended', () => {
        const nextAudio = audioElements[index + 1];
        if (nextAudio) {
            nextAudio.play();
        }
    });
});


const volumeSlider = document.querySelector('.volume-slider');

volumeSlider.addEventListener('input', () => {
    const volume = parseFloat(volumeSlider.value);
    audioElements.forEach(audio => {
        audio.volume = volume;
    });
});

the best that was possible was to hide the entire element completely, but I needed some parts, a volume control for example, I was looking for answers, but I only found some super strange and complex approach in which there is no audio at all, and where there is, they have everything perfectly stylized, but for some reason I don’t have it
Help me please(

How can I fix this error from react-native?

I’m trying to make some scanner app with react native and i was programming the basic frame of the project, but it keeps throwing error.

Here are my code:

App.js

import App from './src/App';

export default App;

src/App.js

import { StatusBar } from 'expo-status-bar';
import { NavigationContainer } from '@react-navigation/native';
import { Stacks } from './Stack';

const App = () => {
  return (
    <NavigationContainer>
      <StatusBar style="auto" />
      <Stacks />
    </NavigationContainer>
  );
};

export default App;

src/Stack.js

import { createNativeStackNavigator } from '@react-navigation/native-stack';
import CameraScreen from './screens/CameraScreen';
import InfoScreen from './screens/InfoScreen';

const Stack = createNativeStackNavigator();

const Stacks = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Camera" component={CameraScreen} />
      <Stack.Screen name="Info" component={InfoScreen} />
    </Stack.Navigator>
  );
};

export default Stacks;

src/screens/CameraScreen.js

import { StyleSheet, Text, View } from 'react-native';

const CameraScreen = () => {
  return (
    <View style={styles.container}>
      <Text>CAMERA SCREEN</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default CameraScreen;

src/screens/InfoScreen.js

import { StyleSheet, Text, View } from 'react-native';

const InfoScreen = () => {
  return (
    <View style={styles.container}>
      <Text>INFO SCREEN</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default InfoScreen;

these code give me an error below:

ERROR

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `App`.

This error is located at:
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:433)
    in BaseNavigationContainer (at NavigationContainer.tsx:132)
    in ThemeProvider (at NavigationContainer.tsx:131)
    in NavigationContainerInner (at App.js:7)
    in App (at withDevTools.js:18)
    in withDevTools(App) (at renderApplication.js:57)
    in RCTView (at View.js:116)
    in View (at AppContainer.js:127)
    in RCTView (at View.js:116)
    in View (at AppContainer.js:155)
    in AppContainer (at renderApplication.js:50)
    in main(RootComponent) (at renderApplication.js:67), js engine: hermes

I asked Gemini about this and it answered to check if ‘Stacks’ is exported correctly, so i checked it but it was okay (from what I’ve seen)

How does strict/non-strict mode works in javascript and does it have relevance in below code [duplicate]

var a = 'global'

var obj = {
    a: "foo",
    b: function() {
        console.log(this.a);   
    }
};

var c = obj.b;
obj.b();
c();

I’m getting the output as ‘foo’ and ‘undefined’. when I’m putting the same code on chatgpt it gives me output as ‘foo’ and ‘global’ explaining that when called ‘c()’, ‘this’ refers to the global/window context. Please explain to me what’s exactly happening behind the scenes and what is this concept exactly. Thank you

Sliding bar not aligned correctly

I have this sliding bar and I can get the thumbs and slide to align.
enter image description here

I am new to css and this is a pain gpt not working out.
I am not sure if it is conflicking css files or not. any help is appreciated.
End goal is to have pro on top and -7 on bottom of left thumb. The right am on top 54 on bottom of right thumb.

I tried to adjust all these fields and nothing seems to be right. the slide left/right and thumb left/right do not adjust like i think it should.

.container {
  height: 10vh;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.slider {
  position: relative;
  width: 200px;
  margin: 0 auto; /* Center the slider */
}

.slider__track,
.slider__range,
.slider__left-value,
.slider__right-value {
  position: absolute;
}

.slider__track,
.slider__range {
  border-radius: 3px;
  height: 5px;
}

.slider__track {
  background-color: #ced4da;
  width: 100%;
  z-index: 1;
}

.slider__range {
  background-color: #9fe5e1;
  z-index: 2;
}

.slider__left-value,
.slider__right-value {
  color: #dee2e6;
  font-size: 16px;
  margin-top: 20px;
}

.slider__left-value {
  left: 0%; /* Adjusted to align with the left edge of the slider */
}

.slider__right-value {
  right: 0%; /* Adjusted to align with the right edge of the slider */
}

.thumb {
  pointer-events: none;
  position: absolute;
  height: 0;
  width: 200px;
  outline: none;
}

.thumb--left {
  z-index: 3;
  left: 10; /* Adjusted to align with the left edge of the slider */
}

.thumb--right {
  z-index: 4;
  right: 100; /* Adjusted to align with the right edge of the slider */
}

.thumb::-webkit-slider-thumb {
  background-color: #f1f5f7;
  border: none;
  border-radius: 50%;
  box-shadow: 0 0 1px 1px #ced4da;
  cursor: pointer;
  height: 18px;
  width: 18px;
  margin-top: 4px;
  pointer-events: all;
  position: relative;
}

.thumb::-moz-range-thumb {
  background-color: #f1f5f7;
  border: none;
  border-radius: 50%;
  box-shadow: 0 0 1px 1px #ced4da;
  cursor: pointer;
  height: 18px;
  width: 18px;
  margin-top: 4px;
  pointer-events: all;
  position: relative;
}

.label-left {
  position: absolute;
  top: -30px; /* Adjusted to move the label above the thumb */
  left: 0;
}

.label-right {
  position: absolute;
  top: -30px; /* Adjusted to move the label above the thumb */
  right: 0;
}


/* For Chrome browsers */
.thumb::-webkit-slider-thumb {
  background-color: #f1f5f7;
  border: none;
  border-radius: 50%;
  box-shadow: 0 0 1px 1px #ced4da;
  cursor: pointer;
  height: 18px;
  width: 18px;
  margin-top: 4px;
  pointer-events: all;
  position: relative;
}

/* For Firefox browsers */
.thumb::-moz-range-thumb {
  background-color: #f1f5f7;
  border: none;
  border-radius: 50%;
  box-shadow: 0 0 1px 1px #ced4da;
  cursor: pointer;
  height: 18px;
  width: 18px;
  margin-top: 4px;
  pointer-events: all;
  position: relative;
}


/* List for data range */

datalist {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  writing-mode: vertical-lr;
}

option {
  padding: 0;
}

input[type="range"] {
  margin: 0;
}

Flashing JS text with hyperlink

I want flashing text to link to two different pages, and for the background colors to take over the entire page. I’m a novice, any help with JS is appreciated! Or maybe I don’t even need JS for this.

Hello!

I’m trying to make a page that flashes between a black bg and white text and a white bg with black text. I want each diff page to be a hyperlink to a separate page. I tried adapting the JS script I had but the flashing only worked the way I wanted to this way. the hyperlink only works with the black bg/white text and when it flashes to white it doesn’t take over the whole page like i want it to. i would also like it to not be static and move with the window configurations but the display properties im trying don’t seem to work with it. i’m really new to this so any help is greatly appreciated!

body {
background-color: black;
}

#blink {

font-family: Arial, Helvetica, sans-serif;
text-align: center;
align-items: normal;
display: inline-block;
font-size: 40rem;
transform: translateX(-50%) translateY(-50%);
color: black;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 50%;
background-color: white;
background-size: auto;
max-width: max-content;
}

#blink2 {

font-family: Arial, Helvetica, sans-serif;
text-align: center;
align-items: normal;
display: inline-block;
font-size: 40rem;
transform: translateX(-50%) translateY(-50%);
color: white;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 50%;
background-color: black;
background-size: auto;
max-width: fit-content;
}

a {
text-decoration: none;
cursor: pointer;
color: inherit;
}

h1 {
font-size: 25rem;
font-weight: 800;
}

    <body>
        <div class="white">
            <h1 id="blink"> <a href=page1.html> hello </a></h1>
       </div>
       <div class="black">
        <h1 id="blink2"> <a href=page2.html> hello </a></h1>
       </div>
        
        <script>
           

            timer();
            function timer(){
                let blink2 = document.getElementById("blink2");
                blink2.style.opacity = blink2.style.opacity == 0 ? 1 : 0;
                setTimeout(timer, 250);
            
            }

            

        </script>
    </body>

Cypress: Can all commands be overwritten at once?

Suppose I want to add a log at the beginning of each command and at the end of each command.
I want to be able to do that for all commands at once.
So, I tried:

// Define a function to intercept custom commands
const logCustomCommand = (originalFn) => {
    return function () {
        const commandName = originalFn.name;
        cy.log(`Custom Command: ${commandName} - Started`);

        // Execute the original custom command function
        const result = originalFn.apply(this, arguments);

        cy.log(`Custom Command: ${commandName} - Ended`);

        return result;
    };
};

// Intercept all custom commands to add logging
Cypress.Commands.overwrite('*', logCustomCommand);

But I got:

Cannot overwrite command for: *. An existing command does not exist by that name.

Can you advise please?

Handle file downloading in browser

I’ve some problems with downloading a file in the browser

My question is this:

How can we prevent downloads in a browser if the machine lacks enough memory? (JavaScript solution)

Is it possible to handle it with JavaScript or not?

Do you know any solution in JavaScript for this problem?

Error: TypeError: Cannot read properties of undefined (reading ‘text’)

I have a simple form that is supposed to be saved in applicant_need table in the database. my fields are (coursetype, course_need, c_name, total). but whenever I try to submit it doesnt work I get a server error 500 then it tells me “Cannot read properties of undefined (reading ‘text’)”
here’s my html

           <form id='addneed' class="intro-y box grid-cols-1 p-5">
         
                <div class="grid grid-cols-1 gap-4 row-gap-5 mt-5">
                                           
                    <div class="intro-y col-span-12 sm:col-span-4 px-2">

                        <div class="mb-2">Course Type</div>
                        <select name="coursetype" onchange="course_type_handler()" id="course_type_id" class="input w-full border flex-1 " required="">
                            <option">Choose an option</option>
                            <?php $x = 1;
                            if ($course_types->num_rows > 0) {
                                while ($rowm = $course_types->fetch_assoc()) { ?>
                                    <option value="<?php echo $rowm['id']; ?>"><?php echo $rowm['name']; ?></option>
                            <?php }
                            } ?>
                        </select>
                    </div>
            
            <div class="intro-y col-span-12 sm:col-span-4 px-2">
                        <div class="mb-2">Courses Need</div>
                        <select name='course_need' id="select_courses_id"  class="input w-full border flex-1 " required="">
                            <option >Choose an option</option>
            
                
                        </select>
                    </div>

    <div class="intro-y col-span-12 sm:col-span-4 px-2">

                        <label>Other</label>
<br>
<div>
                        <input type="radio" name='others'   onchange="radio_extra_handler()" class="input w-full border flex-1" >

                    </div>     

                    </div>  
<br>
<div class='intro-y col-span-12 sm:col-span-4 px-2' name='extra'  id="extra" style='display: none;'>
                        
                        <div class="mb-2">Course Name</div>
                        <input name='c_name'   type="text" class="input w-full border flex-1"  placeholder="Enter course name">
                   
                   
                        <div class="mb-2">Total</div>
                        <input name='total'  type="number"  class="input w-full border flex-1" placeholder="Enter number of nominees">
                    

 </div>                               

    
                    

                </div>

                <div style="display: flex; justify-content: center; margin-top: 20px;">
                    <button required type="submit" class=" button text-white bg-theme-1 shadow-md mr-2">Submit</button>
                </div>



            </div>


      
</form>


js script

<script>
function handleErrors(response) {
    if (response?.ok) {
  console.log('Use the response here!');
} else {
  console.log(`HTTP Response Code: ${response?.status}`)
}}
   // Function to handle form submission
        function handleSubmit(event) {
            // Prevent the default form submission behavior
            event.preventDefault();

            // Get form elements and their values
            const form = event.target;
            const formData = new FormData(form);
            
            // Convert FormData to an object
            const formObject = {};
            formData.forEach((value, key) => {
                formObject[key] = value;
            });

             // Send form data to a PHP file using the Fetch API
            fetch('server/add_needs_server.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formObject),
            })
         .then(handleErrors)
            .then(response =>  response.text())  // I believe the issue start here
            .then(data => {

        console.log(document.getElementById('course_type_id').value);
        console.log(document.getElementById('select_courses_id').value);

                if(data == "Inserted"){

            var coursename = document.querySelector('select[name=course_need]').value;
                    var message = document.querySelector('.message');
                    var response = document.querySelector('.response');

                    message.innerHTML = alert( 'your request has been submitted' );

                    message.classList.remove('failed');
                    message.classList.add('success');
                    response.classList.remove("hide");

                    document.getElementById("addneed").reset();


                } else {
                    var coursename = document.querySelector('select[name=course_need]').value;
                    var message = document.querySelector('.message');
                    var response = document.querySelector('.response');

                    message.innerHTML =  alert( 'Failed to upload' + coursename  );

                    message.classList.remove('success');
                    message.classList.add('failed');
                    response.classList.remove("hide");



                   
                                   }
                //console.log('Server response:', data);
                // You can handle the text response as needed, e.g., display it on the page
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        // Get the form element and add a submit event listener
        const myForm = document.getElementById('addneed');
        myForm.addEventListener('submit', handleSubmit);
    </script>


Aes-28-cbc encrypted video on server not playing React js decrypted video

the problem is that Aes-128-cbc encrypted video is transmitted by the server, I am decryto the data in react js application, all the data is decrypt, but the video is not playing, there is no error, I don’t know how to do it , i tried to use blob url which is also not useful

import React, { useEffect, useState, useRef } from "react";
import axios from "axios";
import CryptoJS from "crypto-js";
import videojs from "video.js";
import "video.js/dist/video-js.css";

const VideoPlayer = ({ src }) => {
  const videoRef = useRef(null);
  const [videoData, setVideoData] = useState(null);

  useEffect(() => {
    const key = "aSecretKey12345678";

    axios
      .get(src, { responseType: "arraybuffer" })
      .then((response) => {
        const encryptedData = new Uint8Array(response.data);
        const decryptedData = CryptoJS.AES.decrypt(
          { ciphertext: CryptoJS.lib.WordArray.create(encryptedData) },
          CryptoJS.enc.Utf8.parse(key),
          {
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
            iv: CryptoJS.enc.Hex.parse("0000000000000000"),
          }
        );
        setVideoData(new Uint8Array(decryptedData.words));
      })
      .catch((error) => console.error("Error fetching encrypted data:", error));
  }, [src]);

  useEffect(() => {
    if (videoData) {
      const player = videojs(videoRef.current, { controls: true, fluid: true });
      player.src({ src: videoData, type: "video/mp4" });
      return () => player.dispose();
    }
  }, [videoData]);

  console.log(videoData, videoRef);

  return (
    <div data-vjs-player>
      <video
        ref={videoRef}
        preload="metadata"
        playsInline
        className="video-js vjs-default-skin"
        controls
      />
    </div>
  );
};