Sync HTML form with URL query string? - javascript

On websites such as eBay, upon returning to a search page, the search options are all filled in. I'd like to do the same with my website, where currently, returning to the search page returns the correct search results but the search form is empty.
The two approaches I've seen to this so far:
Have the form written in HTML, use JS to parse query string and set form values.
How can I pre-populate html form input fields from url parameters?
Generate the form in JS with any values in the query string, this will make a blank form if there's no query string given.
Query String for pre-filling html form field
Both these solutions seem hack-y. I'd imagine that this is a common task, is there a standard or clean method to do this in one or two lines?
There is obviously something that serializes the fields from a form to a query string, there should be a way to use that in reverse to take the query string and fill in the form fields, without having to "roll your own" loop in JS.

I'd suggest saving the information in a session/cookie and pulling from that to populate the form. That's how it's done on eBay.

Just use GET parameters.
http://sample.com/?search=pen&color=blue
Now while building your form elements, just do something like:
$search = isset($_GET['search']) ? $_GET['search'] : '';
$color = isset($_GET['color']) ? $_GET['color'] : '';
echo "<input type='text' value='{$search}' placeholder='Search' />";
echo "<input type='text' value='{$color}' placeholder='Color' />";

Related

How to make php get last row from a Colum from mysql and make the result a variable that I can take with javascript?

I want php to get the last row of a specific Colum. Then I want the result to be a variable that javascript can take and have it a javascript variable.
something like this maybe
var result = [php variable]
My question is not just about how to make a php variable into javascript varibale but also on how to make php get the last row of a colum. Thanks, BTW (I'm new to this stuff so please be clear in your explainations.)
In order to get the last row of a specific colum, you need to query your database in a way such that your desired "last row colum value" is easily obtainable by php. This is commonly done using the SQL ORDER BY and LIMIT clauses.
For example:
SELECT name FROM my_table ORDER BY id DESC LIMIT 1;
This query's result-set will contain only the name column value for the my_table record with the highest id.
PHP can then assume that this data is contained by the first row in the result-set. For example (using PDOStatement):
<?php
//...
$data = $pdoStatement->fetch(PDO::FETCH_ASSOC);
echo $data['name']; // The name column value of the row with the highest id
The specifics of the query for your use case are not made clear by your original post, but the above example logic should apply anyhow. Make sure you provide the appropriate query and have PHP fetch the first record in the result-set.
You can then parse this data into Javascript variables:
<?php
<script>
var result = "<?php echo $data['name']; ?>";
</script>
Warning: This example is very basic, make sure you protect yourself against XSS vulnerabilities. Do not let database data provided by PHP be evaluated by Javascript without protection.

Is there a more concise way to POST a large number of input element values to an API?

I have an ASP.NET project that is currently making use of JQuery and Bootstrap to create a front-end. One part of this front-end involves the user filling out a form made up on 30+ input elements, which then needs to be submitted to a back-end API.
Usually if I needed to communicate with an API I would use JQuery's built in post() and post() methods, and constructing a query string to use within these methods.
However since there is a large amount of input elements associated with this form, I am hesitant to make use of this particular approach as it seems like a very messy and roundabout way to submit the data to the API.
Unfortunately the usual <input action="action.xx"> approach is not available to me in this particular situation, so submitting the form as a whole is not a possibility.
However I really don't want to do something like this below:
queryString =
"?input1=" + $("#input1").val() +
"&input2=" + $("#input2").val() ... //repeat for 30+ input elements
$.post(url + queryString, funtion(data){ ... });
Surely there must be a better way to go about solving this particular issue that doesn't involve creating an abhorrently large string and passing it through JQuery's post method?
Give every input a name attribute instead (the same name you want to use for the query string), and then call .serialize() on the form to generate the query string:
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(this).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="inp1">
<input name="inp2">
<input name="inp3">
<button>submit</button>
</form>
Or, if you can't do that, and you want a shorter, less error-prone way of generating the string than what you're using now, iterate over an array of selectors and grab each's .val(), then join by &s:
const ids = ['input1', 'input2', 'input3'];
const queryString = ids.map(id => $('#' + id).val()).join('&');

concatenate a list of form fields and mixed text content inside another form field

I am using the following web app, ESRI GeoForm, and attempting to customize it for concatenation purposes. It is a private, internal to our organization only, form. So I can't share the form I am using other than through video or images.
So basically, when the users enter 'Address Number' and 'Address Prefix' and other pieces to the 'Address' I would like to concatenate those entries in the fields "Full Address" and "Full Name."
All of these fields are needed, but I would REALLY rather not require users to do a double input so many times. SO...
This is a Dojo app, built on ESRI's Javascript API. I am fairly comfortable with editing small Javascript scripts, and I've built fairly robust ones years ago, but I'm somewhat lost with such a complex and lengthy apps as this one. Luckily, I just had some developers in the GIT Hub group make a very similar change to add the ability to 'lock' form fields. I have been instructed that I could mimic their addition for the locked functionality for fields to add a concatenate functionality for the fields. So... onward I go.
My first step was to go to the JSON for the fields that are added. This JSON is in the default.js file. I decided to utilize what I believe is an Array object as an attribute option. So, for example, when building the form in the JSON and selecting what fields are needed from the database and how to lay them out on the form you create these field attributes. To create a default value for one of these fields you would create an attribute like so:
...
"defaultValue" : "true"
...
What I've done for the concatenate option is to go with an entry like so:
...
"concantenated": [ "FIELD_ONE", "space", "FIELD_TWO", "space",... ],
...
My thoughts are that each HTML Form Field is identified with an ID that is equal to the actual field name. Like so...
<input type="text" class="form-control" data-input-type="String" maxlength="20" id="ADDRNUM" placeholder="175" data-display-type="text">
That field populates the database field ADDRNUM and it uses that field name as the ID. So in my concatenator attribute when I feed a list of field names I can point to those HTML Form Fields via ID.
This way... can be told to concatenate somehow, maybe like so?
('ADDRNUM').keyup(function () { ('FULLADDR').val(this.value); }
The problem I am having is I am not sure where, in the main.js file I need to add the concatenation process/method/function?
If I follow the system used to integrate a 'Locked' option that was just added a day ago... then I would need to duplicate the "disabled: !!currentField.locked" with something like concantenated: !!currentField.concatenator but I am lost as to where / how I integrate a concatenation method.
UPDATE (10APR18):
So I've begun adapting code under [form folder]/js/main.js to test and work with this. I'm starting on line 772.
if (!!currentField.concantenated) {
domClass.add(formContent, "concantenated");
array.forEach(currentField.concantenated, function(entry, i){
console.log(JSON.stringify(entry, null, 4));
console.log( currentField );
if(entry !== "_space_" || "_comma_")
{
console.log( "It is not _space_ nor _comma_ but rather " + entry );
concatField = dom.byId(entry.stringify);
console.log( concatField );
testField = dom.byId('ADDRNUM');
console.log( testField );
test = on(concatField, 'click', 'foo');
console.log( entry + " was just updated with foo");
}
});
}
This is giving me some good feedback through the console.log and what I am finding out is that the fields I need to reference aren't created yet. Now I could just move the fields to the bottom of the JSON list in [form folder]/config/default.js

Dynamic search input as variable for cypher

I'm trying to create an result page with structr 2.0.1.
enter image description here
Within these page I want to show the results of the user input. The string typed into my input field should be transferred via cypher query to my Neo4j-DB.
Input = "admin" -> Cypher(Match (n) Where n.name = 'admin' Return n)
The return value will be used to instantiate a graph obj via an integer-id (that works totally fine and is no issue).
After hours of investigating unfortunately I'm not able to do it witch the built-in functionality. I tried a lot with the "Query & Data Binding", & "HTML-Properties"-Page and Java Script as well but I couldn't transfer the value from my html element to my cypher query function within my fronted.
[input field ("String")--> button fuction()--> cypher (Query) --> function input {graph.addNode(ID)}]
There must be a solution within structr to solve this problem without a direct ajax-call.
Maybe someone of you discovered the same problem or has a solution for this.
I would very appreciate some help in this case.
Thanks!
Maze
the value of your request parameter is available in StructrScript, see https://support.structr.com/article/119 for more details on that.
In the scripting context, there is an object named request that you can access directly, which will contain any request parameter you send to Structr. So in your case, you can access the value of your input field (provided that you set the name to name) like this:
${request.name}
The following steps are needed to make that work:
create <form method="POST" action="/${page.name}">
insert <input type="text" name="name" value="${request.name}">
insert <input type="submit" value="submit">
When you submit the form, the request parameter "name" will be available in the Structr context as described above.
To insert that value into a Cypher query, you have to construct the query around the request value, for example like that:
${cypher(concat('MATCH (n) WHERE n.name = "', request.name, '" RETURN n'))}
But be very careful with a setup like that, because the above code is vulnerable to a query injection attack (aka SQL injection, or rather CQL injection in this case).

Populating data in the text fields using java scripts

I have two html pages. from one html if I am clicking the id which i have made as a link I want the data associated with that to be populated into the other html page.Its like the id of an employee is being cliked and all te values associate dwith it like his name, address and gender should get populated in the text fields in the previous html table. Currently I am not using any DB. I have entered everything manually through html. I want to use only Java script.
If I understand your question: Yes, it can be done. (I don't know why you would want to do this without a database, but it is possible.) When you're making the links on your first page, make sure they contain the information you want in query string format like this:
Bob Smith
Then on your second page, you can use JavaScript to parse window.location.search which is the query string that you passed from your first page. You can do this in many ways. Here is an example function that will let you extract variables from the query string. You could use it like this on the second page:
<script type="text/javascript">
var firstName = getParameterByName('firstName');
var lastName = getParameterByName('lastName');
var gender = getParameterByName('gender');
// now do something with those variables.
</script>

Categories

Resources