Load data into form using htmx js - javascript

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';
?>

Related

Reading in Data from HTML Javascript form

I am creating a website backed by a database. I have created my forms that collect the information but now i need to read in the input from the form when user clicks submit and process it for mySQL. I am having my form action be a new page but I can't figure out how to read in value from the previous page. My Form code looks like this:
<div data-wrapper-react="true">
<span class="form-sub-label-container" style="vertical-align:top;">
<input type="text" id="first_3" name="q3_fullName3[first]" class="form-textbox validate[required]" size="10" value="" data-component="first" />
<label class="form-sub-label" for="first_3" id="sublabel_first" style="min-height:13px;"> First Name </label>
</span>
When user hits submit the action for this page is connect.php. I am not sure how to read in the value there. I tried this following command:
document.getElementById("first_3").value;
This just displays the code on blank html page for connect.php and not read in the values. The data from the forms needs to be processed into different tables if someone can help with that as well that would be great. Thanks
Form handling, in the way you are describing, is something you do server-side. PHP is handled on the server first where PHP tags can be evaluated to HTML, then this is returned to the browser. You would not handle form input from javascript, until after your PHP has done something with it. Here is a refresher: https://www.w3schools.com/php/php_forms.asp
<?php echo $_POST["q3_fullName3[first]"]; ?> would output the value into the HTML page allowing you to do something like this:
console.log("<?php echo $_POST["q3_fullName3[first]"]; ?>");
If you view source of the HTML, you will notice the PHP tag is gone and replaced with the form field value.
It sounds like you might want to get a book about PHP + MySQL since interacting with a database is a more advanced topic. I can recommend this one:
https://www.amazon.com/Learning-PHP-MySQL-JavaScript-Javascript-ebook/dp/B00QUBHNFI/ref=mt_kindle?_encoding=UTF8&me=

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

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

Submit HTML form to display entered info in new page

I have a HTML form (called form.html)and a JavaScript function such that when form is submitted, information in that form will be displayed.
Now I want all those info will be shown in new HTML page (called confirm.html), where should I go from?
NOTE: No php or sever-side or anything that really seriously related, it's just simple OFFLINE HTML-form problem, I just have 2 html place in same folder, I will test it on my browser, that's it. Only thing that I worry is how to use information from form.html file in confirm.html file since they are obviously separated.
Thank you very much, here is my form.html ( I dont have confirm.html yet)
<HTML>
<HEAD>
<TITLE>Contact</TITLE>
<script type="text/javascript">
function addtext()
{
var fname = document.myform.first_name.value;
var lname = document.myform.last_name.value;
var email = document.myform.email.value;
document.writeln("Thank you! You have just entered the following:");
document.writeln("<pre>");
document.writeln("First Name : " + fname);
document.writeln("Last Name : " + lname);
document.writeln("Email Address : " + email);
}
</script>
</HEAD>
<BODY>
<center>
<b>CONTACT US</b> <br></br>
<form name="myform">
<label for="first_name">First Name </label>
<input type="text" name="first_name" maxlength="50" size="30">
<br>
<label for="last_name">Last Name </label>
<input type="text" name="last_name" maxlength="50" size="30">
<br>
<label for="email">Email Address</label>
<input type="text" name="email" maxlength="80" size="30">
<br>
<input type="submit" value="Submit" onClick="addtext()">
</form>
</BODY>
</HTML>
Check out the window object of JavaScript: http://www.devguru.com/technologies/javascript/10855.asp
It has a property location, if you write into it, your browser will redirect:
window.location = "http://www.google.com";
Note though, that this will not post your data to confirm.html. what you are trying to do without server-side scripting is not very useful. An HTML form will use CGI (common gateway interface) to send data to a server, that can then process the information. If you use the file:// protocol (as you seem to be doing; all local, static files), there is no server-side to process the data, only JavaScript.
If using the GET method of sending the data through CGI, you could extract the data from the URL using javaScript (as mentioned in another question). To do this, just update your form like this:
<form action="confirm.html" method="get">
And do not put a onClick handler on the submit button, just let it submit.
Many other tools exist though that way more are suitable for the job: server-side scripting languages, examples include PHP, ASP, JSP. For local setups, your best best is using XAMPP.
If you don't want to rely on server-side technology, this becomes more complicated (and hacky, I might add). Probably the easiest would be to generate a url like this on submit -
http://localhost/confirm.html?first_name=val1&last_name=val2&email=val3
then add some code to confirm.html to unpack this. Here's a related question you may find helpful.
If you'd allow me a moment of editorializing, what exactly are you trying to do? If this is just a personal project to see how html works, then I'd strongly recommend starting to learn about server-side technology - once you start wanting to handle user data and persist state, you're pretty much forced to use the server. The web is by design pretty stateless; you can't pass variable in-between pages without either using the server, or through some very complicated AJAX & DOM updating techniques which tend to rely on specialized server files anyway. You can run a PHP & MySQL server locally using existing technology, and if you're interested in expanding your knowledge of web technology this is an inevitable step.

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