How to populate an textboxes with query string value(s) from URL - javascript

I have a simple Window Forms application that opens up a webpage with set parameters.
The link send the user to a page with 2 text box fields and a submit button.
I am trying to automate this process so it grabs the parameter values and puts it into the text box then clicks submit .
This is my current code for my windows form:
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
libLink.Links.Remove(libLink.Links[0]);
libLink.Links.Add(0, libLink.Text.Length,
"http://www.example.com/?UserName=value1&FirstName=value2");
}
private void libLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
ProcessStartInfo sInfo = new ProcessStartInfo(e.Link.LinkData.ToString());
Process.Start(sInfo);
}
}
}
How can I create a script that that takes those parameters in the URL to populate two text box fields and then submit the form?
This is my HTML Page:
<form action="/send" method="post" novalidate="novalidate">
<input class="form-control" data-val="true" data-val-UserName="Wrong username" data-val-required="Enter a valid Username" id="Username" name="Username" placeholder="Username" type="text" value="">
<input class="form-control" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
<button type="submit">Sign In</button>
</form>
Fairly new to coding so I tried to keep my code as simple as possible.
I looked at possible methods such as QueryStrings, JavaScript and Jquery, but I am not sure how to approach this problem.

There's a few ways of doing it really but i'll give you a basic walk through of how i would do it in javascript with a bit of JQuery.
we have variable with the URL we start by:
var url = "http://www.example.com/?UserName=value1&FirstName=value2"
var params_string = url.split("?")[1] //UserName=value1&FirstName=value2
so first we split the string into a list like above which returns a list of the items which are separated by the "?" character, but we only need the second item(at index 1) so we add the [1] to the end to only store that bit.
We then split this again to get the individual parameters.
var params_string_list = params_string.split("&")
["UserName=value1","FirstName=value2"]
which returns a list as above, again need to break that down i would make it into an object like so :
var params = {}
for(var i =0;i < params_string_list.length;i++ ){
var temp = params_string_list[i].split("=") // looks like ["UserName","value1"]
params[temp[0]]= temp[1]
} //params now looks like {"UserName":"value1","FirstName":"value2"}
as this makes it easy to access and use.
we can then do the following to set the values in the form:
if(params.UserName){
$('#Username').val( param.UserName );
}
if(params.FirstName){
$('#FirstName').val( param.FirstName );
}
if statments are there to check that the value exists in the object so we don't sent the value to "undefined" by accident.
Hope this helps.

Related

Prefill form based on URL parameters javascript

I'm passing name & email through URL parameters from a popup form like this
xyz.com?om_email=test%40test.com&om_name=Test
I need these two forms prefilled on xyz.com site
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
Can anyone please help?
More context would be nice, but try this:
I used a test URL string to allow the example to work, but on the actual site, replace params variable with the one that is commented, (hint: window.location.search) to extract the parameters from the URL.
There are different ways to do this, but I created an object from the parameter string then looped over the inputs and updated their value by matching the data object key to the input value name attribute.
Note: Be sure to run the JavaScript after the page loads.
var url = "xyz.com?om_email=test%40test.com&om_name=Test";
var params = "om_email=test%40test.com&om_name=Test".split("&");
//use this on the actual site to extract parameters from the url
//var params = window.location.search.slice(1).split("&");
//convert the params to an object
var data = params.reduce((obj, param) => {
var pair = param.split("=");
return { ...obj,
[pair[0].replace("om_", "")]: decodeURIComponent(pair[1])
}
}, {});
//console.log({data});
//insert values by matching input name to data object key
document.querySelectorAll("input").forEach(input => input.value = data[input.name]);
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
This is how to autofill a form using HTML5.
<input value="valuehere">

javascript thymeleaf triggering a url

I have a thymeleaf application that should do the following.
Persist some data to the database when the user clicks the submit button. That same submit button must fetch some data from another server that has its own database; different from mine. Here is my code (obviously, I am doing something wrong ergo my question here.)
<form method="POST" th:action="#{/index}" th:object="${notification}" class="contact-form">
<div id="asset-search" class="row">
<div class="col span-12-of-12">
<!-- <div class="alert alert-info" th:if="${notificationSent}">Your feedback is greatly appreciated.-->
<!-- </div>-->
</div>
<div class="col span-1-of-1">
<label class="search-lbl">Tell us what you are searching for and we will try to find it. Please
include email if you wish us to contact you.</label>
</div>
<div class="col span-2-of-2">
<input type="text" name="keyword" id="keyword" placeholder="Search" th:field="*{search}">
<input type="text" name="email" id="email" placeholder="Email (Optional)" th:field="*{email}">
<button type="submit"
th:data-url
="#{http://auction.mainauctionservices.com/cgi-bin/mmcal.cgi?mainauction/keyword/{search}(search=${search}))}"
onclick="window.open(this.getAttribute('data-url'))">Go
</button>
<!--<button type="submit" onclick="equipmentSearchFn()">Search</button>-->
</div>
</div>
</form>
My controller is working fine. It persists data. No need to worry about the back end. Maybe the controller could be rewritten, but its persisting.
HOWEVER, I need to fetch data from the back end of ANOTHER server. The server that I need to get data from has the following format
"http://auction.mainauctionservices.com/cgi-bin/mmcal.cgi?mainauction/keyword/oven" <--- the word oven comes from this input ... you can click the link you will see it will work; you can replace oven for table or sink and it will work.. that is the back end I am fetching from.
However the words oven or sink or table that the user types in the input search bar below are coming from this th:field="*{search}
<input type="text" name="keyword" id="keyword" placeholder="Search" th:field="*{search}">
It does not come from my database, it doesn't have to; it comes from what the user types in the search bar.
I tried to use the
th:data-url
="#{http://auction.mainauctionservices.com/cgi-bin/mmcal.cgi?mainauction/keyword/{search}(search=${search}))}"
onclick="window.open(this.getAttribute('data-url'))">Go
</button>
That you see up there but I don't know how to grab the search the user enters from the
<input type="text" name="keyword" id="keyword" placeholder="Search" th:field="*{search}">
My controller is this
public class IndexController {
#GetMapping({"", "index", "home"})
public String index(Model model) {
model.addAttribute("notification", new Notification());
return "index";
}
#PostMapping(value = "/index")
public void searchNotification(#Valid #ModelAttribute("notification") Notification notification,
#RequestParam("search") String search,
#RequestParam("email") String email,
Model model, BindingResult result,
HttpServletRequest request) {
if (result.hasErrors()) {
return "index";
}
notification.setSearch(search);
notification.setEmail(email);
model.addAttribute("notification", notification);
notificationService.save(notification);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
SimpleMailMessage simpleMailMessage = mailConstructor.sendSearchNotification(appUrl, request.getLocale(), notification);
javaMailSender.send(simpleMailMessage);
model.addAttribute("notificationSent", "true");
model.addAttribute("appUrl", appUrl);
return appUrl;
}
}
I also tried using javascript which was my original thought but the javascript and the controller with return "index" were interfering with each other.
So, I tried to do it with what you see above
here is my javascript
function equipmentSearchFn() {
let keyword;
let url;
keyword = document.getElementById("keyword").value;
url = "http://auction.mainauctionservices.com/cgi-bin/mmcal.cgi?mainauction/keyword/" + keyword;
window.location = url;
}
ideally the javascript would be the fastest and best route but the problem is when its persisting the data via the controller im running into problems with a http POST trying to open a new page with the results..
i don't know if i am overworking this but its definitely got me overworked
thanks
If I understand your question correctly, then you want to have the browser redirect to an external URL after the POST to your controller. To do that, just return a String from your searchNotification method:
#PostMapping(value = "/index")
public void searchNotification(...) {
...
String url = "http://auction.mainauctionservices.com/cgi-bin/mmcal.cgi?mainauction/keyword/" + search;
return "redirect:" + url;
}

sending a value to an input using Symfony

I am trying to use javascript inside Symfony and then I got a problem. The problem is located at my file twig.html. At the begining I had this code:
{{ form_widget(form.name, {'attr': {'class': 'form-control'} }) }}
Then I change it to this in order to use dynamic validation(that was the same code generated in browser, I just add onkeyup action)
<input type="text" id="person_name"
onkeyup="myFunction()" name="person[name]" required="required"
class="form-control" />
Then I was happy because my validation rules work, but I discovered that when I want to update to form. The field name is empty (but in the server it's good). So I would like to get this field. In my function updateAction I dump variable person before handling the form and then name was containing the good element. So the problem is there is a difference between form_widget and the good I just did. I would like to do a thing like this to get my field name:
<input type="text" id="person_name"
onkeyup="myFunction()" name="person[name]" required="required"
class="form-control" value="if(form.name is not empty) form.name"/>
Thank you.
Are you passing the entity or document to your createForm function?
Something like that should work:
controller
$em = $this->getDoctrine()->getManager();
$your_entity = $em->getRepository(**your_entity_path**)->findOneBy([**parameters**]);
$edit = 1;
if(!isset($your_entity)) {
$your_entity = new Your_entity();
$edit = 0;
}
$form = $this->createForm(**your_entity_type_path**, $your_entity);
$editForm->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if(!$edit)
$em->persist($your_entity);
$em->flush();
//other code
}
I hope this is not too messy

How can I prepopulate the remainder of forms based on user input from a first form?

So what I'd like tot do is have a list of forms that show up based on what the user picked in a page before. Now after entering the information in the first form, I would like to give the option of repeating that information for the additional forms . Ex.:
activity 1
Name 1
Name 2
Email
activity 2
Name 1
Name 2
Email
You can see how it can become redundant and tedious if you sign up for many activities. How would I do this in django if possible or javascript if i need to or even html5.
You could do this with just HTML5 and JavaScript (I have no idea what Django is, but this'll be easier if Django is a server-side language that can access form data).
I would make the action attribute of the <form> element in the first webpage lead to the second webpage so that the second webpage would have the GET parameters of that form data, and then in the JavaScript of the second webpage, use those GET parameters to put in data into the form. Here's an example:
tester1.html:
[...]
<form action = "tester2.html">
<input name = "realname" />
<input name = "screenname" />
<input type = "submit" />
</form>
[...]
tester2.html:
[...]
<script>
var form;
window.onload = function() {
var url = document.location.href;
var keys = url.substring(url.indexOf("?")+1, url.length).split("&");
form = document.getElementsByTagName("form")[0];
for (var i = 0; i < keys.length; i++) form[keys[i].substring(0, keys[i].indexOf("="))].value = decodeURIComponent(keys[i].substring(keys[i].indexOf("=")+1, keys[i].length));
};
</script>
[...]
<form>
<input name = "realname" />
<input name = "screenname" />
<input type = "password" name = "password" />
<input type = "submit" />
</form>
[...]

Sending form array values trought ajax

So my php needs 2 values, operation => string and data => array. The following is the form (dynamically generated inputs) :
<form method="post" action="/operations.php">
Title: <input type="text" value="valuehere" name="data[title]">
.
.
.
Description: <textarea name="data[description]"></textarea><br>
<button class="btn janitor_edit" type="submit">Edit Media</button>
<input type="hidden" value="operateMePls" name="operation">
<input type="hidden" value="254" name="data[id]">
</form>
And now I have to create an array from all data[xyz] in the form, but I'm having trouble finding a way to do so. The closest I've come to was doing like so: link
I must store the array as key/values, no other way, so I can ajax_request = { operation: operation_input, data : input_array_data };.
Oh, and the form works as expected when submiting "normaly" trought POST.
If the form works by itself, then let jQuery take care of it converting the data into a form suitable for XHR for you.
data: $('#your_form').serialize();
I've used an object instead of an array. When you json_decode in PHP, pass "true" as your second argument, and the data will come out as an array. I think this is what you wanted. Please comment if you were looking for something different.
$(".janitor_edit").click(function () {
var data = {};
data.operation = $("input[name='operation']").val();
data.data.id = $("input[name='data\\[id\\]']").val();
data.data.title = $("input[name='data\\[title\\]']").val();
data.data.description = $("input[name='data\\[description\\]']").val();
});

Categories

Resources