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

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/

Related

grab values from input box with php

I was wondering if it would be possible to have a php file grab data from a html page with an input box, so that the user enters a word, and the php runs using that word in the script once the user hits enter. Any help would be appreciated.
Use a form with the method attribute set to ‘get’ or ‘post’ like this:
<form method=“post”>
<input type=“text” name=“test” value=“test” />
<button type=“submit”>submit</button>
</form>
Then on the same php page, use this to get the result, store it in a variable and output it:
<?php
$result = $_POST[‘test’];
echo $result;
?>
More information:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form
Hope the formatting in this answer is ok, typed it out on my mobile phone.

How to populate INPUT fields after submitting when user goes back

I have 2 forms for a shopping cart. When they go back I would like the input fields to be filled with info they originally put in before submitting.
1st uses basic form fields to submit billing and shipping info.
2nd is used for CC info. What I would like to do is in that second form have a BACK BTN that will populate all the fields from the first form with the data they entered.
I have a PHP variable $response with an array returning values, but I don't believe they are all included. It brings back a token from PayPal. I think that might be purposely for security reasons. Perhaps I can store them locally in some JS variables?
I tried the below with no results:
<input name="BILLTOFIRSTNAME" id="billtofirstname_id" value="<?php echo $response['BILLTOFIRSTNAME'];?>"/>
use this in your first page -
session_start();
$data = array("input1"=>"value1","input2"=>"value2");
// store any data in this array
$_SESSION['data'] = $data;
Now if user returns to this page -
if(isset($_SESSION['data'])){
// check if data is available
$value1 = $_SESSION['data']['input1'];
}
else{
$value1 = '';
}
In your input's html add this -
<input name="input1" value="<?php echo $value1?>" />
Here you can use local storage variable
<button onclick="store()" type="button">first form submit</button>
<script type="text/javascript">
function store(){
var billtofirstname_id= document.getElementById("billtofirstname_id");
localStorage.setItem("billtofirstname_id", billtofirstname_id.value);
}
</script>
<button onclick="back()" type="button"> Second form back button</button>
<script type="text/javascript">
function back(){
document.getElementById('Id').value=localStorage.getItem("billtofirstname_id");
}
</script>

store dynamically created elements' value to database PHP MySql

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.

How to generate a link for every row/record found in a database to use as a way to populate a form when clicked on?

I have a website with members and when members are logged in they have access to a page with a form that they can use to submit information. This form has a hidden input “user_email” with a pre loaded defualt value that is equal to the logged in members email address on file.
<form action="xxx.php" class="well" id="xxx" name"xxx" method="post">
<input type="hidden" id="user_email" name="user_email" value="xxx#email.com">
<input type="text" id="invoice_id" name="invoice_id">
<input type="text" id="other1" name="other1">
<input type="submit" value="Submit">
</form>
I need a script that will take that pre filled value of a forms input named “user_email” and search and fetch every row/record of data in my database that have that same value under the “user_email” column.
Then For every row/record matched/found I'm trying to have a link generated
When any generated link is clicked, It needs a function to pre fill the form with its corresponding fetched row/record data.
I cant imagine how much time it would take for one to posses the skills required to compose the code it takes to achieve the above...Any point of direction or any help is greatly appreciated...thanks for your time.
You could make a request to a PHP script that reads the email, finds the and returns associated data as an array of objects, and outputs the HTML links, with each link containing the data in custom 'data-x' attributes. For example:
//email_details.php
<?php
//your function that returns an array of objects
$rows = find_the_data($_GET['user_email']);
foreach($rows as $row) { ?>
<a class="email_data_link" href="#" data-invoice-id="<?php echo $row->invoice_id ?>" data-other1="<?php echo $row->other1 ?>">A link</a>
<?php } ?>
You could then use a tool like jquery to modify the form when a link is clicked
$('.email_data_link').on('click', function() {
//copy the data embedded in the clicked link to the form
$('#invoice_id').val($(this).data('invoice-id'));
$('#other1').val($(this).data('other1');
});
Without additional context and understanding your level of expertise, it's hard to create a truly helpful example, but this may at least give you some food for thought.
Best of luck

Filling form fields with jquery

So I have a form that will be used for both inserting and editing data from MySQL.
I thought that instead of writing two forms, I'd write just one, that will be used for both purposes. So when it's for inserting new data, its fields (inputs etc) are obsiously empty. But when it's for editing existing data, I have Jquery for filling the fields with .val().
Like this:
function formSetup(form_name, array_fields)
{
$(document).ready(function(){
var selector;
for(var key in array_fields)
{
selector = "form[name=" + form_name + "] [name=" + key + "]";
//alert(selector);
$(selector).val(array_fields[key]);
}
});
}
And then:
var fieldsArray = new Array();
fieldsArray["field1"] = "data read from Myqsl php";
fieldsArray["field2"] = "data read from Myqsl php";
//etc
Btw, PHP does the job of telling my page whether this form is supposed to insert or edit data, so this javascript function will only be called by php when there is $_GET["action"]=="edit".
What I want to know is, is this the best approach for doing that kind of thing?
Is there a standard way for doing this?
Me to. I'm making the same form for two actions - inserting and editing.
If you using some kind of ajax technology and trying to fill up the form without page refresh you are going right way. But better is just to add values with php by echo'ing data in to the fields values.
There is no such standards for that. Accept you.
You are right, it is nice to have only one form.
Values usualyy filled on the server side (by PHP in your case) but this depends on the project architecture - you may use jQuery. Example for PHP:
<input type="text" name="email" id="email" value="<?=$data['email']?:''?>" />
Example with jQuery:
$.get("getData.php", function(data){
$("input#id").val(data['id']);
$("input#email").val(data['email']);
});
To find out whether the form is used to insert or update data use hidden field with the database record's primary key (usually id):
<input type="hidden" name="id" id="id" value="<?=$data['id']?:''?>" />
When this field is empty - create a new record. When it is containing some value - update a record having the primary key containing in it.
I would do this serverside.
In raw PHP, that is one without a support framework like Yii, Cake, etc. I would implement a light weight MVC framework.
Create a Business Object class.
class MyData
{
$field1;
$field2;
..
}
Then fill your Business Object from your datasource.
$data = new MyData();
$data->field1 = "Something";
$data->field2 = "Other stuff...";
or if it's new data.
$data = new MyData();
Create a form template.
Contents of form.tmp.php
<form ...>
<input type="text" name="field1" value="<?= $data->field1; ?>" />
<input type="text" name="field2" value="<?= $data->field2; ?>" />
</form>
Then use a light wrapper around your template.
ob_start();
include('form.tmp.php');
$html = ob_get_contents();
ob_end_clean();
It's been a while since I've done anything like this. There are a TON of PHP frameworks that take care of this for you though. Some lightweight ones, some heavy enterprise ones.
I didn't test this, but this should get you started.
Instead of populating your form with javascript the better approach would be to handle this server side.
In your php template you can do populate the inputs like this
<input name="field1" type="text" value="<?php echo $fieldValues['field1']; ?>" />
<input name="field2" type="text" value="<?php echo $fieldValues['field2']; ?>" />
If there is no value for each variable the field will be blank otherwise the data you retrieved from the database will be inserted.

Categories

Resources