So I'm trying to build a form for submitting input data and I want the values for each individual element to be stored as a Javascript variable so I can use SessionStorage to access them from another page (I don't want to send the data to a server since I can't pay for one and I don't intend on sending this to multiple users anyway). Problem is that no matter how I try to do it, the values are coming up as null. Here's my code (I changed the variable names because they're sensitive data, but I've checked the actual names and they're not reserved):
<form id="form_updates" method="post">
Input 1: <br>
<input type="text" name="input1" id="input1"><br>
Input 2: <br>
<input type="text" name="input2" id="input2"><br>
Input 3: <br>
<input type="text" name="input3" id="input3"><br>
<button onclick storeValues()>Update Form</button>
</form>
<script>
function storeValues(){
sessionStorage.setItem("ses1", "<?php echo $_POST['input1'] ?>");
sessionStorage.setItem("ses2", form_updates.elements[1].value);
sessionStorage.setItem("ses3", document.getElementById("input3").value);
}
So the code is a mess right now, I'm aware of that, I've been testing multiple solutions and none of them seem to work (once I figure out something that works I'll apply that consistently throughout the code). I've tried using an event listener on the button, and I've tried reading the form. I've tried all three of those methods to store the values inside and outside of storeValues(). Every time, it always evaluates to null. I've been researching this issue for days and I can't seem to figure this out. Please help!
Related
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';
?>
i created a Google Form and list down all the ID in each input type, and then created a localhost with the same ID,
The first thing i want to do is to save the values into a localhost and pass the values in the Google Form or set the values into the corresponding ID or Name in each input type in a new tab, is there a way to do this using ajax or jquery?
my form looks like this
<form method="post" action"">
<input type="text" name="FName">
<input type="text" name="LName">
<input type="Submit">
</form>
$post('https://docs.google.com/a/grabtaxi.com/forms/d/e/1FAIpQLSfjiuhFbURVavdNW82ofHG3gPpBUKkK2VATQQKmV-YKKrJ75Q/viewform'{FName:Fname,LName}function(){
window.open('https://docs.google.com/a/grabtaxi.com/forms/d/e/1FAIpQLSfjiuhFbURVavdNW82ofHG3gPpBUKkK2VATQQKmV-YKKrJ75Q/viewform');
});
i am trying to use the $.post() in jquery but it looks like i cannot set the values into the Google Form.
Any tips please... Thank You very much
You should wrap your javascript code inside a scipt tag. Then, you should bind the code to submit event, tha happened when you press the submit button.
<script type="JavaScript">
$('input[type=submit]').submit(
// here you should put your code
});
</script>
And check your code, you wrote $post instead of $.post mi sing the dot.
I'm looking for a way to update the webpage I'm working on to act as a report for several different people to pass back and forth. I'm using forms to take in several pieces of data and am wondering how I can make it so that it just immediately adds the content to the divs under the right heading. I'm currently using jquery and append and it looks like it adds the desired input and then immediately removes it. I tried using .live as well and it did not show up at all. Is there a way to make form inputs post to the page without submitting to another page?
Here is my code so far, testing just the element that will be the heading for the issue:
<div class="IssueDiv">
</div>
<form id="newIssue">
<fieldset>
<legend>Add a new important issue:</legend>
<input type="text" id="issue" placeholder="Issue Summary...">
<input type="text" id="issue-client" placeholder="Client...">
<input class="ticket" type="text" id="issueParent" placeholder="Parent ticket..."><br>
<textarea placeholder="Issue details..."></textarea><br>
<button id="addIssue">Add Issue</button>
</fieldset>
</form>
And the jquery:
<script>
$(function(){
$("#addIssue").click(function() {
var $issue = $("#issue").val();
var $issueSum = $("<h3></h3>").text($issue);
$(".IssueDiv").append($issueSum);
});
});
</script>
edit: I'm looking into using AJAX but I'm not sure how to make it so that all of the input data will persist. I am basically looking to make a webpage-style-report that will allow myself and my team to update the entries on the report and they will stay on the report until we are able to take them off by removing a div that encapsulates the individual issue.
I would also like to be able to format the individual pieces here separately, so, for instance, I could add a check-box that says the issue is urgent and format the heading of those to be red. What is the easiest way to have data that persists, can be added into new (div/h/p) elements, and is shown on the main webpage, while also allowing me to update formatting?
Your code appears to add the text and then immediately remove it because your form gets posted and the page reloads, effectively resetting the page to its initial state.
If you just want to add the text to the page without posting the form or executing any server-side processing, you can prevent the form from posting using jQuery's preventDefault(). Note that I have created a submit listener on the form itself, rather than a click listener on the submit button.
$("#newIssue").on('submit', function(e) {
e.preventDefault();
...
});
$(function () {
$("#newIssue").on('submit',function (e) {
e.preventDefault();
var $issue = $("#issue").val();
var $issueSum = $("<h3></h3>").text($issue);
$(".IssueDiv").append($issueSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="IssueDiv"></div>
<form id="newIssue">
<fieldset>
<legend>Add a new important issue:</legend>
<input type="text" id="issue" placeholder="Issue Summary...">
<input type="text" id="issue-client" placeholder="Client...">
<input class="ticket" type="text" id="issueParent" placeholder="Parent ticket...">
<br>
<textarea placeholder="Issue details..."></textarea>
<br>
<button id="addIssue">Add Issue</button>
</fieldset>
</form>
However, keep in mind that if you're using this to share reports between computers, this will not work. This is only updating the DOM in the current browser and is not doing any data storage or retrieval. If you need the reports to update online, consider using AJAX to post your data to a server-side script without refreshing the page. Then include some sort of timer that refreshes the content (also using AJAX) on a schedule (e.g. every 10 seconds).
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
My question may sound naive, but really struggling to do a very simple thing. Suppose I have to html page - send.html and receive.html.
In send.html page -
I have text field and a button in like following -
<body>
<form onsubmit="recieve.html">
<input type="text" id="mytextfield">
<input type="submit" id="submitbutton" value="Go">
</form>
</body>
Here I want to put something on the textfield and I want to see that value in the receive page some thing like - Hello 'value of textfield'. That's it.
Do I need to use JS cookie for that? If not, how can I do it in the most simple way?
Need help :(
The most simple way is PHP. Bottom line is you need something handling the data on the server side.
With javascript you can write a function to store the value in a cookie and read it on the next page. By the way, your page goes in the action attribute. onsubmit expects a javascript function, not a page.