Insert multiple text box values as a new entry in an SQL database

Currently, I am implementing a code snippet to incorporate additional text boxes within a form. The main purpose is to enable users to input multiple languages they are proficient in.

<script>
        jQuery(function($) {
            var i = 0;
            $('#theButton').click(addAnotherTextBox);
            function addAnotherTextBox() {
                $("#theForm").append("<br><label>Language <input type='text' name='language" + i + "' >");
            }
        });
    </script>


    <div id='theForm'></div>
    <form id="form" name="form">
        <input id='theButton' type='button' value='Add Medical History'>
        <input id="submit" onclick="myFunctionlanguage()" type="button" 
    value="Update" class="btn btn-primary btn-block" >
    </form>
    

The function triggered by the submit button essentially sends the collected data to a PHP file using AJAX, ensuring no need for page redirection or refresh for submission.

My current PHP code snippet:

$language = $_POST['language'];    
        if (isset($_POST['language1'])) {
            $sql_insert1 = "INSERT into `languages` (`language`,`cc`,`userid`)
    VALUES('$language','cc','$user->id')";
            mysql_query($sql_insert1) or die("Insertion Failed:" . mysql_error());
        }
    

However, it appears that the database isn't updating with each new language added through the text box.

Any insights or suggestions would be greatly appreciated.

Edit: - Despite trying out various examples provided below, the issue persists with adding entries into my database.

Is there a chance the problem lies within my onClick function implementation?

<script>
         function myFunctionlanguage() {
            var language = document.getElementById("location").value;       
            // Display success message upon data storage in database.
            var dataString = '&language1=' + language;
            if (location == '') {
                alert("Please enter a language!");
            } else {
                // Using AJAX to submit the form data.
                $.ajax({
                    type: "POST",
                    url: "includes/updatelanguage.php?userid=<?echo $user->id;?>",
                    data: dataString,
                    cache: false,
                    success: function(html) {
                        alert(html);
                        document.getElementById('close').click()
                        window.location.reload();
                    }   
            });
            }
            return false;
        }
    </script>
    

Answer №1

Give this a shot. I believe it could be beneficial for you.

<script>
jQuery(function($) {

$('#theButton').click(addNewTextField);
function addNewTextField() {
var i=parseInt($("#max").val());
i=i+1;
$("#max").val(i);
$("#form").prepend("<br><label>Language <input type='text' name='language" + i + "' >");
}
});

</script>

<form id="form" name="form">
<input type="hidden" name='max' id="max" value="0"/>
<input id='theButton' type='button' value='Add New Field'>
<input id="submit" onclick="updateLanguages()" type="button" 
value="Update" class="btn btn-primary btn-block" ></form>



$max=$_POST['max'];

for($i=1;$i<=$max;$i++){

$language = $_POST['language'.$i];


if (isset($_POST['language'.$i])) {

$sql_insert1 = "INSERT into `languages`
(`language`,`cc`,`userid`)
VALUES('$language','cc','$user->id')";


mysql_query($sql_insert1) or die("Insertion Failed:" . mysql_error());
}

}

Answer №2

If you want to simplify the process of assigning names to input boxes dynamically, consider naming them all as languages[]. This way, you can submit all input boxes with the name languages[] as a single variable in the $POST array.

Here is an example:

<script>
jQuery(function($) {
    $('#theButton').click(addAnotherTextBox);
    function addAnotherTextBox() {
        $("#theForm").append("<br><label>Language <input type='text' name='languages[]' >");
    }
});

</script>

<div id='theForm'></div>
<form id="form" name="form">
<input id='theButton' type='button' value='Add Medical History'>
<input id="submit" onclick="myFunctionlanguage()" type='button' 
value="Update" class="btn btn-primary btn-block" ></form>

For handling this data in PHP, use the following code:

if (isset($_POST['languages'])) {
    foreach ($_POST['languages'] as $language) {
        $sql_insert1 = "INSERT into `languages` (`language`,`cc`,`userid`) VALUES ('$language','cc','$user->id')";

        mysql_query($sql_insert1) or die("Insertion Failed:" . mysql_error());
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A distinct handler function designed for a dynamically generated form

I have 3 MaterialUI TextFields that are rendered n number of times based on user input (stored in a variable named groupMembersCount) in a functional ReactJS component using the useState hook: const [groupDetails, setGroupDetails] = React.useState([ { ...

Differences in weekend start and end days vary across cultures

Looking for a solution to determine the weekend days per culture code in Typescript/Javascript? While most countries have weekends on Sat-Sun, there are exceptions like Mexico (only Sunday) and some middle-eastern countries (Fri-Sat). It would be helpful ...

The mouseenter event in jQuery is failing to trigger

I'm encountering an issue with the mouseenter event on a div section of my webpage. I am attempting to alter the background color of this div when the mouse enters, but it seems to be disregarded. This is the basic HTML code: <div id="services" c ...

jQuery struggles to locate the active class within the Bootstrap slider

Want to make some changes to the Bootstrap slider? Here is the HTML Code and jQuery: <div id="carousel-slider2" class="carousel slide bs-docs-carousel-example"> <ol class="carousel-indicators"> & ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

Ways to separate a string based on changing values in Javascript

Given this unmodifiable string: "AAACCDEEB" I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so: [['A','A','A'], ['C','C'], [ ...

The Canvas element inside a Bootstrap modal is returning inaccurate mouse coordinates

I am currently troubleshooting an issue with a HTML5 canvas inside a Bootstrap modal. The canvas is designed to be a selection game where objects can be selected and manipulated. Everything works fine in the center of the 600x600px canvas, but there is an ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

JQuery selector is successfully working while vanilla JavaScript is not functioning as expected

This problem is unique because I am experiencing issues with querySelector and querySelectorAll in my JavaScript code. While JQuery works fine, vanilla JS does not work as expected. I would appreciate any insights on why this might be happening. Thank you ...

Struggling to retrieve a response from the ListUsers endpoint in OKTA using the okta-sdk-nodejs Client's listUsers function

Code snippet: async fetchUsersByEmail(email) { try { return await Promise.all([ oktaClient.listUsers({ search: email, }), ]).then((response) => { console.log(response); }); } catch (error) { ...

When hosted, OpenCart encounters a JavaScript error stating that the property "document" cannot be read because it is null

After successfully running opencart on my local machine, I encountered some errors upon uploading it to the hosting/server. The specific error message is as follows: Uncaught TypeError: Cannot read property 'document' of null f.each.contents @ j ...

Display div - conceal div - pause for 15 minutes - continue the cycle

I have a challenging JavaScript task that I've been struggling with for quite some time. The goal is to display a div for 5 seconds, hide it, wait for 15 minutes, then show it again for another 5 seconds, and continue this process in an infinite loop. ...

Posting letters using Lumen

I have researched and tried various methods for sending mail using Lumen. Despite following multiple suggestions, I continue to encounter the following error: (1/1) FatalThrowableError Type error: Too few arguments to function Illuminate\Support&bsol ...

Decision on how to exchange data (JSON or traditional method)

In my current project, I am developing a user-friendly application that allows users to design their own web interface using various tools. Users can create drag-and-drop elements and I need to store this data in a database once they finalize their desig ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

Display an icon button when a user edits the text in a text field, and make it disappear once clicked on

Figuring out how to incorporate a v-text-area with an added button (icon) that only appears when the text within the text area is edited, and disappears once it is clicked on, has proven to be quite challenging. Below is a simplified version of my code to ...

Dynamically filling the text area by fetching data from the database when a dropdown option is selected

There is a table called 'vendortable' with attributes 'vendorid', 'vendorname', and 'vendoraddress'. I am struggling to populate the data from the database into a textarea using jQuery and AJAX. Calling all amateu ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...