Concatenating to a URL from an input Form - javascript

I am making a web application in BOOTSTRAP/Javascript that retrieves high scores from a JSON and then checks for available quests.
Currently this is how I am set up in my javascript file
var baseURL = 'https://www.tip.it/runescape/json/hiscore_user?rsn=&old_stats=1';
var updatedURL =;
var requestURL = updatedURL;
var request = new XMLHttpRequest()
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var userStats = request.response;
}
function URLupdater() {
}
What I am trying to do is concatenate information from a input form on my html page,
<div id="Userinput" class="col-md-2">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"> <img src="/img/admincrown.gif~c200.gif" class="img-rounded" width="20" height="20"> </span>
<input type="text" class="form-control" placeholder="Runescape Username" aria-describedby="basic-addon1">
</div>
</div>
<div id="submitbutton" class="col-md-1"><button id="retrievestats" type="button" class="btn btn-default">Get Stats</button></div>
into the baseURL above after ?rsn=
I am currently attempting to make a function that reads the input on button click, then switches the url to the new one with the username in it and then continuing from there to retrieve the JSON Data. Am I thinking about this the right way or am I off track.

You mean what you are trying to achieve is as such? :
var baseURL = 'https://www.tip.it/runescape/json/hiscore_user?rsn=&old_stats=1&concatenatedData=1234';
If so, I don't see any issues with it. You seem okay to proceed.

Not future-proof
Assuming you only want to append a username to the URL, and don't need to manipulate it in any other way, you can perhaps do it like this:
function getUserData( user_name ) {
var requestURL = "https://www.tip.it/runescape/json/hiscore_user?old_stats=1&rsn=",
request = new XMLHttpRequest();
request.open( "GET", requestURL + encodeURIComponent( user_name ) );
// various sanitizations should be employed on the backend when dealing with user input
request.responseType = "json";
request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
var user_stats = request.responseText;
// process response
} else {
// handle errors
}
}
}, false );
request.send();
}
window.addEventListener( "DOMContentLoaded", function() {
document.getElementById( "retrievestats" ).addEventListener( "click", function() {
var user_input = document.querySelector( "#Userinput input[name=user_name]" ),
user_name;
if ( user_input ) {
user_name = user_input.value;
if ( user_name ) {
getUserData( user_name );
}
}
}, false );
}, false );
There are of course many other factors in reality and this is just a bunch of code, not the bunch of code.
HTML
Instead of wrapping your form in a <div>, you could consider using a <form>. It isn't vital, but makes sense and can be as simple as altering a few tags (and CSS).
<form id="Userinput" class="col-md-2">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"> <img src="/img/admincrown.gif~c200.gif" class="img-rounded" width="20" height="20"> </span>
<input name="user_name" type="text" class="form-control" placeholder="Runescape Username" aria-describedby="basic-addon1">
</div>
<div id="submitbutton" class="col-md-1">
<input id="retrievestats" type="button" class="btn btn-default" value="Get Stats">
</div>
</form>
Summary
As the code you provided and the limited explanation for its existence is obviously only a small part of a greater whole, there are too many variables to cover in one answer. As far as tacking a username onto a "GET" URL goes, this'll work. The rest - I can't say.

Related

Cannot set input value with JS if it has 'autocomplete=off' attribute

EDIT: I have added more code and edited description to help to better illustrate the problem.
I have an input element with an 'autocomplete=off' attribute. I want to refresh the page and set that input text value to what was in it before (don't want the user to lose input data), so I store the value in the 'sessionStorage' and try to set that element with the stored value after the refresh; After form submission my input element gets blank. If I change my HTML page removing the autocomplete, it works fine (the element gets the value stored in the sessionStorage) but I don't want the autocomplete function for that element. There's a way to implement this?
JS:
function submitForm(e, op, id=NaN){
//e is used to build var notification//
//gonna skip details for the sake of simplicity//
var notification = 'somejson'
var formData = JSON.stringify(notification);
var xhr = new XMLHttpRequest();
if (op == 'add'){
sessionStorage.setItem("pv", $('#pv').val());
var pv = sessionStorage.getItem("pv");
sessionStorage.setItem('reload', 'true')
xhr.open("POST", "/sms_service/notifications/add", true);
xhr.send(formData);
xhr.onload = function() {
if (xhr.status == 200){
window.location.href = "/sms_service/notifications";
}
else {
window.location.reload();
document.getElementById("pv").value = pv;
console.log('pv', pv);
}
}
}
}
HTML:
<form onsubmit="event.preventDefault()" action="" method="POST" id="addForm" novalidate>
<div id="container">
<div class="col-8">
<input type="text" class="form-control" id="pv" autocomplete="off" show="on">
</div>
<span>
<button class="btn btn-primary btn-user" type="submit" value='add'
onClick="submitForm(this, 'add')" >Submit</button>
</span>
</div>
</form>
your code may have set the input value, then reset when reloading
the solution is
call document.getElementById("pv").value = pv;
at the top of the code
var pv = sessionStorage.getItem("pv");
document.getElementById("pv").value = pv;
sessionStorage.setItem("pv", $('#pv').val());
sessionStorage.setItem('reload', 'true')
xhr.open("POST", "/sms_service/notifications/add", true);
xhr.send(formData);
xhr.onload = function() {
if (xhr.status == 200){
window.location.href = "/sms_service/notifications";
}
else {
window.location.reload();
}
}
the previous possibility worked because the autocomplete function did function to fill in frequently used inputs

How to send img to discord webhook with javascript

const params = new URLSearchParams(window.location.search);
$(document).ready(_ => {
if (params.get("url") != null) {
$("input")[0].value = params.get("url");
}
if (params.get("img") != null) {
$("input")[1].value = params.get("img");
}
});
let url;
let img;
let submit = _ => {
url = $("input")[0].value;
img = $("input")[1].value;
if (!url.length) {
return alert('Please enter URL');
}
}
let send = _ => {
$.ajax({
type: "POST",
url: url,
async: true,
data: {
file: (img)
},
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="box">
<p title="Webhook url to send spam message">Webhook URL</p><input required name="inp1" placeholder="https://discord.com/api/webhooks/........." type="url" autocomplete></input>
</div>
<div class="box">
<p title="Message you want to spam it">Image</p><input required name="inp2" placeholder="Image Link" type="file"></input>
</div>
<a onclick="submit()"><button id="button" >Send</button></a>
I want the attachment to be sent through the API in discord chat. I tried doing it like this but it doesn't work. The file:() I think might be the issue but also the input type I don't know
Without jQuery you might try something like this using the fetch api in conjunction with the FormData interface and the FileList
const d=document;
const q=(e,n=d)=>n.querySelector(e);
d.addEventListener('DOMContentLoaded', ()=>{
q('button#button').addEventListener('click', e=>{
e.preventDefault();
let url = q('input[name="inp1"]').value;
let files = q('input[name="inp2"]').files;
if (!url.length) return alert('Please enter URL');
let fd = new FormData();
fd.set('url', url);
fd.set('img', files.item(0));
fetch( url, { method:'post', body:fd } )
.then(r=>r.text())
.then(text=>{
alert(text)
})
})
});
<div class="box">
<p title="Webhook url to send spam message">Webhook URL</p>
<input required name="inp1" placeholder="https://discord.com/api/webhooks/........." type="url" autocomplete />
</div>
<div class="box">
<p title="Message you want to spam it">Image</p>
<input required name="inp2" placeholder="Image Link" type="file" />
</div>
<button id="button">Send</button>
The jQuery version is quite probably not quite correct as the snippet yields an error with the $.post method and being unfamiliar with jQuery I cannot see the mistake
const params = new URLSearchParams( window.location.search );
$(document).ready(() => {
let url;
let img;
let fd=new FormData();
if( params.get("url") != null ) {
$("input[name='inp1']")[0].value = params.get("url");
};
$('#button').click(e=>{
url = $("input[name='inp1']")[0].value;
img = $("input[name='inp2']")[0];
if( !url.length ) {
return alert('Please enter URL');
}
fd.set('url',url);
fd.set('img',img.files.item(0));
$.ajax({
type:"POST",
url:url,
data:fd,
success:r=>{console.log(r)},
error:e=>{console.warn(e)}
});
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="box">
<p title="Webhook url to send spam message">Webhook URL</p>
<input required name="inp1" placeholder="https://discord.com/api/webhooks/........." type="url" autocomplete />
</div>
<div class="box">
<p title="Message you want to spam it">Image</p>
<input required name="inp2" placeholder="Image Link" type="file" />
</div>
<button id="button">Send</button>
Worth noting perhaps is that you cannot set the value of a file input element programmatically - only the user can set this value by browsing for and selecting a file.

how to access a web page and change its inner contents using AJAX?

Here I'm trying to get the webpage and its contents and trying to modify the inner values and trying to post using ajax.
1.First I'm placing a url in first text box.
2.Then after clicking GET button, the html codes will be shown in 2nd text box..
3.After editing the codes, I'm trying to do post.
I tried to do this on an insecure web page(http) to train myself.. but didn't work.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
var url ="";
var both;
function rstSrv()
{
let request = new XMLHttpRequest();
url = document.getElementById('getURL').value;
both = proxyurl+url;
console.log("Cons1:::"+request);
setTimeout(function()
{
if(request.status==200)
{
console.log("Cons2::"+(request.response));
var list=request.response;
document.getElementById('getInnerHtml').value=list;
console.log(list);
document.getElementById('get').innerHTML=list;
}
else
{
//console.log(`error ${request.status} ${request.statusText}`)
var list=(`error ${request.status} ${request.statusText}`)
document.getElementById('get').innerHTML=list;
}
},2000);
request.open("GET",both, true);
request.send();
}
function postVal()
{
var pstFile=document.getElementById('getPostInnerHtml').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("get2").innerHTML = this.responseText;
}
};
xhttp.open("POST", both, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(pstFile);
alert("done");
}
<div style='length:100%;width:100%;overflow: auto'>
<div> Insert URL </div>
<input type="text" id="getURL" style=':50%;width:20%;overflow: auto'><br>
<button onclick="rstSrv()"> GET </button>
<div type="text" id="get" style='length:40%;width:100%'></div><br>
<div> Copy InnerHTML Values </div>
<input type="text" id="getInnerHtml" style=':50%;width:20%;overflow: auto'><br><br><br>
<div> Paste InnerHTML Values </div>
<input type="text" id="getPostInnerHtml" style=':50%;width:20%;overflow: auto'><br>
<button onclick="postVal()"> POST </button><br>
<div type="text" id="get2" style='length:40%;width:100%'></div><br>
</div>
I cant get what I did wrong. Can some one help me to sort it out.. Thanks in advance..

Filling the form I entered on my site on the other site

I am trying to auto-fill the form I entered from the site with javascript subdomains, but there is no problem like this.
When I Enter Date My URL:
www.example.com/example
But it works like this:
https://sub.example.com/example?from_date=21%2F02%2F2021&to_date=26%2F02%2F2021&num_adults=1&num_children=1&check_availabilities=
So when I enter a date in the subdomain, there is no parameter in the URL address. Is there any way I can pass this without parameters?
My Script and Form
function loadXMLDoc() {
var url = "http://example.com";
var parameters = "foo=bar&bar=baz"; // Construct you form values like field=value&field2=value2&...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
<div class="booknow-wrapper flexbox">
<div class="title" style="font-size: 26px; font-weight:600;"><span></span> </div>
<div class="col-auto">
<div class="booknow-card">
<div class="booknow-input">
<input type="date" name="from_date" id="arrival" value="from_picker" placeholder="Giriş Tarihi" required autocomplete="off">
</div>
</div>
</div>
<div class="col-auto">
<div class="booknow-card">
<div class="booknow-input">
<input type="date" name="to_date" id="departure" value="to_picker" placeholder="Çıkış Tarihi" required autocomplete="off">
</div>
</div>
</div>
And My Console Fetch
"referrer": "https://sub.exampla.com/booking",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": -
"from_date=15%2F02%2F2021&to_date=28%2F02%2F2021&num_adults=1&num_children=1&check_availabilities=",
"method": "POST",
As long as you are in the same domain and you want to propagate some data you filled in a page in your sub-domain, you can save the data in a browser storage, such as localStorage or sessionStorage:
// register changes
window.localStorage.setItem(name, value);
window.sessionStorage.setItem(name, value);
// retrieving data
window.localStorage.getItem(name)
window.sessionStorage.getItem(name)
You can see following code in the snippet, but it will not work since it is sandboxed and localStorage is not allowed. You can run a test on the same code on JSFiddle. I write the snippet here just for reference.
// select your elements
let btnInput = document.getElementById('storage_example_btn');
let btn = document.getElementById('save_btn');
let chgInput = document.getElementById('storage_example_change');
let shwRes = document.getElementById('show_results');
let results = document.getElementById('results');
// when click on "Save Data" button
btn.addEventListener('click', () => {
// save input data to storage
sessionStorage.setItem('__SO_EXAMPLE_1__', btnInput.value);
});
// when the "onChange" input changes
chgInput.addEventListener('change', () => {
// save input data to storage
sessionStorage.setItem('__SO_EXAMPLE_2__', chgInput.value);
});
// when click on "Show Storage" button
shwRes.addEventListener('click', () => {
// get input data from storage
let res1 = sessionStorage.getItem('__SO_EXAMPLE_1__')
let res2 = sessionStorage.getItem('__SO_EXAMPLE_2__')
// show it in the result div
results.innerHTML = 'Session Storage<br/>Data from "Save Data" Input: ' +
res1 + '<br/>Data from "onChange" Input: ' + res2
});
Register data with a button:
<input id="storage_example_btn" type="date"/>
<button id="save_btn">Save Data</button><br/>
Register data <code>onChange</code>:
<input id="storage_example_change" type="date" />
<br/><br/>
<button id="show_results">Show Storage</button>
<div id="results"></div>
As localStorage implements the same interface of sessionStorage you can choose which one to use, depending on your application. Check from docs the differences.

How to send multiple input values with same class name or id via ajax

I'm trying to send multiple input values via AJAX to my PHP script. It's working fine when I use getElementById. However I have the option to add a child. It iterates the input fields, then I get values only from the first child. I tried to use getElementsByClassName but it gives values as undefined. This is my code:
<div id="name-field" class="name-field row">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Name of child</label>
<input id="firstname" class="firstname" name="firstname" type="text" />
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" id="thedate" />
</div>
</div>
</div>
Add Child
Next Step
//Iterate child function
jQuery(function($) {
$("#addChild").click(function() {
$(".name-field:first").clone().find("input").val("").end()
.removeAttr("id")
.appendTo("#additionalselects")
.append($('<a class="delete" href="#"><i class="fa fa-times"></i></a>'));
});
$("body").on('click', ".delete", function() {
$(this).closest(".name-field").remove();
});
});
//Sending values function
function btnSubmit(step) {
//Set Var with Name
//Set Var with DoB
if (step == 'step1') {
//values using ID
var Name = document.getElementById("firstname").value;
var DoB = document.getElementById("thedate").value;
//Values using classname
var Name = document.getElementsByClassName("firstname").value;
var DoB = document.getElementsByClassName("date").value;
//Create a Variable catVar Having the Var Name and Var DoB Concatinated with a --
var stepVar = Name + "--" + DoB;
$(".thevoornaam, .date").each(function() {
alert();
});
} else {
}
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", "validations/btnSubmit.php?q=" + step + "&q2=" + stepVar, true);
xmlhttp.send();
}
I hope you guys understand what I'm trying to achieve with this, if I did't explain it correctly.
Thanks in advance.
using jQuery you can do it in this way.
var firstname = [];
$("#name-field .firstname").each(function(){
firstname.push($(this).val());
});
In firstname you will all the values.
Update
Here is a working pen.
https://codepen.io/smitraval27/pen/dmvwVB
document.getElementsByClassName("firstname")
returns an array... so the following will give you the elements value with index i. To get all the values you will need to do a ForEach.
document.getElementsByClassName("firstname")[0].value
Since you're using JQuery elsewhere, why not use...
$('.firstname')[0].val();
The most ideal way to do this is :
add a form wrapper to your fields (id="ajaxForm")
to have a name to all your form
fields and use the below code to generate the data to be passed to
your AJAX call
$("#ajaxForm").serialize()
The return value of $.serialize() can be directly used as the data for the ajax call
$("#ajaxForm").on("submit", function () {
var ajaxData = $("#ajaxForm").serialize();
$("#ajaxData").text(ajaxData);
$.ajax({
url:"",
type: "get",
data : ajaxData,
success: function (resp) {}
});
console.log(ajaxData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ajaxForm" onsubmit="return false" >
<input id="firstname" class="firstname" name="firstname" type="text" />
<input type="text" name="date" class="date" id="date" />
<input type="submit" value="submit">
</form>
<div id="ajaxData"></div>

Categories