How to display mysql data through javascript in dynamic form field - javascript

I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>

Related

Get value of dynamically added input

I have a form with possibility to add additional input fields. I get those values with $_POST['input_name'] and can insert to db / send mail. The problem is that I want those fields and values be displayed when page is refreshed if there was errors left, but I can't get values of dynamically added inputs in Jquery code - just the first one which is added statically. Is it possible to get those values in jQuery code?
My HTML
<div class="field_wrapper">
<div>
<input type="text" name="input_name[]" class="form-control" placeholder="Enter name" value="<?php if(isset($_POST['input_name'])) echo $_POST['input_name'][0];?>"/>
</div>
</div>
My jQuery
jQuery(document).ready(function(){
console.log(jQuery('#contactForm').serialize()); <- getting first value
var vals = jQuery("input[name='input_name[]']").map(function(){ return this.value}).get();
console.log(vals); <- getting first value
var maxField = 10; //Input fields increment limitation
var addButton = jQuery('.add_button'); //Add button selector
var wrapper = jQuery('.field_wrapper'); //Input field wrapper
var x = 1; //Initial field counter is 1
//Once add button is clicked
jQuery(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
var fieldHTML = '<div><input type="text" name="input_name[]" class="form-control" placeholder="Enter name"/> \
</div>';
x++; //Increment field counter
jQuery(fieldHTML).appendTo(wrapper); //Add field html
}
});
//Once remove button is clicked
jQuery(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
jQuery(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});

Creating array of text boxes dynamically using javascript and accessing text box names from php to pass data to mysql

I have a simple form with a text box. The user is able to add more text boxes by clicking a button.
I am dynamically creating the text boxes using javascript, however I have 2 issues:
1- I am not sure how to access the text boxes from the PHP file.
2- Whenever I click +addmore button on my html page it creates new text boxes but it clears the value of the previous ones.
Below is the html part:
<input type="text" id="program" name="program[]"> //Initital text box
<div><a onclick="CreateTxt()">+Add More</a></div> //Add more button
<input type="hidden" id="hid" name="hid" value="0">
<input type="submit" value="Next" name="submit1">
Below is javascript part:
var i = 1; // Global counter
var hidden_field;
function CreateTxt(){
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
y.setAttribute("Name", "program" + i); //I am sure this is not working for the array names
y.setAttribute("class", "form-control");
document.getElementById('userdata1').innerHTML +=
'<label for="program"><br />Program</label>';
document.getElementById('userdata1').appendChild(y);
hidden_field = document.getElementById("hid").value = i; //passing the number of created textboxes
i++;
}
Below is PHP part:
<?php
session_start();
include('connection.php');
$id = $_SESSION['id'];
$i = $_POST['hid'];
if(isset($_POST['submit1'])){
if($i > 0){ //It means more than one text box exist
$program = [];
for ($j = 0; $j <= $i; $j++){
$program[$j] = $_POST['program'][$j];
$sql = $db->prepare ("UPDATE user SET program = ?, WHERE id = ? ");
$sql->bind_param("ss", $program[$j], $id);
$sql->execute();
}
}
}
?>

update ID automatically

i need a help here. i want to automatically update my iD whenever i submit my data. let me explain a bit more.
Here is the scenario when i submit a form the id of my page needs to update automatically. for example if i enter id 3 and submit the html form, when i open the form again it must check the Id from database and show the next id.
This means if the last data i entered has id 3 it then show me id 4 automatically when i refresh the page and want to submit new data
how can i add ID validation query in that code
need your expert advises.. thanks alot!!!
Html
<form action="survey-data-entry.php" name="1st-form" id="form-control" method="post" >
<label>Id.</label>
<input type="text" class="form-control" placeholder=" 0451211315" name="ID" id="id" required>
php
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
$sql= "INSERT INTO phpstartup (ID, )
VALUES('$ID') ";
if(!mysql_query($sql))
{
die('caution' . mysql_error());
}
echo"1 record added";
}
You need to get the maximum of id + 1 from the query to use it for your next submission.
$rslt = mysql_query('SELECT MAX(ID) + 1 as nextId FROM phpstartup');
$row = mysql_fetch_assoc($rslt);
$nextId = $row['nextId'];
Now you can use the variable $nextId in your forms for re submission.

How to use Javascript to validate dynamically generated PHP form?

I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?
This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
Then, the use of jQuery saves pain...
Within your submit script:
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
Add this jQuery lib call in your head:
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
EDIT - See comments
Function validate should be this:
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}
getElementById returns the first element matching the selector. If you just want to verify that any of them were checked, you could do something like:
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;

Creating form fields from user input

I found a code that creates some form fields based on a number chose by the user.
<script type='text/javascript'>
function addFields(){
var number = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Member " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "Member["+i+"]";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
</script>
<input type="text" id="member" name="member" value="">Number of Members: <br />
<input type="button" id="enterdetails" value = "Enter Details"onclick="addFields()">
<div id="container"/>
</div>
It works fine. But I want to create elements with names/values imported from a database. In php I do like this:
<SELECT name='smth'>
<OPTION value=""></OPTION>
<?php
$qry = $dbh->query("select * FROM table");
while ($a = $qry->fetch(PDO::FETCH_ASSOC)) {
$smth = $a['smth'];
echo "<OPTION value='$smth'>".$smth."</OPTION>";
}
?>
</SELECT>
Need help on how to do it in javascript.
You cant get database fields with javascript. You must use php or something like this.
Maybe this can help you. Here is the link. choose your database and table, and select your field names, and choose field's type of form (text area, text, radio button groups, etc) and push create. You will have a bootstrap designed form and php insert code writed with medoo (medoo.in).
you can use this. create your database first and make form automaticly. Copy code and paste to your pages.
Also i offer you to use meddo to connect and use sql with it. There is a sample in that link form.min.php, includes your database and user and pass information.

Categories