Run a script from a link - javascript

I have the following script that shows me information in a div, it works very well but with a button ... I am trying to make it walk from a link, I tried many ways and nothing, any ideas?
<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("contenido").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contenido").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
history.pushState(null, "", str+ ".xhttp");
xhttp.send();
}
</script>
<input type='button' value='6df67913c1' onclick='showCustomer(this.value);' />

You have to do something like this
const myLinkButton = document.getElementById('my-Link-button')
;
myLinkButton.onclick=e=>
{
e.preventDefault() // -> disable link action for new url
console.log( myLinkButton.dataset.value )
}
<a href="#" data-value="6df67913c1" id="my-Link-button" >button by link</a>

Use <a href="JavaScript: void (0)" onclick="callYourFunction()>link<\a>

You can do this.
<script>
function showCustomer(element) {
const str = element.getAttribute('data-value')
var xhttp;
if (str == "") {
document.getElementById("contenido").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contenido").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
history.pushState(null, "", str+ ".xhttp");
xhttp.send();
}
</script>
Same, from link

Related

javascript executed more than one

at the first I consider both if and else block executed. After added debugger to code, I don't know why my code run more than once.
function Submit(form) {
var timer_starttime = document.getElementById("timer_starttime");
var timer_finishtime = document.getElementById("timer_finishtime");
if (wait_s.reportValidity() && wait_m.reportValidity()) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_program";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
document.getElementById("success-alert").className = "alert alert-success alert-dismissible";
console.log(this.responseText);
console.log("if");
debugger;
} else {
document.getElementById("error-alert").className = "alert alert-danger alert-dismissible";
console.log("else");
}
};
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({
"timer_finishtime": timer_finishtime.value,
"timer_starttime": timer_starttime.value
}));
}
return false;
}
console.log("end");
<form id="TimeForm" action="" method="POST">
...
<button type="submit" class="btn btn-primary" onclick="return Submit(this);">Save</button>
When you send an AJAX request, the request goes through a number of states. See the documentation of XMLHttpRequest.readyState for the full details.
The onreadystatechange function will be called each time the state changes. So your else block will be executed repeatedly for all the initial states. Then when the request completes successfully, the if block will be executed.
You should only check for an error in the final state 4, not treat all the other states as errors.
function Submit(form) {
var timer_starttime = document.getElementById("timer_starttime");
var timer_finishtime = document.getElementById("timer_finishtime");
if (wait_s.reportValidity() && wait_m.reportValidity()) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_program";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
document.getElementById("success-alert").className = "alert alert-success alert-dismissible";
console.log(this.responseText);
console.log("if");
debugger;
} else {
document.getElementById("error-alert").className = "alert alert-danger alert-dismissible";
console.log("else");
}
}
};
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({
"timer_finishtime": timer_finishtime.value,
"timer_starttime": timer_starttime.value
}));
}
return false;
}
console.log("end");
<form id="TimeForm" action="" method="POST">
...
<button type="submit" class="btn btn-primary" onclick="return Submit(this);">Save</button>

Right way to verify that a user is logged

I use AJAX requests to make the user area of my website.
A "Log off" button must be displayed only when the user is connected.
For connecting a user, here my AJAX request:
function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
document.getElementById("popup_login").innerHTML += this.responseText;
if (isUserLogged()){
var x = document.getElementById("log_off");
x.classList.remove("inative_logoff");
x.classList.add("active_logoff");
}
}
};
var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);
xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}
And here my AJAX request to check if a user is connected:
function isUserLogged(){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(this.responseText);
if (this.responseText == "true") return true;
else return false;
}
};
xhr.open("POST", "php/is_user_connected.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}
My "Log off" button doesn't display for some reason.
function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
document.getElementById("popup_login").innerHTML += this.responseText;
isUserLogged();
}
};
var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);
xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}
----------
function isUserLogged(){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(this.responseText);
if (this.responseText == "true"){
alert("ok");
alert("test function");
var x = document.getElementById("log_off");
x.classList.remove("inative_logoff");
x.classList.add("active_logoff");
}
else {
//do your other code..
}
}
};
xhr.open("POST", "php/is_user_connected.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}
You can try if (isUserLogged() == true){ instead if (isUserLogged()){

multiple xhttp.sends in one page

hi when im trying to use xhttp.send(); it keeps returning
net::ERR_EMPTY_RESPONSE
my code is like this. when the user tries to presses too fast it kicks him off of the page. is there a way to stop this?
document.domain = "bitcoinrpg.com";
function UsernameTaken(name) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (name == "") {
document.getElementById("UsernameTaken").innerHTML = "";
return;
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("UsernameTaken").innerHTML = this.responseText;
}
};
xhttp.open("GET", "CheckUsername.php?q=" + name, true);
xhttp.send();
}
function BattlePlayers() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("BattleTable").innerHTML = this.responseText;
}
};
xhttp.open("POST", "GetPlayers.php?", true);
xhttp.send();
PlayerInfo();
}
function PlayerInfo() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("CharacterBar").innerHTML = this.responseText;
}
};
xhttp.open("POST", "PlayerInfo.php?", true);
xhttp.send();
}
function FightPlayer(enemyName) {
var elements = document.getElementsByClassName("BattleButton");
for (var i = 0; i < elements.length; i++) {
elements[i].setAttribute("disabled", "disabled");
}
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("battlestatus").innerHTML = this.responseText;
BattlePlayers();
}
};
xhttp.open("GET", "FightPlayer.php?enemyname=" + enemyName, true);
xhttp.send();
}
function InventoryShow() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("InventoryTable").innerHTML = this.responseText;
}
};
xhttp.open("POST", "PlayerInventory.php?", true);
xhttp.send();
}
I've tried messing about with just about every php.ini setting ive tried renaming each xhttp variable for each function every time it just returns the same. you can see what im meaning here
For anyone experiencing the same thing and you are with GoDaddy for your hosting. you need to switch its a problem on there end and switching fixed it for me.

Global var, correct way or any workaround? (before DOM ready) [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
Have been trying to set a global var in javascript to be access from another function,
but there is a particular global var that I can't access, it returns null.
It works if i declare the var in the function itself.
Note: I am unable to use any js library.
This does not works:
var xhttp = new XMLHttpRequest(); <-- this works as the request in the function runs.
var DialogBody = document.getElementById("DialogBody");//<-- this is the problem
function fetchDialog() {
url = "../message/user_status.php";
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
console.log("OK");// returns ok.
/*below all return error*/
DialogBody.innerHTML = "TEST";//<-- error: Cannot set property 'innerHTML' of null
}
}
}
This works:
function fetchDialog() {
url = "../message/user_status.php";
var DialogBody = document.getElementById("DialogBody");
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
console.log("OK");// returns ok.
DialogBody.innerHTML = "TEST";//This works.
}
}
}
So my question is, how do I set that var as global instead of in function.
EDIT:(Solves by links provided by SO user.) <- not what I want.
var xhttp = new XMLHttpRequest();
var DialogBody;
document.addEventListener("DOMContentLoaded", function(event) {
DialogBody = document.getElementById("DialogBody ");
});
function fetchDialog() {
url = "../message/user_status.php";
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
//console.log("OK");
DialogBody.innerHTML = "TEST";
}
}
}
UPDATE:(What I actually wanted.)
A little not so pretty workaround is this though it might be frown upon.
What I was actually trying to achieve is to set global var (consolidated).
I end up using eval() to set those var as string to achieve what I want and I find myself it very useful.
javascript concept
/.....
var xhttp = new XMLHttpRequest();
DialogBody = 'document.getElementById("DialogBody")';
//or DialogBody = 'document.getElementById("DialogBody").innerHTML';
function fetchDialog() {
url = "../message/user_status.php";
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
//console.log("OK");
eval(DialogBody).innerHTML="Test";
//or eval(DialogBody) = "a message that is dynamically generated";
//eval(DialogBody).className="Whatever";
}
}
}
actual scenario.
user_status.php
//..query ends.
<div id="DialogTitleMessage">
<?php echo $DialogTitle;?>
</div>
<div id="DialogBodyMessage">
<?php echo $DialogTitle;?>
</div>
actual javascript
//.....
var xhttp = new XMLHttpRequest();
DialogBody = 'document.getElementById("DialogBody")';
DialogTitle = 'document.getElementById("DialogTitle")';
DialogTitleMessage = 'document.getElementById("DialogTitleMessage")';
function fetchDialog() {
url = "../message/user_status.php";
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
eval(DialogBody).innerHTML = xhttp.responseText;
eval(DialogTitle).innerHTML = eval(DialogTitleMessage).innerHTML;
}
}
}
Try putting your var inside a document.addEventListener function :
document.addEventListener("DOMContentLoaded", function(event) {
var DialogBody = document.getElementById("DialogBody");
fetchDialog();
});
or
var DialogBody;
document.addEventListener("DOMContentLoaded", function(event) {
DialogBody = document.getElementById("DialogBody")
fetchDialog();
});
Instead of
window.onload = function() {
DialogBody = document.getElementById("DialogBody"); //Intializing
};
So the var will be declared after the document has been loaded.
The difference between window.onload and document.addEventListener is that you can use several time document.addEventListener when you can use only once window.onload.
Also just to let you know window.onload will be active after the window is loaded (image, videos...), and document.addEventListener will be active after the documentis loaded.
You need to execute getElementById when DOM is loaded, try this:
window.onload = function() {
window.DialogBody = document.getElementById("DialogBody");
};
var DialogBody; //Declaring
window.onload = function() {
DialogBody = document.getElementById("DialogBody"); //Intializing
};
function fetchDialog() {
url = "../message/user_status.php";
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
DialogBody.innerHTML = "TEST"; //Use here
}
}
}
try this:
window.onload = function() {
window.DialogBody = document.getElementById("DialogBody");
};
OR THIS:
var DialogBody;// by declaring this variable globally you can access it anywhere and also can avoid scope conflicts
function fetchDialog() {
url = "../message/user_status.php";
DialogBody = document.getElementById("DialogBody");
xhttp.open('POST',url,true);
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && http.status == 200) {
showOverlay();
console.log("OK");// returns ok.
DialogBody.innerHTML = "TEST";//This works.
}
}
}

XMLhttprequest issues

I'm trying to work on xmlhttprequests which isn't working. When inserting an alert box I receive a status of 0. Cant quite figure out what's wrong.
function submitChat() {
if (form1.uname.value != '' && form1.msg.value != '') {
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
alert(xmlhttp.status);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "insert.php?uname=" + uname + "&msg=" + msg, true);
xmlhttp.send();
} else {
alert("All Fields are Mandatory !!!");
return;
}
}
<form name="form1" action="#">`` Chatname:
<input type="text" name="uname" />
<br/>
<textarea name="msg"></textarea>
Send
<br/>
<br/>
</form>
<div id="chatlogs">
Loading Chat History !!!!!!!!!!
</div>
You should do .open() before your alert. So your code becomes like this:
function submitChat() {
if (form1.uname.value != '' && form1.msg.value != '') {
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","insert.php?uname="+uname+"&msg="+msg,true);
alert (xmlhttp.status);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readystate==4 && xmlhttp.status==200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
} else {
alert("All Fields are Mandatory !!!");
return;
}
}

Categories