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
Related
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.
I'm creating a login where you click on a button and it shows the login via $("#loginbox").show();, I want to show the contents in loginbox/<div class="loginContainer"> in a popup window. I've been trying to use window.open() but I don't think it'll work for what I want.
my code:
const $document = $(document);
const $login = $("#login");
const $loginBox = $("#loginbox");
const $formElement = $(`
<div class="loginContainer">
<label for="userNameBox"><b>Username: </b></label>
<input type="text" class="userName"id="userNameBox" placeholder="Enter Username"required="required">
<input type="button" class="loginButton" id="loginButton" value="Login"/>
</div>
`);
$document.on("click", "#loginButton", function() {
const $userNameBox = $("#userNameBox");
if ($userNameBox.val() !== "") {
location.href = "mylink.com";
} else {
alert("Please Enter a Username.");
location.reload();
}
});
$('.login').click(function(e) {
if ($loginBox.children().length === 0) {
$loginBox.append($formElement);
}
$("#loginbox").show();
event.preventDefault();
return false;
});
So basically i am trying to implement 2checkout in my website and i have done everything from documentation but i get this error: TwoCheckoutException: Bad request - parameter error. I tried checking and playing with private/public keys and id but when i change them it says "authoization error" so i am sure they are okay. I read about addresses and everything and i have changed them but still not working.
Here is my full code:
#{
ViewData["Title"] = "Test";
}
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<h2>Test</h2>
<form id="myCCForm" action="/Home/SubmitCard" method="post">
<input name="token" type="hidden" value="" />
<div>
<label>
<span>Card Number</span>
<input id="ccNo" type="text" value="" autocomplete="off" required />
</label>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
<input id="expMonth" type="text" size="2" required />
</label>
<span> / </span>
<input id="expYear" type="text" size="4" required />
</div>
<div>
<label>
<span>CVC</span>
<input id="cvv" type="text" value="" autocomplete="off" required />
</label>
</div>
<input type="submit" value="Submit Payment" />
</form>
<script type="text/javascript">
// Called when token created successfully.
var successCallback = function (data) {
var myForm = document.getElementById('myCCForm');
// Set the token as the value for the token input
myForm.token.value = data.response.token.token;
// IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function (data) {
if (data.errorCode === 200) {
alert("Error 200");
// This error code indicates that the ajax call failed. We recommend that you retry the token request.
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function () {
// Setup token request arguments
var args = {
sellerId: "901417674",
publishableKey: "309FC596-8380-4B6F-B269-3E157A5A5D0B",
ccNo: $("#ccNo").val(),
cvv: $("#cvv").val(),
expMonth: $("#expMonth").val(),
expYear: $("#expYear").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function () {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#myCCForm").submit(function (e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>
and here is server side code:
public IActionResult SubmitCard()
{
TwoCheckout.TwoCheckoutConfig.SellerID = "901417674";
TwoCheckout.TwoCheckoutConfig.PrivateKey = "4E704021-B233-435F-A904-47B2620B9E66";
TwoCheckout.TwoCheckoutConfig.Sandbox = true;
try
{
TwoCheckout.AuthBillingAddress Billing = new TwoCheckout.AuthBillingAddress();
Billing.addrLine1 = "123 Main Street";
Billing.city = "Townsville";
Billing.zipCode = "43206";
Billing.state = "Ohio ";
Billing.country = "USA";
Billing.name = "Joe Flagster";
Billing.email = "Ex#a.com";
Billing.phoneNumber = "065";
TwoCheckout.ChargeAuthorizeServiceOptions Customer = new TwoCheckout.ChargeAuthorizeServiceOptions();
Customer.total = 1;
Customer.currency = "USD";
Customer.merchantOrderId = "12";
Customer.billingAddr = Billing;
Customer.token = Request.Form["token"];
TwoCheckout.ChargeService Charge = new TwoCheckout.ChargeService();
var result = Charge.Authorize(Customer);
return View("Success", result);
}
catch(TwoCheckout.TwoCheckoutException ex)
{
return View("Error", ex.ToString());
}
}
and here is all info from my sandbox:
You may need to update your site settings for sandbox from Site Management -> Site Settings and Turn to On for Demo Settings and check again
May it helps you
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 was trying to do the form submit response, like on submit the form fields should be hidden and to show the thank you message without refreshing the page, but when i click submit the page is getting refreshed and showing the ajax response {"result":"success","data":"{\"message\":[\"sample message\"]}"
tried using Send Email from a Static HTML Form using Google Apps Mail!
(function() {
'use strict';
function getFormData(form) {
var elements = form.elements;
var fields = Object.keys(elements).filter().map(function(k) {
if (elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
} else if (elements[k].length > 0) {
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name) {
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
//formData.formGoogleSend = form.dataset.email || ""; // no email by default
formData.formPage = form.dataset.page || "";
}
function handleFormSubmit(event) {
if (this.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
this.classList.add('was-validated');
} else if (this.checkValidity() === true) {
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
}
function loaded() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener("submit", handleFormSubmit, false);
});
}
document.addEventListener("DOMContentLoaded", loaded, false);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>
I expect to show the thankyou message without refreshing the page but the actual result is the page getting refreshed and showing the Ajax response
move event.preventDefault(); out of the if statement so the default submit action of the form is never triggered. You don't want to do an submit when you do an ajax request since the submit action will navigate to the form action url.
$('.needs-validation').on('submit', handleFormSubmit);
function handleFormSubmit(event) {
event.preventDefault();
if (this.checkValidity() === true) {
//Do this in the ajax succes event handler
$('.thankyou_message').show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>