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.
Related
Please guys i created a form validation program using html, css and javascript and i want the form to validate when they user input changes though i am not getting error but the form is not validating, can any one resolve my program and detect my mistakes
const loader = document.querySelector('.loader');
// selecting inputs
const submitBtn = document.querySelector('.submit-btn');
const names = document.querySelector('#name');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const num = document.querySelector('#number');
const tac = document.querySelector('#terms-and-con');
const notification = document.querySelector('#notification');
/// showalert function
const showAlert = (msg) => {
let alertMsg = document.querySelector('.alert-msg');
let alertBox = document.querySelector('.alert-box');
alertMsg.innerHMTL = msg;
alertBox.classList.add('show');
setTimeout(() => {
alertBox.classList.remove('show');
}, 3000)
}
/// send data function
const sendData = (path, data) => {
fetch(path, {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data),
}).then((res) => res.json()).then(response => {
processData(response);
})
}
/// submit button functionality
submitBtn.addEventListener('click', () => {
if (name.value.length < 3) {
// showAlert('name must be 3 letters long');(
alert('bad input')
} else if (!email.value.length) {
showAlert('enter your email');
} else if (password.value.length < 9) {
showAlert('password should be eight letters long');
}
})
this is the html program
<div>
<input type="text" autocomplete="off" id="name" placeholder="name">
<input type="email" autocomplete="off" id="email" placeholder="email">
<input type="password" autocomplete="off" id="password" placeholder="password">
</label>
<br>
<input type="checkbox" class="checkbox" id="notification">
<label for="notification">receive upcoming offers and events mails</label>
<button class="submit-btn">create account</button>
</div>
already have an account?. Login in here
</div>
<div class="alert-box ">
<img src="img/error.png" alt="" class="alert-image">
<p class="error-message alert-msg">
There is an error
</p>
</div>
i think here
if(name.value.length < 3){ // name.value.length should be names.value.length as its
// here const names = document.querySelector('#name');
// just a typo nothing to worry about your code should
// work
and a suggestion check all three fields seprately regardless of if name is fine then check email and if email is fine then check password, btw your code is just fine it should work
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.
I have change password html form. When user submits that form, I write another <p> </p> element to tell user changed his password or did not and add link to Login page. Both link to Login and Cancel button does the same - redirect to login page. However, after POST method when I click Cancel/redirect to login buttons the screen just keeps loading and never really redirects you there. If I click submit button once again, it sends POST request again so this button works fine no matter how many requests I send. What's wrong with redirection? I can't seem to figure that out. I checked that in Firefox and it seems to work there fine. My code is below:
document.getElementById("btn_cancel").onclick = function(event) {
window.location.href = "/login";
};
var token = window.location.href.substring(window.location.href.lastIndexOf("/") + 1);
function validate() {
var responseText = document.getElementById('error_id');
var password = document.forms["reset-pasword"]["new_password"].value;
var confirmPassword = document.forms["reset-pasword"]["repeat_password"].value;
if (password !== confirmPassword) {
error = "Passwords do not match";
responseText.innerHTML = error;
responseText.className = "error_text";
return false;
}
return true;
}
document.getElementById("btn_change").onclick = function(event) {
event.preventDefault();
var responseText = document.getElementById('error_id');
if (validate() != true)
return;
var password = document.getElementById("new_password").value;
var request = {
token: token,
password: password
};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/update', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = (res) => {
response = res['target']['response'];
if (response) {
response = JSON.parse(response);
responseText.innerHTML = response.message;
responseText.className = "error_text";
} else {
responseText.innerHTML = "Password changed succesfully. Login";
responseText.className = "success_text";
}
};
xhr.send(JSON.stringify(request));
};
<body onload="document.getElementById('reset-pasword').focus();">
<div class="box" id="change_password_panel">
<form name="reset-pasword" id="reset-pasword">
<label for="password">New password</label>
<input type="password" placeholder="New Password" id="new_password" name="new_password" required />
<label for="password">Repeat new password</label>
<input type="password" placeholder="Repeat Password" id="repeat_password" name="repeat_password" required />
<div style="width: 100%; display: inline-block;margin-top: 10px;">
<div style="float: left;"><button id="btn_change" class="button">Change password</button>
</div>
<div style="float: right;"><button id="btn_cancel" type="button" class="button">Cancel</button></div>
</div>
<p id="error_id"></p>
</form>
</div>
</body>
Also, if I click Cancel button first, before clicking Submit, redirection works fine.
If I put window.location.href = "/login"; inside xhr.onload in if and else statements it doesn't work either. So the problem is could be with POST method? I'm really lost with this one..
This is network when I click 'Cancel' before submitting form:
and this is after:
It doesn't even have 'login' in it...
I also tried
document.getElementById("btn_cancel").onclick = function (event) {
event.preventDefault();
fetch('/login/default.html')
.then(window.location.href = "default.html");
};
but it seems it just goes inside window.location.href and never goes out there
I had similar problem once and still I don't know what was wrong, but I solved this problem adding <a> tag agin adding event to the button.
document.getElementById("btn_cancel").innerHTML = "<a href='/login'>Cancel</a>";
Can you try
setTimeout(function(){document.location.href = "/login;"},500);
or
window.location.assign("/login");
I have page for changing password and after sending POST request to backend. I add additional element Login so that user could go back to login page and login. However neither this, nor Cancel button doesn't do anything. After I click on it the page starts loading but stays always the same - doesn't redirect to the login page. If I copy that link and open in new page and click Cancel then, it works fine. Here's my code:
document.getElementById("btn_cancel").onclick = function () {
window.location.replace("/login");
};
var token = window.location.href.substring(window.location.href.lastIndexOf("/") + 1);
function validate() {
var responseText = document.getElementById('error_id');
var password = document.forms["reset-pasword"]["new_password"].value;
var confirmPassword = document.forms["reset-pasword"]["repeat_password"].value;
if (password !== confirmPassword) {
error = "Passwords do not match";
responseText.innerHTML = error;
responseText.className = "error_text";
return false;
}
return true;
}
document.getElementById("btn_change").onclick = function (event) {
var responseText = document.getElementById('error_id');
if (validate() != true)
return;
var password = document.getElementById("new_password").value;
var request = {
token: token,
password: password
};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/v1/Auth/UpdatePassword', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = (res) => {
response = res['target']['response'];
if (response) {
response = JSON.parse(response);
responseText.innerHTML = response.message;
responseText.className = "error_text";
} else {
responseText.innerHTML = "Password changed succesfully. Login";
responseText.className = "success_text";
}
};
xhr.send(JSON.stringify(request));
event.preventDefault();
};
<div id="change_password_panel">
<form name="reset-pasword" id="reset-pasword">
<label for="password">New password</label>
<input type="password" placeholder="New Password" id="new_password" name="new_password" required />
<label for="password">Repeat new password</label>
<input type="password" placeholder="Repeat Password" id="repeat_password" name="repeat_password" required />
<div style="width: 100%; display: inline-block;margin-top: 10px;">
<div style="float: left;"><button id="btn_change" class="button" type="button">Change
password</button></div>
<div style="float: right;"><button id="btn_cancel" type="button" class="button">Cancel</button></div>
</div>
<p id="error_id"></p>
</form>
</div>
what could be wrong here?
Both cancel and Change password buttons seem same to me but I can click Change password multiple times and when I click cancel page just keeps loading.
I've also tried:
document.getElementById("btn_cancel").onclick = function (event) {
event.preventDefault();
window.location = "http://localhost:4200/";
};
nothing works...
Clicking on the cancel button works correctly.
As for the Change password button, check the xhr.onload function. On success, you need to render "Password changed succesfully. Login" inside in an html element; something like document.getElementById("resultDiv").innerHTML="Password changed succesfully. Login", at the moment you're just updating the value of responseText.innerHTML but responseText is not defined anywhere.
responseText is not defined. You are trying to change the text of same button so for that you need to have a reference of it.
<script type="text/javascript">
document.getElementById("btn_cancel").onclick = function () {
window.location.replace("/login");
};
var token = window.location.href.substring(window.location.href.lastIndexOf("/") + 1);
var button = document.getElementById("btn_change");
button.onclick = function () {
var password = document.getElementById("new_password").value;
var request = {
token: token,
password: password
};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/changePassword', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = (res) => {
response = res['target']['response'];
if (response) {
response = JSON.parse(response);
button.innerHTML = response.message;
button.className = "error_text";
} else {
button.innerHTML = "Password changed succesfully. Login"
button.className = "success_text"
}
};
xhr.send(JSON.stringify(request));
};
<div id="change_password_panel">
<form name="reset-pasword" id="reset-pasword">
<label for="password">New password</label>
<input type="password" placeholder="New Password" id="new_password" name="new_password" required />
<label for="password">Repeat new password</label>
<input type="password" placeholder="Repeat Password" id="repeat_password" name="repeat_password" required />
<div style="width: 100%; display: inline-block;margin-top: 10px;">
<div style="float: left;"><button id="btn_change" class="button" type="button">Change
password</button></div>
<div style="float: right;"><button id="btn_cancel" type="button" class="button">Cancel</button></div>
</div>
<p id="error_id"></p>
</form>
</div>
What do you want to do in onload callback? if you want to redirect to login page, you should use window.location.href
document.getElementById("btn_cancel").onclick = function (event) {
event.preventDefault();
window.location = "http://localhost:4200/";
};
You forgot href, window.location.href is right
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.