How to submit form with concatenated URL? - javascript

I'm fairly new to the whole Javascript scene. Followed along with those online javascript tutorial things like code academy offers so I'm going by what I learned off of there and what I have read through other tutorials. Read though a few other posts to try and help me but I can't figure it out
So here's my question,
I am trying to take a form input, send it to a javascript file, then the javascript file returns a string which then I wish to reload the frame with. I'm attempting to make a simple chrome extension for me and my friends.
When I click "View Grade!" I get an error:
No webpage was found for the web address: chrome-extension://gcgddggimojbfgpbdmpfkmiofmpinjgb/location.href=getURL(account)?
and I can't determine if my javascript isn't working right or I just don't know how to send to a URL outside the "chromium" (as I call it) world.
This is my html file:
<form action="location.href=getURL('account')">
PSU Account (i.e. xyz123): <input type:"text" id="account">
<input type="submit" value="View Grade!">
</form>
And this is my javascript file:
function getURL(account) {
var psuAccount = document.getElementById(psuAccount);
// I changed strA to the ***.***.*** for this post
var strA = 'https://***.***.***/section/Gradebook/Student/default.aspx?userId=';
var strB = '&reportMode=true';
var newURL = strA + psuAccount + strB);
return(newURL);
}

I think this is exactly what <form>s are for...no need for Javascript for something like this. Try:
<form action="https://***.***.***/section/Gradebook/Student/default.aspx" method="GET">
PSU Account (i.e. xyz123): <input type="text" name="userId" />
<input type="hidden" name="reportMode" value="true" />
<input type="submit" value="View Grade!" />
</form>
The submit mechanism will automatically use the action attribute of the form. Since the method is "GET", it will also add a querystring of key/value pairs for elements in the <form> with a name attribute. So with your form, it will add a key "userId" with the value as the textbox's current value at time of submission. It will also add a key "reportMode" with the value "true". So the final URL that will be submitted is:
https://***.***.***/section/Gradebook/Student/default.aspx?userMode=true&userId=SOME_INPUT_STRING
If you need to use Javascript, try:
<div>
PSU Account (i.e. xyz123): <input type:"text" id="account" />
<input type="button" value="View Grade!" onclick="getURL();" />
</div>
with:
function getURL() {
var psuAccount = document.getElementById("account").value;
var strA = 'https://***.***.***/section/Gradebook/Student/default.aspx?userId=';
var strB = '&reportMode=true';
var newURL = strA + psuAccount + strB;
window.location.href = newURL;
}

Related

How to go to another html page with onsubmit without erasing data

My code will not work as I am trying to get my values to submit to another html page while keeping them. If I put a return false; it will go to the next HTML page without keeping the values; and if I don't have that it keeps the values without going to the next page. Please help if this is actually possible and if it is not please give me other suggestions.
document.getElementById('form').onsubmit = function(e) {
class matches {
constructor(name1, name2) {
this.name1 = name1;
this.name2 = name2;
}
}
const p1 = document.querySelector('#person1').value;
const p2 = document.querySelector('#person2').value;
const pair = new matches(p1, p2);
console.log(`${pair.name1} and ${pair.name2}`);
return false;
};
<div id="main-header">
<h1>Ship It! ❥</h1>
</div>
<div id="container">
<div id="title">
<h1>What is your magical Ship?</h1>
<form action="pages/lodaing.html" id="form"> <input type="text" placeholder="Your Firstname" id="person1" autocomplete="off">
<input type="text" placeholder="Their Firstname" id="person2" autocomplete="off"><br>
<button id="button" type="submit"><a href="/pages/lodaing.html"onclick="">&#9829</button>
</a>
</form>
</div>
</div>
If I need to add anything else please inform me. Sorry if I am not using the correct terms (I am new to the work).
Thank you!
Remove the code for onSubmit event listener
add name property to your input elements
HTML [Current page]
<form action="pages/lodaing.html" id="form">
<input type="text" placeholder="Your Firstname" name="person1"
autocomplete="off">
<input type="text" placeholder="Their Firstname" name="person2" autocomplete="off"><br>
<button id="button" type="submit">Submit</button>
</form>
You can write below code to get the input values of both inputs on next page
JS [Next page]
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var person1 = getParameterByName('person1');
var person2 = getParameterByName('person2');
console.log(person1,person2);
Explanation
What's happening here is,
The form on current page [HTML] submits a get request on 'pages/lodaing.html'
When a form is submitted using the 'Get' method [which is default] the new page is loaded with form values as query parameters created from form inputs [?param1=value1&param2=value2]
So, we wrote some script to get exact param values from the url on next page
Inside Javascript function, We pass the param name for which we need to get the value submitted
The function parses the url string for the pattern & searches for the key we pass & return the value for same
Hope this was easy to understand for you!
Making your form send values through a GET method (which is the default) you can use the Javascript URLSearchParams object on the next page, this object has all you need to handle your passed data. With this object you can avoid using the Javascript code on your first page, unless you need specific data checks and/or manipulation of course.
Checkout URLSearchParams here.
NOTE:
In your code you have to specify attribute name for the input fields whose value you want to pass to the other HTML page, as written the form is going to send nothing.

How to concatenate url with a variable everytime a login is made

The Wordpress site I'm working on:
http://www.careersroadmap.com/
After submission of a registration form, I have to redirect to this URL:
http://careertest.edumilestones.com/access-login-api.php?
However, during the redirect, I have to pass this variable to the URL:
category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere
So the final destination URL will be:
http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere
The access_code variable will change for each user that logs in.
I tried an AJAX call using the code below:
<script>
var startButton = document.getElementById("startButton");
startButton.addEventListener("click", getApiFunction());
function getApiFunction(){
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'http://careertest.edumilestones.com/access-login-api.php?category=2123&channel_id=371&cd=89&age=371&access_code=accesscodehere');
myRequest.onload= function(){
var myData = JSON.parse(this.response);
};
myRequest.send();
};
</script>
After trying the above code, I got the CORS policy error.
How do I accomplish this with Javascript or PHP??
I suppose you could add hidden inputs to the registration form.
Something along those lines:
<form action="http://careertest.edumilestones.com/access-login-api.php" method="GET">
<input type="hidden" name="category" value="2123">
<input type="hidden" name="channel_id" value="371">
<input type="hidden" name="cd" value="89">
<input type="hidden" name="age" value="371">
<input type="hidden" name="access_code" value="democodesjam12474">
</form>
A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.
Read more about it here: https://www.w3schools.com/tags/att_input_type_hidden.asp

How can I make a search bar with an <input> button open a domain if entered?

I currently have this code for a custom DuckDuckGo search bar:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>
It automatically opens the URL https://duckduckgo.com/?q={{SEARCH}} when you enter text in the box and press the enter key.
How could I make this bar go to a domain if one is entered? Optimally, it wouldn't validate the domain, just if it sees a string in the pattern xxxx.* with no spaces, it would open that page in a new tab.
Thank you for any help!
One way to solve it is by capturing the submit event of the form, analyze the input value and when it is a domain, open a new window with the domain and cancel the submit by returning false. In case of not being a valid domain, let the form proceed as usual by returning true.
Your html:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>
Your javascript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}
So one way to handle it is to use an if condition and check the string against a RegExp that recognizes domain names.
Here's a nifty one you can use:
/[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
I assume you don't need help getting the value from your text field or the actual redirection. However, if you needed more help, comment below and I'll post a more complete answer. The code below should help you get to where you want:
var domainRegExp = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
var pass = domainRegExp.test('test.com')
var fail = domainRegExp.test('test')
console.log(pass, 'pass')
console.log(fail, 'fail')
So as you can see the value inside the 'pass' variable is true, and 'fail' is false.

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

Categories