Error stopping function after alert message is shown - javascript

I'm developing a proxy service and everything works great. When you press the submit button, it has an onclick function. I also now have it detecting when adblock is enabled, and I don't want the funcion to go through if adblock is detected, (meaning I want it so the proxy won't actually start if you have adblock enabled, and I want the alert message to pop up ONLY when you press the button UNTIL you disable adblock.)
If you have adblock, here's an example of what I'm looking for. (http://fastp.org/) On this website, if you have adblock enabled, you can't submit the form. Mine still goes through after you press "ok" on the alert box. In my javascript code I tried doing a "return false;" and also a "else" but nothing seems to work. I don't want the form to submit if you have adblock enabled.
I want it so if adblock is enabled, it will show the alert box, and when you press "ok" I don't want it to still launch the proxy in the new tab. I want it to launch when adblock is disabled.
Here's my code:
$(document).ready(function() {
$('#browsebtn').click(function() {
val = $('#urlinput').val();
$('#urlinput').val(val.replace($('#remove1').val(), ""));
});
});
$(document).ready(function() {
$('#browsebtn').click(function() {
val = $('#urlinput').val();
$('#urlinput').val(val.replace($('#remove2').val(), ""));
});
});
$(document).ready(function() {
$('#browsebtn').click(function() {
val = $('#urlinput').val();
$('#urlinput').val(val.replace($('#remove3').val(), ""));
});
});
function forceLower(strInput) {
strInput.value = strInput.value.toLowerCase();
}
function checkAdBlocker() {
try {
fetch(
new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
method: 'HEAD',
mode: 'no-cors'
})).catch(error => {
showNotification();
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification();
}
var x;
x = document.getElementById("urlinput").value;
if (x == "" || x == "https://" || x == "http://" || x == "www." || x == "http://www." || x == "https://www.") {
$("#error").show().delay(3000).fadeOut();
return false;
} else {
var ddl = document.getElementById("servertype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "server1") {
setTimeout(function() {
window.open('http://server1.com/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server2") {
setTimeout(function() {
window.open('http://server2.com/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server3") {
setTimeout(function() {
window.open('http://server3.com/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server4") {
setTimeout(function() {
window.open('http://server4.com/' + document.getElementById('urlinput').value);
}, 200);
}
}
}
function showNotification() {
alert("Please disable adBlocker");
}
<form action="javascript:void(0);" method="POST">
<input id="remove1" type="hidden" value="https://" /><input id="remove2" type="hidden" value="http://" /><input id="remove3" type="hidden" value="www." />
<input type="text" name="name" placeholder="Enter web address.." id="urlinput" onkeyup="return forceLower(this);" /><button type="submit" id="browsebtn" onclick="return checkAdBlocker()" name="submit" value="Browse">BROWSE</button>
<div class="serverselect"><label>Select Server:</label></div>
<div class="selectserver">
<select id="servertype" name="dropdown">
<option value="server1" data-sort="1">πŸ‡ΊπŸ‡Έ US Server</option>
<option value="server2" data-sort="2">πŸ‡¨πŸ‡¦ CA Server</option>
<option value="server3" data-sort="3">πŸ‡©πŸ‡ͺ DE Server</option>
<option value="server4" data-sort="4">πŸ‡¬πŸ‡§ GB Server</option>
</select>
</div>
<p id="error">Please enter a valid URL address.</p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Sorry, yes I know the code is long, but I wanted to make sure the new code wouldn't affect any code that was left out. (everything is sort of looped together) Thanks for taking a look.

In similar cases I usually use try...catch in while loop as track it with variable:
while (true) {
var adBlocker = false
try {
fetch(
new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
method: 'HEAD',
mode: 'no-cors'
})).catch(error => {
showNotification();
adBlocker = true
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification();
adBlocker = true
}
if (adBlocker == false) {
break
}
}
UPDATE:
fetch is async function so adBlocker variable is false and the loop is broken before cathing error
In this code I made fetch In async function to be able to use await and call redirect from then method that works on fetch success:
function checkAdBlocker() {
async function AdBlock() {
try {
// Wait for fetch
let adTest = await fetch("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js")
.then(response => {
redirect()
adBlocker = false;
})
.catch(error => {
showNotification();
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification();
}
}
AdBlock()
function redirect() {
var x;
x = document.getElementById("urlinput").value;
if (x == "" || x == "https://" || x == "http://" || x == "www." || x == "http://www." || x == "https://www.") {
$("#error").show().delay(3000).fadeOut();
return false;
} else {
var ddl = document.getElementById("servertype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "server1") {
setTimeout(function () {
window.open('https://devoooo-proxy.herokuapp.com/proxy/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server2") {
setTimeout(function () {
window.open('https://google-github.herokuapp.com/http/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server3") {
setTimeout(function () {
window.open('https://proxy.bibliotecavirtualalergia.com/browse.php?u=http://' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server4") {
setTimeout(function () {
window.open('http://server3main.epizy.com/browse.php?u=http://' + document.getElementById('urlinput').value);
}, 200);
}
}
}
}

Related

Open new tab onclick JS event using handler ashx

I have a login button with onclick event...onclick = "login();"
I successfully logged in ...but I wanted to open new tab instead.
This is my javascript:
login = function() {
if ($("#UserName").val().length == 0) {
return;
}
if ($("#Password").val().length == 0) {
return;
}
var logindata = new Object();
logindata.UserName = $("#UserName").val();
logindata.Password = $("#Password").val();
locustraxx.showLoading("loginformDiv");
locustraxx.doAjaxPostback('//example.com/LoginHandler.ashx', logindata, null, null,
function(data, textStatus, jqXHR) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (data.success == true) {
if ($("#Remember").is(':checked')) {
$.cookie('remember', $("#UserName").val() + '|' + $("#Password").val(), {
expires: 36500,
path: '/'
});
}
var retUrl = $.QueryString("ReturnUrl");
if (retUrl == undefined || retUrl == null) {
window.location.replace(data.data, '_blank');
} else {
window.location.href = decodeURIComponent(retUrl).replace(/\~~/g, ".");
}
if (isChrome) {
// clearCookies();
}
return false;
} else {
alert(data.message);
$("#UserName").focus();
}
}, null,
function() {
login.hideLoading("loginformDiv");
});
}
I tried _blank... window open, but to no avail
Could you please specify better what you have tried so far in theory you should be OK with:
window.open('https://www.google.com', '_blank');
If It isn’t working please specify the error output of the console.
There is also a known issue in which the browser opens a new window instead of a new tab, but that has to do with the user preferences, nothing to do about that. See here.

How to validate form based on values and submit call out to another page accordingly?

How can I pause submission so that I can validate, check values, and possibly submit an xhtml callout based on the choices all before allowing the form to finally submit?
Have tried using various jquery methods found on here, using callbacks, setting timeouts, and holding in a while loop until everything's done. A lot of the alerts found in the code are only for troubleshooting/tracing purposes.
function completeTicket() {
alert("fnOpenDiag Called");
$("#dialog-confirm").html("Auto create return eTicket?");
// Define the Dialog and its properties.
$("#dialog-confirm").dialog({
resizable: false,
modal: true,
title: "Auto create return eTicket?",
height: 250,
width: 400,
buttons: {
"Yes": function () {
var quickissue = "Return <?php echo ($ticketRow['items_count'] >= 1 ? $ticketRow['items'] : 'Computer'); ?>";
var selectedLocation2 = <?php echo ($ticketRow['Location_ID'] == '' ? 0 : $ticketRow['Location_ID']); ?>;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null) {
alert ("This browser does not support XMLHTTP!");
}
var url="xhtmlCallOut_QuickEticket.php?callerID=pc_ticket_detail&selectedLocation_ID=" + selectedLocation2 + "&tboxIssue=" + quickissue;
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
if (xmlhttp.readyState==4){
if (xmlhttp.responseText != 0){
alert(xmlhttp.responseText);
}
}
alert("ticket success");
return true;
$(this).dialog('close');
//callback(true);
//callback();
},
"No": function () {
return true;
$(this).dialog('close');
//callback(false);
//callback();
}
}
});
}
function checkForm() {
alert("checkform called");
if(document.getElementById('assocCompany').selectedIndex == 0) {
alert('Please associte this company with a known company name\nfrom the drop list.');
document.getElementById('assocCompany').focus();
e.preventDefault();
return false;
}
else if(document.getElementById('assignTech').selectedIndex == 0 && document.getElementById('status').selectedIndex >= 2){
alert('You must define a technician first!');
document.getElementById('assignTech').focus();
e.preventDefault();
return false;
}
else if(RegisterForm.elements['status'].value == 3 && RegisterForm.elements['tboxreaspend'].value.length < 3){
alert('You must give a reason for this ticket being changed to pending');
document.getElementById('tboxreaspend').focus();
e.preventDefault();
return false;
}
else if(RegisterForm.elements['tboxissue'].value.length < 3){
alert('You must give a description of the issue');
document.getElementById('tboxissue').focus();
e.preventDefault();
return false;
}
else {
pc_ticketdetail.actionbutton.disabled=true;
return false;
}
}
function showPendingReason() {
var y = document.getElementById("status");
var val = y.options[y.selectedIndex].value;
if (val == 3) {
$('#trReasPend').show();
} else {
$('#trReasPend').hide();
}
}
function submitForm() {
alert("submitform called");
var x = document.getElementById("status");
var valx = x.options[x.selectedIndex].value;
alert("statval is " + valx);
if (valx == 4) {
if (completeTicket()) {
e.preventDefault();
return false;
alert("complete ticket done");
} else {
e.preventDefault();
return false;
}
} else {
if (checkForm()) {
e.preventDefault();
return false;
alert("checkform done");
} else {
alert("checkform FALSE return");
e.preventDefault();
return false;
}
}
}
<div id="dialog-confirm"></div>
<form action="<?php $_SERVER['PHP_SELF']; ?>" name="pc_ticketdetail" id="pc_ticketdetail" method="post" onSubmit="return submitForm();">
<select name="status" id="status" onChange="javascript:showPendingReason();">
<option<?php if($ticketRow['status'] == 1){ echo ' selected'; } ?> value="1">New</option>
<option<?php if($ticketRow['status'] == 2){ echo ' selected'; } ?> value="2">Bench</option>
<option<?php if($ticketRow['status'] == 3){ echo ' selected'; } ?> value="3">Pending</option>
<option<?php if($ticketRow['status'] == 4){ echo ' selected'; } ?> value="4">Finished</option>
<?php if($ticketRow['status'] == 5){
echo '<option selected value="5">Closed/Deleted</option>';
} ?>
</select>
It currently seems to step through as expected except the "completeTicket" and "checkForm" functions are either not being called or not returning correctly. The form simply submits and closes when they should fail validation or open the modal dialogue and ask to create return ticket.
Take a look on the (async - await) function in javaScript.
async function
your checkForm() never return false so is your completeTicket() never return true. you can initially define a variable as false and make it true if it meets a specific condition then return the variable to the main function.
<script>
function c(){
let isTrue = false;
if(condition){
isTrue = true;
}
return isTrue;
}
function d(){
if(c()){
alert("c returned true");
} else{
alert("c returned false");
}
}
</script>
If you remove the alerts from under the return statements, that would help you in tracing the problem, because no code will run after you return from a function. Same thing for $(this).dialog('close').
And I think that you should capture the event object before using it in e.preventDefault() so try to remove the onSubmit attribute from the form and adding the listener through jQuery like so :
$(YOUR_FORM_SELECTOR).submit(function(e) {
// here you access to the e Object
})
I don't know if that related to the problem you have, Try describing what's happening exactly when you run the code.

redirect checked checkbox with php and make it work

How can i make it work with php code this code, the code is about if you checked will redirect to another website but i want to create checked option with url: https://example.com/index.php?checked1
First Line of code
if (isset($_GET['checked1'])) {
$showcheck = 'checked';
}
And javascript code below both codes are in one file index.php
<input <?=$showcheck?> type="checkbox" onclick="handleClick(this)">Redirect me after 30s<br>
<script>
let handleClick = (ele) => {
if (ele.checked) {
redirectTime = setTimeout(() => {
window.location = "/menu.php"
}, 30000)
} else if (!ele.checked && typeof redirectTime !== 'undefined') {
clearTimeout(redirectTime);
}
}
</script>
with php is not starting redirecting after 30s
You've said window.location = "/", which navigates to /, not to /index.php?checked1=anything.
try this:
<?
if (isset($_GET['checked1'])) {
$showcheck = 'document.getElementById("test").click();';
}
?>
<input type="checkbox" id="test" onclick="handleClick(this)">Redirect me after 30s<br>
<script>
let handleClick = (ele) => {
if (ele.checked) {
redirectTime = setTimeout(() => {
window.location = "/menu.php"
}, 30000)
} else if (!ele.checked && typeof redirectTime !== 'undefined') {
clearTimeout(redirectTime);
}
}
<?=$showcheck?>
</script>

Contact Form Backend needed, Frontend given

I used to host a website at carrd.co with the pro plus plan. I chose the expensive plan because of the possibility to download the website and host it on an own server.
What I did not know, was that this did not include server-side code.
My problem is, that I have the front end code, but every PHP code I try fails to interact with this code. Since I can only develop with Java, I cannot get to a solution by myself.
The issue is that I do not know what the next step is to make this code work on my server so that it successfully sends me an email when this form is submitted by a user. I do not have any backend code and do not know where to start.
1) where can i put a PHP file to answer to this request? How do i have to name it?
2) how can i parse the arguments?
3) how do i have to format the answer from the php script to the ajax script?
Could you guys please help here? Thanks a lot!!!
(i might even be able to solve this with some good hints if you cannot be bothered to provide a full solution! I'm thankful for any advice!)
The frontend code:
Form:
<form id="form02" method="post">
<div class="inner">
<div class="field"><input type="text" name="name" id="name" placeholder="Name"
maxlength="128"/></div>
<div class="field"><input type="email" name="email" id="email"
placeholder="Email" maxlength="128"/></div>
<div class="field"><input type="text" name="fname" id="-fname" placeholder="Fname"
maxlength="128"/></div>
<div class="field"><textarea name="message" id="message" placeholder="Message"
maxlength="16384"></textarea></div>
<div class="actions">
<button type="submit">Send Message</button>
</div>
</div>
<input type="hidden" name="id" value="form02"/>
</form>
Script:
function form(id, settings) {
var _this = this;
this.id = id;
this.mode = settings.mode;
this.method = settings.method;
this.success = settings.success;
this.preHandler = ('preHandler' in settings ? settings.preHandler : null);
this.failure = ('failure' in settings ? settings.failure : null);
this.optional = ('optional' in settings ? settings.optional : []);
this.$form = $('#' + this.id);
this.$form.addEventListener('submit', function (event) {
_this.submit(event);
});
this.$form.addEventListener('keydown', function (event) {
if (event.keyCode == 13 && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
_this.submit(event);
}
});
var x = $('#' + this.id + ' input[name="' + settings.hid + '"]');
if (x) {
x.disabled = true;
x.parentNode.style.display = 'none';
}
this.$submit = $('#' + this.id + ' button[type="submit"]');
this.$submit.disabled = false;
};form.prototype.notify = function (type, message) {
if (message.match(/^(#[a-zA-Z0-9\_\-]+|[a-z0-9\-\.]+:[a-zA-Z0- 9\~\!\#\#$\%\&\-\_\+\=\;\,\.\?\/\:]+)$/)) location.href = message; else alert((type == 'failure' ? 'Error: ' : '') + message);
};
form.prototype.submit = function (event) {
var _this = this, result, handler, fd, k, x, $f, $ff;
event.preventDefault();
if (this.$submit.disabled) return;
result = true;
$ff = this.$form.elements;
for (k in $ff) {
$f = $ff[k];
if ($f.type != 'text' && $f.type != 'email' && $f.type != 'textarea' && $f.type != 'select-one') continue;
if ($f.disabled) continue;
if ($f.value === '' || $f.value === null) {
if (this.optional.indexOf($f.name) !== -1) continue;
result = false;
} else {
x = '';
switch ($f.type) {
case 'email':
x = "^([a-zA-Z0-9\\_\\-\\.\\+]+)#([a-zA-Z0-9\\- \\.]+)\\.([a-zA-Z]+)$";
break;
case 'select':
x = "^[a-zA-Z0-9\\-]$";
break;
default:
case 'text':
case 'textarea':
x = "^[^\\<\\>]+$";
break;
}
result = result && $f.value.match(new RegExp(x));
}
if (!result) break;
}
if (!result) {
this.notify('failure', 'Missing and/or invalid fields. Please try again.');
return;
}
if (_this.method == 'get') {
_this.$form.submit();
return;
}
if (x = $(':focus')) x.blur();
this.$submit.disabled = true;
this.$submit.classList.add('waiting');
handler = function (values) {
var x, k, data;
data = new FormData(_this.$form);
if (values) for (k in values) data.append(k, values[k]);
x = new XMLHttpRequest();
x.open('POST', ['', 'post', _this.mode].join('/'));
x.send(data);
x.onreadystatechange = function () {
var result = false, message = 'Sorry, something went wrong. Please try again later.', alert = true, o;
if (x.readyState != 4) return;
if (x.status == 200) {
o = JSON.parse(x.responseText);
if (o) {
if ('result' in o) result = (o.result === true);
if (('message' in o) && o.message) message = o.message;
if ('alert' in o) alert = (o.alert === true);
}
}
_this.$submit.classList.remove('waiting');
if (result) {
_this.$form.reset();
if (alert) window.alert(message); else _this.notify('success', (_this.success ? _this.success : message));
} else {
if (alert) window.alert(message); else _this.notify('failure', (_this.failure ? _this.failure : message));
}
_this.$submit.disabled = false;
};
};
if (_this.preHandler) (_this.preHandler)(_this, handler); else (handler)();
};
new form('form02', {mode: 'contact', method: 'post', hid: 'fname', success: '#contact-done',});
An html form normally uses an action parameter to specify a url for the script to submit the form data to. However it looks like your javascript code is hard-coded to create an ajax post back to a url at /post/contact, which may explain why the examples you have tried do not work.
Yes, you do need a script of some kind on your server to process the response, but it doesn't have to be PHP - whatever your hosting provider supports, and whatever is capable of handling what you want to do with the data.

Return false is not prevent calling form submitting in javascript

On a form submit I am calling following function.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for(var i = 0, l = checkboxs.length; i < l; i++) {
if(checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if(checkedAtLeastOne) {
if(!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "checkreportid.action?reportId=" + reportId, true);
xhttp.send();
xhttp.onreadystatechange = function (e) {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("checkreportid").innerHTML = xhttp.responseText;
var reportid = $('#reportid').val();
console.log("reportId->" + reportId);
console.log("reportid->" + $('#reportid').val());
if(reportid == reportId) {
alert("Duplicate Report ID!");
return false;
} else {
return true;
}
}
}
}
} else {
alert("You must select atleast one column");
//e.preventDefault();
return false;
}
}
Here if the reportid equals to reportId it gives the alert (Duplicate Report ID) but it calls the action. return false is not prevent calling the action.
I am calling the function as below.
<s:form action="savereport" namespace="/" validate="true"
onsubmit="return confirmSubmit()">
EDITED
Now I am trying following. If the report ID is empty it gives relevant alert message (Report ID cannot be empty). It it is not empty it calls the checkreportid action but it doesn't give duplicate error message even if there are duplicate report ids. It calls the form submitting action.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if (!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
////////
$.ajax({
url: "<s:url action='checkreportid'/>",
type: "GET",
data: {reportId: reportId},
dataType: "text/javascript",
traditional: true,
statusCode: {
200: function (data) {
console.log(data.responseText);
document.getElementById("checkreportid").innerHTML = data.responseText;
var reportid = $('#reportid').val();
console.log("reportId->"+reportId);
console.log("reportid->"+reportid);
if (reportid==reportId) {
alert("Duplicate Report ID!");
return false;
} else {
if (!checkedAtLeastOne) {
return true;
} else {
alert("You must select atleast one column");
return false;
}
}
}
}
});
}
}
What am I missing with my code ?
This is due to the asyncronous nature of a XMLHttpRequest. You are returning false in a callback function, not in the onsubmit handler.
You should look into doing what you want without an XMLHttpRequest or use a syncronous request (this is not reccomended and disabled in some browsers).
The reccomended option is to stop the form submitting all the time with
e.preventDefault();
return false;
And to manually submit the form with a XMLHttpRequest in the original callback if you want to.
The reason is that XMLHttpRequest is aysnchronous.
Your call to
xhttp.send();
returns immediately and therefore that if-else branch doesn't have a return false.
The return statements in your code boil down to:
if(checkedAtLeastOne) {
if(!reportId) {
return false;
} else {
}
} else {
return false;
}
You should add preventDefault method to the form element like below.
<form onsubmit='event.preventDefault(); return confirmSubmit();'>
<input type='submit' />
</form>
Use return in onsubmit event to trigger return false action,
<form onsubmit = "return confirmSubmit()">
</form>

Categories

Resources