store dynamically created elements' value to database PHP MySql - javascript

newbie here.. I have a form where a user can click a button to add an input text element. I did this using JQuery.
What I want to accomplish is to save the values of the dynamically added textboxes to the database.
I have the following code below but storing to database is not working as it should be.
HTML Code:
<form id='myform' action='save.php' method='POST'>
<input type='button' value='Add Another User' id='auser'>
<input type='text' id='user' name='user'>
<input type='submit' value='Save User/s' name='submit'>
</form>
JQUERY code:
$('#auser').on('click', function() {
$('#myform').append("<input type='text' id='user' name='user'>");
});
PHP Code(success.php):
<?php
if (isset($_POST['submit'])){
$username = $_POST['user'];
$qry=$con->prepare('INSERT INTO userslist (username) VALUES (?)')
$qry->execute(array($username));
}
?>
thanks in advance for any help..

Aside from the typos mentioned in the comments above, you'll need to create a grouping name in your HTML form inputs on the user field. So you'll need to change it into:
<input type='text' class='user' name='user[]'>
// ^
Sidenote: I'd suggest just use a class instead.
After that, so you'll also change the JS that spawns multiple textbox fields:
$('#auser').on('click', function() {
$("<input typ='text' id='class' name='user[]'><br/>").insertBefore('.user').last();
// ^ need to add those too
});
After that, when you submit the page (the PHP), you'd get an array instead of one value:
$usernames = $_POST['user']; // this is now an array of usernames
Then in your query, now that its dynamic, you'll need to create the query dynamically too using those PDO placeholders. In the end you'll need these:
if(isset($_POST['submit'])) {
$usernames = $_POST['user'];
$query = 'INSERT INTO userslist (username) VALUES '; // base query
// dynamically build placeholders
$placeholders = implode(',', array_fill(0, count($usernames), '(?)'));
$final_query = $query . $placeholders;
// the final query would look like
// INSERT INTO userslist (username) VALUES (?),(?),(?)
$qry = $con->prepare($final_query); // prepare
$qry->execute($usernames); // bind the user names
}
Sample Demo

Change to this:
$('#auser').on('click', function() {
$('#myform').append("<input type='text' class='user' name='user'>");
}); //-------------------------------------^^^^^^^---change the attribute to class
What happens with ids is when browser finds an element with id then it does not look for next element in the page.
So to overcome this issue you should either use unique ids for every element or just change the attribute to class as suggested in the answer.

Related

How to change a HTML table data value after form submission

I have a form.
<form action="form.php" method="POST" name="form1" id="f1">
On this form is an input for a name.
<input type="text" class="form-control" id="n1" placeholder="Name" required>
The user inputs their name and clicks submit, the form.php then kicks in and this name is emailed to an email address.
$name = $_POST['n1'];
If this is successful the user is redirected to another page via;
header("Location: /anotherpage.html");
Up to this point everything works fine.
On this page is a HTML table with a table data cell;
<td id="table1"></td>
Q. What I am trying to do is when the user is redirected to this page the name they submit appears in the tables data cell.
I have tried a couple of things with no success.
On the HTML side;
value="<?php echo $name;?>" & value="<?php echo $_POST['n1'];?>" within the td tag.
<?php echo $name;?> & <?php echo $_POST['n1'];?> between the td tags.
& on the PHP side after the redirect header;
getElementById('n1').value = $name;
getElementById('n1').value = $_POST['n1'];
Is there a way of doing this?
Look forward to hearing from anyone
Kind Regards
You can send the name over the url using the header using PHP...
// check the submission of your form using the name set in the submit button...
if(isset($_POST['submit'])){
// DO NOT SKIP ON SANITIZING YOUR INPUTS!!!!!
// This example is very basic, I am not showing how to sanitize inputs
$fname = filter_var(strip_tags($_POST['fname'], FILTER_SANITIZE_STRING));
$lname = filter_var(strip_tags($_POST['lname'], FILTER_SANITIZE_STRING));
// do your email stuff
// after you have done all your other code, send the name
// key/value pair over the url using the header...
header("Location: someotherpage.html?fname=".fname ."&lname=".lname);
}
Once you have sent the values over the url to the someotherpage.html page you can use URLSearchParams to search the url for key parameters to get their paired value/s. window.location.search => The query string portion of the URL. This includes the question mark, and everything following. Use .get() to get the url's parameters using their key. Then you can assign them using javascript with the dataset attribute => element.dataset.fname = firstName.
let parameters = new URLSearchParams(window.location.search);
let firstName = parameters.get('fname');
let lastName = parameters.get('lname');
let div = document.getElementById('data');
div.dataset.fname = `${firstName} ${lastName}`;
Returns the following on someotherpage.html :

Advantage in sending a value defined with PHP in a form

EDIT: This code isnt for debugging, it is written only as an example and doesnt need completion as the point of it is just seeing the advantages of using a HIDDEN input in a form to retrieve some value. The answers may also be quick and graphic or metaphorical. I dont want a working code, just the advantages of using each methodology. I also fixed an imaginary condition to the while loop and a value for $record_id and placed them so you can understand.
<?php
if (isset($_POST['delete_action'])) {
$deletedRow = $_POST['row_to_be_deleted'];
mysqli_query($connection, "DELETE FROM table_name WHERE record_id = " . $deletedRow);
//Here is where hidden field value is used
}
$someSQL = "SELECT * FROM comments_tbl WHERE postID=$PostRetrievedID";
while ($someFetch = mysqli_fetch_array($con, $someSQL)) {
$record_id = $someFetch['comment_ID'];
$record_content = $someFetch['comment_Content'];
?>
<span>
<?php echo $record_content; ?>
</span>
<form method="post">
<input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>"/>
<input type="submit" name="delete_action" value="Delete comment"/>
</form>
<?php
}
?>
If your question is about why hidden fields even exists, then I have to say that they are used on lots of websites for the exact reason you show in the example.
Lots of times, when you have a form and the user submits it, you need some extra data that the user should not see so that you can manage the data the user submitted. Like in you example, one common use is to atach the ID of the row.

Javascript array data into form fields name=JSkey value=JSvalue

Assume I have a form which has been filled and saved to a SQL database. The form contains over 50+ input fields. The user should be able to update the form data at a later point.
So when the user clicks a certain edit button, the following happens: Data gets fetched from SQL with a PHP script and will be converted to a Javascript array.
The HTML form has input fields with 'name' attributes that are exactly the same as the keys in the Javascript array. The only thing left is to fill the HTML input value attribute with the corresponding values from the Javascript array.
I am pondering how to do this. Probably with some sort of loop or some kind of 'find and replace' function. Anyway all kind of tips or help are highly appreciated!
EDIT: A piece of example code to clarify:
<? php
$Formdata = ($mysqli, "SELECT * FROM FormName WHERE FormID = '$_SESSION['FormID']'");
$Formdata = json_encode($Formdata);
?>
<script>
var FormData = jQuery.parseJSON ( '<?php echo $FormData; ?>' );
</script>"
<form>
Firstname <input type="text" name="Firstname (FIND ARRAY KEY)" value="PLACE CORRESPONDING ARRAY VALUE HERE"><br>
Address <input type="text" name="tel (FIND ARRAY KEY)" VALUE="ARRAY VALUE HERE"><br>
<input ....and so on...
</form>
If You use jQuery use jQuery("input").val(): http://fiddle.jshell.net/kLp9vhvf/1/

How To trigger a php query using a link

i have a page, in where by i can want to collect and store the amount of page views, i have a php query that stores my page views onclick of a button,
if(isset($_POST['submit'])){
mysql_select_db($database_epl, $epl);
$query_lin = sprintf("SELECT * FROM topic WHERE id = %s ORDER BY `Date` DESC", GetSQLValueString($colname_lin, "int"));
$topicId = $_GET['id']; // you need to change 'id' to the name of your ID-parameter in the URL
$viewsIncrementQuery = "UPDATE `topic` SET `Views` = `Views` + 1 WHERE `id` = " . $topicId;
$incremented = mysql_query($viewsIncrementQuery, $epl) or die(mysql_error());
// run/execute mysql query
but now i want to be able to call that query using links, (on click of a link)
How can i go about this
You can add a onclick event to the link and have it set a form's action attribute and then trigger a submit
html
<form method="post" id="myForm">
<input type="text" name="id" />
<input type="button" name="submit" value="submit">
</form>
Click to submit
Javascript
function submitForm(element){
var action = element.href;
var form = document.getElementById("myForm");
form.action = action;
form.submit();
}
Your data would then be in the $_POST global array, if you want it in the $_GET global then just change the method attribute to get
You need to call this page with an ajax query, like this in JQuery. With this, you'll be able to transmit parameters as GET or POST, and receive them in your page, where you will do your update query.
Pass a parameter with your link:
http://example.com/yourpage.php?send=123
in yourpage.php
var_dump($_GET['send']);
returns
string(3) => 123
EDIT:
in your html output introduce a parameter for your link:
link
in yourpage.php
if($_GET['updateview'] == 1)
{
//your sql query etc. from the question.
}

Sending dynamically created html content through email with PHP

I'm making a simple todo list: http://jsbin.com/pemeqeni/1/edit?html,output
I want to be able to email myself the list, and I'm wondering how to do this with PHP specifically. I thought about scraping the HTML with DOMdocument, but I think that will only get the content from the static HTML page, which will never have list items. My other idea is to dynamically create a bunch of hidden input fields in the emailForm and dynamically delete them just as I do with the list items. Are there any other options? What's the standard protocol for something like this?
Something like this should work for getting all list elements.
<script>
function getEachListElement() {
var testList = document.getElementsByClassName("todoBody");
for (var i = 0; i < testList.length; i++) {
document.writeln(testList[i].innerHTML);
}
}
</script>
Try it out by changing your form action to this
<form name="emailForm" method="GET" action="JavaScript:getEachListElement()">
Then you can just create a string that you pass to PHP to email to yourself.
Have you tried the php mail function?
ie
<?
mail( $email, $subject , $text );
?>
Instead of get I would use post then set up a php script you call where you put your values(strings) into variables using $_post and use the mail function to mail those variables(strings).
just to be more clear your html would look like this
<form name="emailForm" method="POST" action="getContent.php">
<input type="text" name="email" value="email"><input type="submit" value="send">
</form>
Your getContent.php would then look like this
<?
$myemail = "myemail#tada.com";
$email = $_POST["email"];
mail ($myemail, 'The shiz you wanted', $email);
?>

Categories

Resources