Javascript function running after return false - javascript

In my code, when a select box is changed, a js function (ConfirmDelete) is called which asks the user if they are sure they want to change the select box. If the user selects no, it will return false and would normally stop the execution.
My problem is that I also have another AJAX/JS function defined after this that is waiting for the select box to be changed and if it is, it sends details to a php script which adds a record into a mysql database.
I'd like to know if there is anyway that I can stop the AJAX/JS code from running after a user has selected No.
The JS function
function ConfirmDelete()
{
var x = confirm("Are you sure?");
if (x)
return true;
else
return false;
}
The AJAX/JS function
$( ".dropdown" ).change(function() {
var request = new XMLHttpRequest();
var id = this.value;
var content = this.name;
request.open("POST", "samefile.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
}
}
request.send("id="+id+"&content="+content);
window.location.reload();
window.location.reload();
}
);
The HTML Select box
<select class="dropdown" name="09:00-1-0-16-05-26" Onchange="return ConfirmDelete();">
<option class="co0es0sp1fd1oo0fs0" value="47">mike berry</option>
<option value="cancel-47">Cancel</option></select>
The order of the html is
JS Function defined in header
HTML code
AJAX/JS Script tag after

The AJAX/JS function
$( ".dropdown" ).change(function() {
if(!ConfirmDelete()) return; // right here, use this to confirm
var request = new XMLHttpRequest();
var id = this.value;
var content = this.name;
request.open("POST", "samefile.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
}
}
request.send("id="+id+"&content="+content);
window.location.reload();
window.location.reload();
}
);
Adding onchange event directly in HTML does not solve the problem.
Use this instead;

Related

What is wrong with my Ajax Javascript when submitting or displaying a form?

The code below SHOULD be opening an 'add' form and allowing Ajax to send the response back to the server. I'm a bit of a newb when it comes to this and I can't find what's wrong with it. In the Developers Console, it says the problem is with the xhr.send(); line. Can you tell me what I need to change to get this to work?
function DisplayForm() {
var div = document.getElementById("formDiv");
div.classList.toggle("show");
div.innerHTML = '<img class="loadingImg" src="images/loading.gif" alt="Loading..." height="60" width="60" border="0">';
var xhr = new XMLHttpRequest();
xhr.open('GET', "add.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
DisplayAfterLoad(data);
var button = document.getElementById("saveForm");
button.addEventListener("click", function(event) {
event.preventDefault();
recordAdd();
});
}
}
}
xhr.send();
}
It shows the "loading.gif" but does nothing else.

Auto Link shorting via PHP&AJAX (bit.ly)

I would like to build a form (VIA POST METHOD) with just one field (url - link shortening). Now the question is how and if is it possible to build a form that detects the value of the URL field is a link and automatically shortens it rather than waiting you click Send (for exmaple like the web of Bit.ly).
The main idea is once the field is an identifier that value is a proper Hyperlink is directly sends and shortens (And the field is replaced by a shortened link) it without waiting for the click on the SEND.
index.html
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a url in the input field below:</b></p>
<form>
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>
gethint.php
<?php
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
if (!filter_var($q, FILTER_VALIDATE_URL) === FALSE) {
// short the link
$rand = rand(1,1000);
$hint = 'http://domain.com/'.$rand; }
echo $hint === "" ? "Not a valid URL" : $hint; ?>
I'd use jQuery for the event triggering/AJAX and https://gist.github.com/dperini/729294 for weburl regex.
I'm not that at home on pure JavaScript AJAX calls, but is
xmlhttp.open("GET")
the right way to go at it if you want to make a POST?
Anyway the main thing you're missing is
function isUrl(url){
var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
if(regex.test(url)){
return regex.test(url);
}else{
return regex.test("http://"+url);
}
}
So this should be your new index.html
<html>
<head>
<script>
var extensions = [".aero",".biz",".cat",".com",".coop",".edu",".gov",".info",".int",".jobs",".mil",".mobi",".museum",".name",".net",".org",".travel",".ac",".ad",".ae",".af",".ag",".ai",".al",".am",".an",".ao",".aq",".ar",".as",".at",".au",".aw",".az",".ba",".bb",".bd",".be",".bf",".bg",".bh",".bi",".bj",".bm",".bn",".bo",".br",".bs",".bt",".bv",".bw",".by",".bz",".ca",".cc",".cd",".cf",".cg",".ch",".ci",".ck",".cl",".cm",".cn",".co",".cr",".cs",".cu",".cv",".cx",".cy",".cz",".de",".dj",".dk",".dm",".do",".dz",".ec",".ee",".eg",".eh",".er",".es",".et",".eu",".fi",".fj",".fk",".fm",".fo",".fr",".ga",".gb",".gd",".ge",".gf",".gg",".gh",".gi",".gl",".gm",".gn",".gp",".gq",".gr",".gs",".gt",".gu",".gw",".gy",".hk",".hm",".hn",".hr",".ht",".hu",".id",".ie",".il",".im",".in",".io",".iq",".ir",".is",".it",".je",".jm",".jo",".jp",".ke",".kg",".kh",".ki",".km",".kn",".kp",".kr",".kw",".ky",".kz",".la",".lb",".lc",".li",".lk",".lr",".ls",".lt",".lu",".lv",".ly",".ma",".mc",".md",".mg",".mh",".mk",".ml",".mm",".mn",".mo",".mp",".mq",".mr",".ms",".mt",".mu",".mv",".mw",".mx",".my",".mz",".na",".nc",".ne",".nf",".ng",".ni",".nl",".no",".np",".nr",".nu",".nz",".om",".pa",".pe",".pf",".pg",".ph",".pk",".pl",".pm",".pn",".pr",".ps",".pt",".pw",".py",".qa",".re",".ro",".ru",".rw",".sa",".sb",".sc",".sd",".se",".sg",".sh",".si",".sj",".sk",".sl",".sm",".sn",".so",".sr",".st",".su",".sv",".sy",".sz",".tc",".td",".tf",".tg",".th",".tj",".tk",".tm",".tn",".to",".tp",".tr",".tt",".tv",".tw",".tz",".ua",".ug",".uk",".um",".us",".uy",".uz", ".va",".vc",".ve",".vg",".vi",".vn",".vu",".wf",".ws",".ye",".yt",".yu",".za",".zm",".zr",".zw"];
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
function isUrl(url){
var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
if(regex.test(url)){
return regex.test(url);
}else{
return regex.test("http://"+url);
}
}
function showHint(str) {
delay(function(){
str = str.toLowerCase();
var dot = str.lastIndexOf(".");
var extension = str.substr(dot);
extension = extension.split('/')[0];
var found = $.inArray(extension, extensions) > -1;
if (!isUrl(str)||!found) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}, 500)
}
</script>
</head>
<body>
<p><b>Start typing a url in the input field below:</b></p>
<form>
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>
edit: Say you will start typing in http://www.example.net.. The AJAX will trigger on "http://www.example.ne" and then again when you add the last letter. To avoid that, you might try "change" instead of "keyup" event.
edit2: Now checks against list of valid domain extensions
edit3: Now waits half a second before posting the result.
edit4: Small oversight while checking for extensions, fixed with
extension = extension.split('/')[0];
Also if you want to enable users to write URL's without "http://" and similar, you'll need an edited regex or write a small hack that adds that to your string before you send it into "isUrl()".

settimeout not getting called?

I have a javascript which call a server and get a JSON data which contains some config to enable/disable redirecting to another link. I need to delay the redirection by a few seconds, but it seems that setTimeout() is not getting called in my method. Even if I change redirect() as an anonymous function and pass it in setTimeout it is still not getting called.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {
function redirect(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);
// set global object for using it inside the settimeout function
var redirect;
and then inside the xhr.onreadystatechange = function() {
redirect = function(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
setTimeout('redirect()',3000);
Thanks for all the suggestions. I have improved it as per suggestion by talsibony, and I further found out also that document.write() removes all my content, which makes it unable to find the redirect global variable. So I have instead changed it to add a div element and set the innerHTML. Here is the fixed code in case if someone encountered similar issue.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;
xhr.onreadystatechange = function() {
redirect = function(){
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
var div = document.createElement("div");
document.body.insertBefore(div, document.body.firstChild);
div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

Multiple XMLHttpRequests not working

I am puzzled about this. I have two XMLHttpRequests that operate on Select elements of my HTML file (each one operates on a different Select element right when the HTML file is loaded). I am using a callback function as was recommended on W3CSchools. If my variable xmlHttp is defined outside of my callback function, only the second request works, and the first one gets deleted before it has a chance to finish. If I put 'var' in front of it the same thing happens. However, if my variable is inside the function with 'var' in front of it, then absolutely nothing happens. I have narrowed it down to where to the line that says "HERE!!!!!" is where the program seems to hang. I know the loadXMLDoc function does not actually finish because when I put an alert outside of it, nothing happens. I am supposing it has something to do with the 'if' part and the program not being able to recognize xmlHTTP, even though it was locally defined. I am still pretty new to JavaScript and just want to be able to run multiple XMLHttpRequest objects at once without them getting in each other's way but also without the page hanging. Any ideas why this does not work?
HTML:
<form>
<select id="stateSelectCities">
<!-- Will be populated with MySQL -->
</select>
<select id="citySelect">
<option>Select a State</option>
</select>
<br />
<br />
<select id="stateSelectCounties">
<!-- Will be populated with MySQL -->
</select>
<select id="countySelect">
<option>Select a State</option>
</select>
<p id="xmltest"></p>
<p id="currentState"></p>
<p id="sc"></p>
<p id="rs"></p>
<p id="st"></p>
</form>
JavaScript:
<script type="text/javascript">
function loadXMLDoc(method, data, url, cfunc) {
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.onreadystatechange = cfunc;
xmlHTTP.open(method, url, true);
if (data) {
xmlHTTP.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHTTP.send(data);
} else {
xmlHTTP.send();
}
}
function returnStateListForCounties() {
loadXMLDoc('GET', null, "stateslist.xml", function() {
document.getElementById('countySelect').disabled = true;
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// Read the XML Data and Populate Counties States Menu
var response = xmlHTTP.responseXML;
var states = response.getElementsByTagName('state');
for (i = 0; i < states.length; i++) {
var option = document.createElement('option');
option.innerHTML = states[i].childNodes[0].nodeValue;
option.setAttribute('onmouseup', 'returnCounties(this.innerHTML)');
document.getElementById("stateSelectCounties").add(option);
}
}
//document.getElementById("sc").innerHTML = 'statusCode: ' + xmlHTTP.status;
//document.getElementById("rs").innerHTML = 'readyState: ' + xmlHTTP.readyState;
//document.getElementById("st").innerHTML = 'statusText: ' + xmlHTTP.statusText;
})
}
function returnStateListForCities() {
loadXMLDoc('GET', null, 'stateslist.xml', function() {
document.getElementById('citySelect').disabled = true;
// HERE!!!!!
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// Read the XML Data and Populate Cities States Menu
var response = xmlHTTP.responseXML;
var states = response.getElementsByTagName('state');
for (i = 0; i < states.length; i++) {
var option = document.createElement('option');
option.innerHTML = states[i].childNodes[0].nodeValue;
option.setAttribute('onmouseup', 'returnCities(this.innerHTML)');
document.getElementById("stateSelectCities").add(option);
}
}
document.getElementById("sc").innerHTML = 'statusCode: ' + xmlHTTP.status;
document.getElementById("rs").innerHTML = 'readyState: ' + xmlHTTP.readyState;
document.getElementById("st").innerHTML = 'statusText: ' + xmlHTTP.statusText;
})
}
//returnStateListForCounties();
returnStateListForCities();
</script>
The problem here is xmlHTTP variable which is defined inside loadXMLDoc function and try to use again inside returnStateListForCounties function, I'll do it like this:
function loadXMLDoc(method, data, url, cfunc) {
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.onreadystatechange = function() {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200)
{
cfunc(xmlHTTP.responseXML); //Call passed func with the resulting XML
}
};
xmlHTTP.open(method, url, true);
if (data) {
xmlHTTP.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHTTP.send(data);
} else {
xmlHTTP.send();
}
}
This way you encapsulate the data recovery.

how to click submit on achor tag without it refreshing the data on page php, sql and javascript

when ever I click send on the anchor tag the whole data on the page coming from the database refreshes. How do I prevent this. I have tried several options online but none works.
my JavaScript code is below. In some way I'm trying to get it like a facebook activity feed where the reatime info is being pushed out and the content that is already there does not disappear and appear on refresh.
<script>
function submitChat() {
if (form1.msg.value == '') {
alert('enter your message');
return;
}
$('#imageload').show();
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
$('#imageload').hide();
}
}
xmlhttp.open('GET', 'insert.php?&msg=' + msg, false);
xmlhttp.send();
return false;
}
$(document).ready(function(e) {
$.ajaxSetup({
cache: false
});
setInterval(function() {
$('#chatlogs').load('reg.php')
}, 2000);
});
</script>
here is the anchor tag being echod by php
<a href=\"#\"onclick=\"submitChat()\" \"onsubmit=return false\" >send</a>
send
Change
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
to
currentData = document.getElementById('chatlogs').innerHTML;
document.getElementById('chatlogs').innerHTML = currentData + xmlhttp.responseText;

Categories