I am having problem submit form without reload using ajax

I have some problem with my code. when I enter the correct username and password it fails to redirect to index.php.

i want to do php file side navigation instead of js side navigation using window.location.href

login.php:

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['btn-login'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];


        if (User::authenticate($conn, $username, $password)) {
            // Thực hiện sesison
            Auth::login();
            // redirect("index.php");
            echo "success";
            header("Location: index.php");
        } else {
            echo "<script>alert('Vui lòng đăng nhập lại');</script>";
        }
    }
    ?>

main.js:

   $("form").on("submit", function (event) {
        event.preventDefault(); // Prevent the form from being submitted normally

        if (validateLoginForm()) {
            // Use AJAX to submit the form
            $.ajax({
                url: "login.php", // URL to the PHP file that will handle the AJAX request
                type: "POST",
                data: $(this).serialize(), // Serialize form data for submission
                success: function (response) {
                    // Handle success
                    if (response === "success") {
                        window.location.href = "login.php";
                    } else {
                        alert("Login failed. Please try again."); // Show error message
                    }
                },
                error: function (error) {
                    // Handle error
                    alert("An error occurred. Please try again."); // Show error message
                },
            });
        }
    });

Thank you for your help <3

Next Js “No overload matches this call”

i currently using nextjs 14, i having a problem on onSuccess section keep showing no overload matches this call, need help and guide on this.

the program language i using.

npm: '10.4.0',
  node: '21.6.1',
  acorn: '8.11.3',
  ada: '2.7.4',
  ares: '1.20.1',
  base64: '0.5.1',
  brotli: '1.1.0',
  cjs_module_lexer: '1.2.2',
  cldr: '44.0',
  icu: '74.1',
  llhttp: '9.1.3',
  modules: '120',
  napi: '9',
  nghttp2: '1.58.0',
  nghttp3: '0.7.0',
  ngtcp2: '0.8.1',
  openssl: '3.0.12+quic',
  simdjson: '3.6.3',
  simdutf: '4.0.8',
  tz: '2023c',
  undici: '5.28.2',
  unicode: '15.1',
  uv: '1.47.0',
  uvwasi: '0.0.19',
  v8: '11.8.172.17-node.19',
  zlib: '1.3.0.1-motley-40e35a7'

enter image description here

import { useRouter, useSearchParams } from "next/navigation"
import { trpc } from "../_trpc/client"

const Page = async () => {
  const router = useRouter()

  const searchParams = useSearchParams()
  const origin = searchParams.get('origin')


  const {data, isLoading} = trpc.authCallback.useQuery(undefined, {
    onSuccess: ({success}) => {      <==== error here
      if(success) {
        router.push(origin ? `/${origin}` : '/dashboard')
      }
    }
  })
  

}

export default Page

the error code

No overload matches this call.
  Overload 1 of 2, '(input: void, opts: DefinedUseTRPCQueryOptions<{ success: boolean; }, { success: boolean; }, TRPCClientErrorLike<{ errorShape: DefaultErrorShape; transformer: false; }>, { ...; }>): DefinedUseTRPCQueryResult<...>', gave the following error.
    Object literal may only specify known properties, and 'onSuccess' does not exist in type 'DefinedUseTRPCQueryOptions<{ success: boolean; }, { success: boolean; }, TRPCClientErrorLike<{ errorShape: DefaultErrorShape; transformer: false; }>, { success: boolean; }>'.
  Overload 2 of 2, '(input: void, opts?: UseTRPCQueryOptions<{ success: boolean; }, { success: boolean; }, TRPCClientErrorLike<{ input: void; output: { success: boolean; }; transformer: false; errorShape: DefaultErrorShape; }>, { ...; }> | undefined): UseTRPCQueryResult<...>', gave the following error.
    Object literal may only specify known properties, and 'onSuccess' does not exist in type 'UseTRPCQueryOptions<{ success: boolean; }, { success: boolean; }, TRPCClientErrorLike<{ input: void; output: { success: boolean; }; transformer: false; errorShape: DefaultErrorShape; }>, { ...; }>'.ts(2769)

i expect to solve only “onSuccess: ({success})” error section.

Finding elements in Flask + Jinja

I am trying to create an flask app that uses Jinja templating. I have a navbar that contains links with the class name ‘nav-link’. They are in base.html. I dynamically create index.html. Later I try to acess the links in script.js:

const navLinks = document.querySelectorAll('.nav-link');

I log the navLinks into the console and this is what I get:

NodeList

Is there a way to get dynamically created elements? A way to add event listenrs onto them? Thank you in advance.

What’s the optimal approach to iterate over a large dataset in JavaScript using artificial intelligence? [closed]

I’m working on a project where I need to iterate over a large dataset stored in an array in JavaScript. I want to ensure that my iteration approach is optimal in terms of speed and efficiency. How can I leverage artificial intelligence to optimize the iteration process over this array? Are there any machine learning techniques or algorithms that can help improve the performance of my code? I appreciate any guidance or practical examples that can help me effectively apply AI in this context. Thank you!

Will React Native input’s text available in a RAM memory dump be garbage collected at some point? How long would that take?

Long story short, I need to confirm that text written inside some inputs would eventually be cleared from the RAM memory so that it can’t be accessed through a memory dump. From what I understand, since I’m using a high level programming language, I can’t manually manipulate the memory and rely entirely on the garbage collector.

I am using frida server and fridump to create the RAM dump and I’m testing on Android right now.

Now I am wondering how long must I wait before the strings in the memory get garbage collected? I am creating the memory dump after the Stack that contains the input fields gets unmounted, so I imagine that they should be eligible for deletion at that point.

That being said, I’ve waited a long time inbetween dumps while the application is running, and it seems that the strings are not being removed from memory.

Streaming audio from a PyAudio stream to be played on a webpage in Javascript

I’m trying to take an audio stream from my computer using PyAudio (specifically the pyaudiowpatch fork), stream that audio data over a websocket (using the websockets library, and play it on a web page using javascript. To do this, I have the following Python code on the server side:

import pyaudiowpatch as pyaudio

import asyncio
from websockets.server import serve


CHUNK_SIZE = 512


async def main():
    with pyaudio.PyAudio() as p:
        # 23 is the index of the device i'm trying to get the data from
        audio_device = p.get_device_info_by_index(23)
        with p.open(
            format=pyaudio.paInt16,
            channels=audio_device["maxInputChannels"],
            rate=int(audio_device["defaultSampleRate"]),
            frames_per_buffer=CHUNK_SIZE,
            input=True,
            input_device_index=audio_device["index"]
        ) as stream:
            async def handler(ws):
                print(f"Connection from {ws}")
                while stream.is_active():
                    chunk = stream.read(CHUNK_SIZE)
                    await ws.send(chunk)
                    print(f"Sent chunk to {ws}")
                print(f"Closing connection to {ws}")

            async with serve(handler, host="localhost", port=8081):
                print("Listening...")
                await asyncio.Future()

asyncio.run(main())

This code works fine, and when I make a connection from the web page, the data is sent over just fine. My client-side js is as follows:

const host = "ws://localhost:8081"
const ws = new WebSocket(host, "testProtocol")
const audioContext = new AudioContext()
const source = audioContext.createBufferSource()

source.connect(audioContext.destination)

document.getElementById("playButton").onclick = () => {
    source.start()
}

ws.onmessage = (event) => {
    event.data.arrayBuffer().then(data => {
        audioContext.decodeAudioData(data, (buffer) => {
            source.buffer = buffer
        })
    })
}

The idea is that the ws client receives the data as a blob, and then turns it into an ArrayBuffer to be played by the Web Audio API. However, I get the following error from the js: Uncaught (in promise) DOMException: The buffer passed to decodeAudioData contains an unknown content type. Clearly this means that the audio data I am passing is not in a format that the Web Audio API can understand.

What is the correct way to play the audio being streamed over to the web page?

What is the right way to pass component props in Vue3 tests that use Vuetify components?

I am trying to write a basic unit test for a component called CompanyBioPanel. Here is a simplified version of the component:

// template

    <v-card-text>
      <v-tabs v-model="companyTabs">
        <v-tab value="generalData">
          <h2>Details</h2>
        </v-tab>
        <v-tab value="companyConfiguration">
          <h2>Company Configuration</h2>
        </v-tab>
      </v-tabs>
      <v-divider />
      <v-window
        v-if="companyData.company_id != null"
        v-model="companyTabs"
      >
        <v-window-item value="generalData">
          <v-list>
            <company-data-item
              v-for="item in generalData"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </v-list>
        </v-window-item>
        <v-window-item value="companyConfiguration">
          <v-list>
            <company-data-item
              v-for="item in companyConfiguration"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </v-list>
        </v-window-item>
      </v-window>
    </v-card-text>

// script
import type { Company } from './types'
import {
  computed,
  toRefs,
  ref,
  type ComputedRef
} from 'vue'
import CompanyDataItem from './CompanyDataItem.vue'

const props = defineProps<{ companyData: { [key: string]: string } }>()

const companyTabs = ref(null)

const { companyData } = toRefs(props)

const companyIdOrNull = computed(() => {
  return companyData.value?.company_id ?? null
})

const generalData: ComputedRef<CompanyDataItemProps[]> = computed(() => {
  if (companyData.value == null) {
    return []
  }

  return [
    {
      label: 'Name',
      value: companyData.value.name,
      fieldName: 'name',
      isEditable: true
    }
  ]
})

In my test, I would like to assert that when I pass the companyData object as a prop to my component, it renders the company-data-item component.

Here is my test:

import { mount } from '@vue/test-utils'
import { h } from 'vue'
import { VApp } from 'vuetify/components'
import CompanyBioPanel from './CompanyBioPanel.vue'

it('renders the company bio panel', async () => {
  const companyData = {
    company_id: 'abc',
    name: 'Test Company'
  }

  const wrapper = mount(VApp, { slots: { default: h(CompanyBioPanel, { props: { companyData } }) } })

  expect(wrapper.exists()).toBe(true)
  const html = wrapper.html()
  expect(html).toContain('Test Company')

  const companyName = wrapper.find('h1')
  expect(companyName.text()).toBe('Test Company')

  const companyDataItems = wrapper.findAllComponents({ name: 'company-data-item' })
  expect(companyDataItems.length).toBe(1)
})

This is a simple test asserting that child components are generated from data passed as props. However, I get the following error when I attempt to run my test:

⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/components/company-view/company-bio-panel/CompanyBioPanel.test.ts > renders the company bio panel
TypeError: Cannot read properties of undefined (reading 'company_id')
 ❯ src/components/company-view/company-bio-panel/CompanyBioPanel.vue:45:27
     43|       <v-divider />
     44|       <v-window
     45|         v-if="companyData.company_id != null"
       |                           ^
     46|         v-model="companyTabs"
     47|       >

This doesn’t make sense to me, because I am passing the props in my test, so how could companyData be undefined?

I’ve also tried modifying the way I pass props to be like this:

  const wrapper = mount(VApp, { slots: { default: h(CompanyBioPanel, { companyData }) } })

but that leads to an even stranger error:

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

Vitest caught 1 unhandled error during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Rejection ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
TypeError: Cannot create property '_destroyed' on number '-1'
 ❯ clearImmediate node:timers:325:24
 ❯ GlobalWindow.cancelAnimationFrame ../../node_modules/happy-dom/src/window/Window.ts:921:10
 ❯ node_modules/vuetify/lib/components/VSlideGroup/VSlideGroup.mjs:104:9
 ❯ callWithErrorHandling ../../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:156:18
 ❯ callWithAsyncErrorHandling ../../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:164:17
 ❯ job ../../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:1831:9
 ❯ flushPreFlushCbs ../../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:308:7
 ❯ updateComponentPreRender ../../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5876:5
 ❯ ReactiveEffect.componentUpdateFn [as fn] ../../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5794:11
 ❯ ReactiveEffect.run ../../node_modules/@vue/reactivity/dist/reactivity.cjs.js:182:19

How to properly configure element positions with Tailwind CSS

I’m working on a Next.js project using Tailwind CSS for styling. I need to position elements horizontally from the center of the page so that they don’t shift or overlap each other, with the possibility of vertical scrolling. I would like to find a solution other than using large indents, like mt-96. How can this layout be achieved in Tailwind CSS?

The code I write pushes the text “MY PROJECTS” outside the page and I don’t know how to fix it. Code:

function Main() {
    return (
        <div className = "flex flex-col text-center ">
            <m.div
                initial={{ opacity: 0, x: -100 }}
                animate={{ opacity: 1, x: 0 }}
                className="flex flex-row"
                transition={{ duration: 0.1, ease: "easeOut" }}>
                <div className="navbar-container">
                    <NavbarM />
                </div>
                <div className="flex md:flex-row justify-start text-left w-full mx-auto">
                    <div>

                        <p className='uppercase text-sm tracking-widest text-[#ffffffb7] text-left p-3 ml-14 '>Let's work together</p>

                        <h1 className='text-6xl text-[#B1BDC9] text-center sm:hidden font-face-my69'>
                            MY <span className="text-[#d2d2d2] whitespace-nowrap">PROJECTS.</span>
                        </h1>

                    </div>
                </div>

            </m.div>
            
            {/* Project element */}

            <div className="w-full flex flex-col">

                <ProjectItems
                    title_1='Drone-Face-Tracking'
                    title_2='PyTorch'
                    backgraundImg={Tello}
                />


                <ProjectItems
                    title_1='Unity Game' 
                    title_2='Welcome to my Unity game project'
                    backgraundImg={Unity}
                />

                <ProjectItems
                    title_1='Bagging Algorithm' 
                    title_2='Sklearn'
                    backgraundImg={Bagging_algoritm}
                />

            </div>
        </div>
    );
};

export default Main;

Typescript: Declare interface with all optional indices accessible by “indexing into”

I want to create an interface that has all the CSS properties as possible indices but it could have none, and I want to “index into” it.

This would be ideal but it is not working:

declare interface ICSSStyles {
  [name: string]: ICSSStyle;
  fontStyle?: ICSSStyle;
  alignContent?: ICSSStyle;
  color?: ICSSStyle;
}

declare interface ICSSStyle {
  value: any;
  weight: number;
}

let obj: ICSSStyles = {
  fontStyle: {value: "italic", weight: 1000}, 
  color: {value: "red", weight: 100}
}

for (let key in obj) {
  console.log(obj[key]);
}

The error I get when I hover over alignContent is: “Property ‘alignContent’ of type ‘ICSSStyle | undefined’ is not assignable to ‘string’ index type ‘ICSSStyle’.”

All of the indices must be optional because it’s possible that any will be present or none. I also need to get to them through a string index, like the for…in loop above.

I have found similar questions Here and Here, but if they have given me the answer, I have missed it.

How can I set this up?

PHP & JavaScript says user’s email already exists in the database upon submit when its not

i’m trying to learn some php and after creating a php script that checks for email duplicates in the database I’m getting en error message that says the email entered is already in the database when its clrearly not, and I’m using AJAX to check the form and output some messages in the form itself, can you guys help me ? tried everything and it still says user email exists when its not

PHP CODE (removed the db info):

<?php
// Database connection
$servername = "";
$username = "";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Form submission handling
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form data
    $email = trim($_POST['email']);
    $username = $_POST['username'];
    $password = $_POST['password'];
    $phone = $_POST['phone'];

    // Check if email already exists in the database
    $checkDuplicateEmailQuery = $conn->prepare("SELECT * FROM users WHERE email = ?");
    $checkDuplicateEmailQuery->bind_param('s', $email);
    $checkDuplicateEmailQuery->execute();
    $result = $checkDuplicateEmailQuery->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(array('error' => 'The email address already exists. Please use a different email.'));
    } else {
        // Hash the password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        // Insert user data into the database with hashed password using prepared statement
        $insertQuery = $conn->prepare("INSERT INTO users (username, password, phone, email) VALUES (?, ?, ?, ?)");
        $insertQuery->bind_param("ssss", $username, $hashedPassword, $phone, $email);

        if ($insertQuery->execute()) {
            echo json_encode(array('message' => 'User created successfully'));
        } else {
            echo json_encode(array('error' => 'Error in inserting user data'));
        }
    }

    // Close database connection
    $conn->close();
}

the JS code:

document.getElementById('registrationForm').addEventListener('submit', function(event) {
    event.preventDefault();

    var email = document.getElementById('email').value.trim(); // Trim the email input to remove leading/trailing spaces
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    var phone = document.getElementById('phone').value;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'api/register.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                if (response.hasOwnProperty('error')) {
                    document.getElementById('error-message').innerText = response.error;
                } else if (response.hasOwnProperty('message')) {
                    alert(response.message);
                    // Additional actions for success case      
                } else {
                    alert('Unexpected response from server');
                }
            } else {
                alert('Error: ' + xhr.status);
            }
        }
    };

    var formData = 'email=' + encodeURIComponent(email) + '&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password) + '&phone=' + encodeURIComponent(phone);

    xhr.send(formData);
});

I have tried to remove the js itself and it works as intended but when I add the js back it breaks again I CANNOT understand why…

Why is this Javascript Function Call is not working in HTML? [closed]

Im writing code for a zodaic sign calculator and im not sure what the problem is but the answer is not being calculated, dont know if its because the function is not being called? Any help would be great

Javascript

}
function Output() {
 const year = document.getElementById("year").value;
 if (year === "Make year 4 Digets and Positive!") {
    CZ = "Fix Year";
 }
 document.getElementById("result").innerHTML = NewZodiac;
}
    <h2> Step 4: Click the Button</h2>
    
 
 
    <h2> Output</h2>
    <h3> New Zodiac Sign:</h3>
    
 

Delaying code rendering in Monaco diffEditor until diff calculation is complete

I am currently developing with Monaco’s diffEditor and I have come across a problem. When I create the diffEditor and call setModel, the diff is calculated based on the diffAlgorithm. In cases where the calculation time is long, the code in the editor is displayed first, and then the diff is displayed quite a bit later.

This could potentially confuse users as they have no way to know the time it takes for the diff to be calculated. They might even assume it to be an error. Therefore, I want to prevent the code from being displayed until the diff is calculated. I’d prefer to show a loading or progress bar during this time. Is there a way to achieve this?

Below is the code I am using to create the editor:

function GitCommitDlg*displayDiffView(info) {
    const fileName = info[0].title;

    theApp.gitManager.getDiff(fileName, (originalCode, modifiedCode) => {
        if (this.diffEditor) this.diffEditor.dispose();
    
        this.diffEditor = monaco.editor.createDiffEditor(this.diffContentView.element, {
            originalEditable: false,    // for left pane
            readOnly: true,             // for right pane
            enableSplitViewResizing: true,
            automaticLayout: true,
        });
    
        const originalModel = this.createMonacoModel(originalCode);
        const modifiedModel = this.createMonacoModel(modifiedCode);
    
        this.diffEditor.setModel({
            original: originalModel,
            modified: modifiedModel,
        });
    });
};

Change color of a function return JavaScript

In JavaScript
How can i change the colors of a text from a html text replaced by function parameter, directly from an external condition.
If i have an input that must be filled with a message, as a parameter of my function, then it replaces a text from the html.
i don’t know how to directly apply styles to the function.
Then i want two conditions to determinate the color of the message:
example:
condition 1 = true => green
condition 2 = true => red
How can i do that?
i can’t find a solution

How can I write a function that returns the objects in an array that have the two same property values?

Let’s say I have the following object:

const myObjects = [
    { name: "Alice", age: 30 },
    { name: "Bob", age: 25 },
    { name: "Alice", age: 30 },
    { name: "David", age: 25 }
];

I wrote the following function, so that the objects with the specified same props are returned in a new array:

function findObjectsWithSameProperties(objects, property1, property2) {
  // Create an empty array to store the results
  const matchingObjects = [];

  // Loop through each object in the array
  for (const obj of objects) {
    // Check if the object has both specified properties
    if (obj.hasOwnProperty(property1) && obj.hasOwnProperty(property2)) {
      // Check if the values of the specified properties are the same
      if (obj[property1] === obj[property2]) {
        // If they are, add the object to the results array
        matchingObjects.push(obj);
      }
    }
  }

  // Return the array of matching objects
  return matchingObjects;
}

However, my function isn’t returning anything when I expect it to return this:

[
    { name: "Alice", age: 30 },
    { name: "Alice", age: 30 },
];

Here’s how I’m calling the function: findObjectsWithSameProperties(myObjects, "age", "name");

Does anyone know what I’m doing wrong? Here’s a CodePen link: https://codepen.io/obliviga/pen/WNWNbMX?editors=0011