Need to wrap string in 'Single Quotes' on form submission - javascript

Hello all this is what I got:
NSN: <input type="text" name="filterCriteria(NSN).values" value=""/>
<input type="hidden" name="filterCriteria(NSN).fieldName" value="NSN"/>
<input type="hidden" name="filterCriteria(NSN).operation" value="="/>
For database purposes I need to wrap the string of input value= in single quotes on form submission. I guess this can be done in javascript?

This is really not the job of JavaScript (which runs - or doesn't - in the browser) to prepare the data for the database query that is performed at server-side.
Never trust any data that comes from the browser. Always use prepared statements to bind the parameters of the query and make sure they're correctly escaped and quoted.

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

How to pass form values to Javascript

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!

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

getting value of input box on another page

I have two pages; page1 and page2. page1 holds a form while page2 has some images. I want to enter a sentence into the form on page1 and get the value of that text box on page2.
the form on page1
<form name="input" action="page2.html" method="get">
<input type="text" name="textbox" id="textbox">
<input type="submit" value="Submit">
</form>
what would be the proper way to go about this?
Would I use the get method along with the action method to send the value through the url and then extract it using window.location.href then splitting the text after the ? or is there a simpler way of achieving this?
Thanks
Just send it in the query string and read it in page2, as you said.
See this to have an idea of how to read the query string parameter:
How can I get query string values in JavaScript?
Your way of doing this would work, although it's certainly not a good long term solution. If your site is going to get more complicated, it would be better to use a server-side language like .NET, PHP, Ruby, etc.
If you have to get thed data using only JS, then you need to use URL. Otherwise you can use server side script like jsp.
When you use URL, make sure the text is URL-encoded before appending to the URL.

Submit unmasked form value with jQuery/meioMask

I mask the input of fields like SSN to contain dashes when they are displayed but would like the value that is submitted to be only the numbers.
For example, my SSN is formated as:
<input type="text" name="ssn" alt="999-999-9999"/>
And upon entering "1234567890" I get the nice formatted output.
123-456-7890
Now I would like only the numbers to be submitted as "1234567890". Is this easily possible?
For reference: http://www.meiocodigo.com/projects/meiomask/
This would probably solve your problem. It's quick-n-dirty though. It just removes the '-' signs with a regex and spits it out into a hidden field which will then be submitted.
<input type="text" id="ssnMasked" />
<input type="hidden" id="ssn" name="ssn" />
<input type="button" value="Submit" onclick="RemoveMaskAndSubmit()"/>
<script type="text/javascript">
function RemoveMaskAndSubmit() {
$('#ssn').val($('#ssnMasked').val().replace(/\-/g,''));
$('#formId').submit();
}
</script>
I'm not sure on the etiquette on answering my own question but I actually used a fairly simple solution derived from both of your answers.
Problems arose from using hidden fields based on the site using the Struts framework and it's automatic form processing and special JSP form tags. I would change the backend to do all the processing there but as it's the middle of the day I can't restart the Tomcat server to load in the changes without crippling operations for a short time.
On submit I call a function UnmaskMaskedValue() which explicitly sets all the masked values to have a mask not containing the invalid characters.
function UnmaskMaskedValue() {
$('#ssn').setMask('9999999999');
}
This changes the value before any data is submitted to be valid on the backend.
I appreciate both of your suggestions and would rate you up if only I was able to.
Looks like this option is deprecated.
<a onclick="jQuery('#unmasked_string').html( jQuery('#unmasked_input').unmaskedVal() );return false;" href="#">Get the unmasked value from the input</a>

Categories

Resources