XMLhttprequest issues - javascript

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;
}
}

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>

Run a script from a link

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

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()){

How Do not call function except storage the script in local storage completed?

I do not want to call function LoadLocal(); unless the task window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
really has been completed. How?
function loadServer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
loadLocal();
}
else if (xmlhttp.status == 400) {
loadLocal();
}
else {
loadLocal();
}
}
};
xmlhttp.open("GET", "http://tokojs.com/app/hokinawafashion.js?"+Math.random(), true);
xmlhttp.send();
}
I do not want to call function LoadLocal(); unless the task window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
has been completed. How?
This is full script
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(r){var t,e,o,a,h,n,c,d="",C=0;for(r=Base64._utf8_encode(r);C<r.length;)t=r.charCodeAt(C++),e=r.charCodeAt(C++),o=r.charCodeAt(C++),a=t>>2,h=(3&t)<<4|e>>4,n=(15&e)<<2|o>>6,c=63&o,isNaN(e)?n=c=64:isNaN(o)&&(c=64),d=d+this._keyStr.charAt(a)+this._keyStr.charAt(h)+this._keyStr.charAt(n)+this._keyStr.charAt(c);return d},decode:function(r){var t,e,o,a,h,n,c,d="",C=0;for(r=r.replace(/[^A-Za-z0-9\+\/\=]/g,"");C<r.length;)a=this._keyStr.indexOf(r.charAt(C++)),h=this._keyStr.indexOf(r.charAt(C++)),n=this._keyStr.indexOf(r.charAt(C++)),c=this._keyStr.indexOf(r.charAt(C++)),t=a<<2|h>>4,e=(15&h)<<4|n>>2,o=(3&n)<<6|c,d+=String.fromCharCode(t),64!=n&&(d+=String.fromCharCode(e)),64!=c&&(d+=String.fromCharCode(o));return d=Base64._utf8_decode(d)},_utf8_encode:function(r){r=r.replace(/\r\n/g,"\n");for(var t="",e=0;e<r.length;e++){var o=r.charCodeAt(e);o<128?t+=String.fromCharCode(o):o>127&&o<2048?(t+=String.fromCharCode(o>>6|192),t+=String.fromCharCode(63&o|128)):(t+=String.fromCharCode(o>>12|224),t+=String.fromCharCode(o>>6&63|128),t+=String.fromCharCode(63&o|128))}return t},_utf8_decode:function(r){for(var t="",e=0,o=c1=c2=0;e<r.length;)o=r.charCodeAt(e),o<128?(t+=String.fromCharCode(o),e++):o>191&&o<224?(c2=r.charCodeAt(e+1),t+=String.fromCharCode((31&o)<<6|63&c2),e+=2):(c2=r.charCodeAt(e+1),c3=r.charCodeAt(e+2),t+=String.fromCharCode((15&o)<<12|(63&c2)<<6|63&c3),e+=3);return t}}
var versi = '1';
// Load Script Local
var sc = localStorage.getItem('scriptjs');
function loadLocal(){
if (sc === undefined || sc === null || sc.length === 0){
loadServer();
}
else{
var s = document.createElement('script');
s.type = 'text/javascript';
var code = Base64.decode(sc);
try {
s.appendChild(document.createTextNode(code));
document.body.appendChild(s);
} catch (e) {
s.text = code;
document.body.appendChild(s);
}
}
}
//
// Load Script Server
function loadServer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
loadLocal();
}
else if (xmlhttp.status == 400) {
loadLocal();
}
else {
loadLocal();
}
}
};
xmlhttp.open("GET", "http://tokojs.com/app/hokinawafashion.js?"+Math.random(), true);
xmlhttp.send();
}
//
window.onload = loadServer();

XMLHttpRequest status is 0 why?

Here is my code:
var xmlhttp;
function HttpObject(str)
{
//alert("iam in process request");
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
alert ("xmlhttp");
}
else if(window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert ("ms.xmlhttp");
}
else
{
XmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
xmlhttp.onreadystatechange = processRequest();
xmlhttp.open("POST",'/CountryTest.do',true);
xmlhttp.send(null);
}
function processRequest()
{
if (xmlhttp.readyState === 0) {
alert("u r in 0 :: The request is not initialized ");
}
var target = document.getElementById("curlist");
var res = xmlhttp.responseText;
alert(res);
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
alert("in readystate");
}
else
{
alert("error in readystate");
}
}
It always displaying status 0
curlist is id of my country state prog
can any one say me where is problem?
/CountryTest.do is the url pattern of the servlet.
xmlhttp.onreadystatechange = processRequest();
You just called processRequest immediately, and assigned its return value to onreadystatechange.
You want to assign the function itself, without calling it.
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState=='4')
{
alert(xmlhttp.responseText);
}
}

Categories