Filling form fields with jquery - javascript

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.

Related

Load data into form using htmx js

I'm using HTMX a javascript library that allows you to access AJAX directly in HTML.
Although I understand the basic logic of HTMX, there are some aspects that I don't get.
I managed to make a form and write data to the server:
<form id="my-form">
<input type="text" name="firstname">
<input type="text" name="secondname">
<button type="button"
hx-post="write.php"
hx-target="#container-div"
hx-swap="innerHTML">
Submit
</button>
</form>
<div id="container-div"></div>
HTMX will read all name and will submit them to write.php where they can be read with a loop of $_POST:
write.php:
foreach ($_POST as $key => $value) {
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}
I don't understand how to populate the form with the data returned by the server. For example, given the following form and the following output I would like to populate the single INPUT fields when the button is pressed:
HTML:
<button type="button"
hx-get="load.php"
hx-target="#my-form"
hx-swap="innerHTML">
Load data
</button>
<form id="my-form">
<input type="text" name="firstname">
<input type="text" name="secondname">
</form>
load.php:
$a = array(
"firstname" => "John",
"secondname" => "Smith",
);
echo json_encode($a);
I know that docs say that "when you are using htmx, on the server side you typically respond with HTML, not JSON", but does this means that the server output should be the whole HTML code necessary to render the form again like this?
echo "
<form id="my-form">
<input type="text" name="firstname" value="John">
<input type="text" name="secondname" value="Smith">
</form>
";
What if the form had dozens of fields, long select menus and complex checkboxes groups? Won't it be an enormous amount of data passed from the server to the client?
I'm pretty sure I'm missing something...
You are correct in your understanding: htmx would expect you to return all the HTML that you want to populate the form with.
This might seem inefficient, but it turns out that HTML compresses very well and the typical payload is not much larger than the JSON equivalent. This blog article outlines why that is.
Additionally, even with a larger payload, the transfer time is often dwarfed by the connection set up and processing time. htmx doesn't require any client-side templating, and thus can be much faster than many JSON-based UI setups that require that. intercooler.js, the predecessor to htmx, grew out of a small helper function that I wrote because I was processing a huge table in JSON and it was taking forever. I found out that just receiving the table in HTML form and slamming it into the DOM was orders of magnitude faster.
All that being said, I don't want to dismiss your question. There are ways to narrow your payload down in htmx:
You can use the hx-target to narrow down the area that is updated to the minimum amount of HTML
You can use Out of Band Swaps to target specific items for replacement
Push come to shove, you can use the HX-Trigger header to pass data directly to a javascript event handler to populate your form
However, before doing any of that, I would recommend just trying the boring, simple way and seeing if the performance is acceptable. I am guessing that the answer will be yes, and you will find that the decreased maintenance burden is well worth whatever small perf gains might be achieved by a more complicated solution.
you can calculate how many forms that you have filled in first then output or process them
<?php
$numberOfForm= (count($_POST))/2;
for ($i=1; $i<=$numberOfForm; $i++) {
// declare the variable
$firstname= $_POST["firstname"];
$secondname = $_POST["secondname"];
echo '$firstname'.'$secondname';
?>

Use get_option in WordPress to create new JavaScript variable

So I've been building my first WordPress plugin, and I've of course hit some roadblocks. I first wrote all this code as a page template, but now I'm converting it to a plugin so I can use it across several sites.
It's essentially a contact form that creates a price quote based on user selection. When it was a template, I just hardcoded the values and made everything work with an external jQuery file. Now, I'm wanting to take user input from the plugin admin settings page and use that value to make calculations rather than the values I hardcoded.
Here's what I had before with the jQuery:
(function($) {
$(document).ready(function(){
$("#carpet_cleaning).change(function () {
var bedrooms = $("#carpet_cleaning").val();
/*-------CHANGE RATES HERE--------*/
var total = (bedrooms * 39);
var totalPrice = "$" + total;
$("#output1").text(totalPrice).fadeIn();
});
}(jQuery));
So basically I want to use user input from the plugin admin settings instead of hardcoding a 39. That way prices can vary depending on what price the user wants to set.
Here's my HTML for my admin settings:
<h2>Display Settings</h2>
<form method="post" action="options.php">
<?php settings_fields( 'my-plugin-settings-group' ); ?>
<?php do_settings_sections( 'my-plugin-settings-group' ); ?>
<fieldset>
<input type="text" size="3" name="carpet_cleaning_price" value="<?php echo esc_attr( get_option('carpet_cleaning_price') ); ?>" /><label>Carpet Cleaning Price Per Room</label>
</fieldset>
<?php submit_button('Save all changes', 'primary','submit', TRUE); ?>
</form>
I was under the impression that I could use get_option to store the user input. If that's the best way to do that, how could I access that value in my jQuery variable?
Ideally I'd want to do something like:
var sectionalCleaning = carpet_cleaning_price;
And then just use carpet_cleaning_price instead of 39, which would give me the user value.
Is there some way I can do this easily? I'm also going to have to do this on the backend using PHP so that someone can't adjust the values in their browser and the calculation happens on the server, so if you have a solution for that as well, I'm open to that. Go easy on me, I'm a new developer! Thank you.

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

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/

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

Categories

Resources