I have a problem using AJAX. The 2 functions that are called via the onclick event, post each value toggle AJAX and back data in two divs. If only put one function in one onclick. it runs well. but put 2, only run the last one ajax2('".$data."','".$num2."');. Where is the problem?
echo "<a OnClick=\"ajax1('".$data."','".$num1."');ajax2('".$data."','".$num2."');\">" click </a>";
two js code, function is similar. just function number, processing page and ruturn div is not same.
function1
function ajax1(data,number) {
HttPRequest = false;
if (window.XMLHttpRequest) {
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
var url = 'page1.php';
var pmeters = "data=" + data + "&number=" + number;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("return1").innerHTML = HttPRequest.responseText;
}
}
}
function2
function ajax2(data,number) {
HttPRequest = false;
if (window.XMLHttpRequest) {
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
var url = 'page2.php';
var pmeters = "data=" + data + "&number=" + number;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("return2").innerHTML = HttPRequest.responseText;
}
}
}
Change the first line of both functions to var HttPRequest = false;. This makes the httprequest private to each function.
Related
I am trying to get status of any address,in which request_withd function is call ,then action goes on another function named 'is_address_exist' which is return response status of any address in
'yes' or 'no' but i am getting 'undefined' response message in console.
function is_address_exist(address) {
var xmlhttp = new XMLHttpRequest();
var url = '../ withdrawn/address_check/' + address;
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
return xmlhttp.responseText;
}
}
}
}
function request_withd(e) {
var response_status = is_address_exist(address);
console.log(response_status);
}
The onreadystatechange function is a call back function, it runs async, it should have the intended actions included in its definition. This should work.
function is_address_exist(address){
var xmlhttp=new XMLHttpRequest();
var url='../withdrawn/address_check/'+address;
xmlhttp.open('GET',url,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4)
{
if(xmlhttp.status===200){
console.log(xmlhttp.responseText);
}
}
}
}
function request_withd(e){
is_address_exist(address);
}
Or for non async function
function is_address_exist(address) {
var responseText ="";
var xmlhttp = new XMLHttpRequest();
var url = '../ withdrawn/address_check/' + address;
xmlhttp.open('GET', url, false);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
responseText = xmlhttp.responseText;
}
}
}
return responseText;
}
function request_withd(e) {
var response_status = is_address_exist(address);
console.log(response_status);
}
is_address_exist() doesn't return anything here.
Your return is happening within a xmlhttp.onreadystatechange = () => ...
You could either use callbacks or promises here.
Callback example:
function is_address_exist(address, handler){
//...
xmlhttp.onreadystatechange = function(){
//...
handler(xmlhttp.responseText);
});
}
is_address_exist('...', function(data){
console.log(data);
});
Promise example:
function is_address_exist(){
return new Promise(function (resolve, reject) {
//...
xmlhttp.onreadystatechange = function(){
//...
resolve(xmlhttp.responseText);
});
xmlhttp.onerror = reject;
});
}
is_address_exist()
.then(function (data) {
console.log(data)
})
.catch(console.error.bind(console));
How can I get the content when the enter key is pressed?
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax(Mode) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 're.asp';
var pmeters = "lname=" + encodeURI( document.getElementById("txtCustomerID").value) +
"&tMode=" + Mode;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "Now is Loading...";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
document.getElementById("txtCustomerID").value = '';
}
}
}
</script>
<form name="frmMain"action="#">
<textarea name="txtCustomerID" id="txtCustomerID"onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>
**> how to get content when enter form keyboard (enter submit function)**
<input type="button" name="btnAdd" id="btnAdd" value="Add"OnClick="JavaScript:doCallAjax('ADD');">
<span id="mySpan"></span>
</form>
On the server side you get the values by using the Request object. For example:
<%
Dim serverTxtCustomerID
serverTxtCustomerID = Request("lname")
%>
You can read more about the Request object here.
I'm working on the project where I (sadly) cannot use jQuery. And I need to do something which is simple in jQuery but I cannot do it in pure JavaScript. So, I need to run one ajax request using a response form another one. In jQuery it will look like:
$.get("date.php", "", function(data) {
var date=data;
$("#date").load("doku.php?id="+date.replace(" ", "_")+" #to_display", function() {
$(document.createElement("strong")).html(""+date+":").prependTo($(this));
});
});
And this is my code in pure JS which isn't working:
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(ObiektXMLHttp)
{
ObiektXMLHttp.open("GET", "date.php");
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
var date = ObiektXMLHttp.responseText;
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
}
}
}
ObiektXMLHttp.send(null);
}
What am I doing worng?
You forgot to call ObiektXMLHttp.send(null); on second case:
//....
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function() {
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
};
//Here
ObiektXMLHttp.send(null);
How about something like this (naive prototype):
// xhr object def
var xhr = {
obj: function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
throw new Error("can't init xhr object");
},
get: function(url, fn) {
var xhr = this.obj();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
fn(xhr.responseText);
}
};
xhr.open("GET", url);
xhr.send(null);
}
};
// implementation
xhr.get("date.php", function(data){
xhr.get("doku.php?id=" + data.replace(" ", "_"), function(data){
alert(data);
});
});
It's not clear what you got wrong (can you tell us?), but I'd suggest to rely on some helper function like this:
function xhrGet(url, callback) {
if (window.XMLHttpRequest)
var xhr = new XMLHttpRequest();
else if (window.ActiveXObject)
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (!xhr) return;
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (typeof callback === "function") callback(xhr);
};
xhr.send(null);
return xhr;
}
So all you have to do is to use this function:
xhrGet("date.php", function(x1) {
xhrGet("doku.php?id=" + date.replace(" ", "_"), function(x2) {
// do stuff
// x1 and x2 are respectively the XHR object of the two requests
});
});
How does I get the response from the server in JavaScript? This is my sample code:
function get_Image(values) {
if (window.XMLHttpRequest) {
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http_request.open("GET", "http://sample_address_for_server", true);
http_request.send();
}
alert(http_request.status);
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}
}
}
Try using this block .. the problem with your code is that you missed the quote while creating the open connetion
function get_Image(values){
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("MSXML2.XMLHTTP")
} catch () {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch () {}
}
} else {
return false
}
}
http_request.onreadystatechange = function () {
alert(http_request.status);
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}}
};
http_request.open( "GET", "http://sample_address_for_server", true);
http_request.send(null);
}
you have to attach a function to the object's onreadystatechange event. The way you are doing, you are trying to get the response imediately after you sent the request, you don't have any response yet.
function get_Image(values) {
if (window.XMLHttpRequest) {
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http_request.open("GET", "http://sample_address_for_server", true);
http_request.send();
}
alert(http_request.status);
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}
}
}
}
This code works in Chrome and Firefox, but not IE (which is to be expected). Does anyone see anything wrong with this code that would render it useless in IE?
var waittime=400;
chatmsg = document.getElementById("chatmsg");
room = document.getElementById("roomid").value;
sessid = document.getElementById("sessid").value;
chatmsg.focus()
document.getElementById("chatwindow").innerHTML = "loading...";
document.getElementById("userwindow").innerHTML = "Loading User List...";
var xmlhttp = false;
var xmlhttp2 = false;
var xmlhttp3 = false;
function ajax_read() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("chatwindow").innerHTML = xmlhttp.responseText;
setTimeout("ajax_read()", waittime);
}
}
xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true);
xmlhttp.send(null);
}
function user_read() {
if(window.XMLHttpRequest){
xmlhttp3=new XMLHttpRequest();
if(xmlhttp3.overrideMimeType){
xmlhttp3.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp3) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState==4) {
document.getElementById("userwindow").innerHTML = xmlhttp3.responseText;
setTimeout("user_read()", 10000);
}
}
xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true);
xmlhttp3.send(null);
}
function ajax_write(url){
if(window.XMLHttpRequest){
xmlhttp2=new XMLHttpRequest();
if(xmlhttp2.overrideMimeType){
xmlhttp2.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp2) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp2.open('GET',url,true);
xmlhttp2.send(null);
}
function submit_msg(){
nick = document.getElementById("chatnick").value;
msg = document.getElementById("chatmsg").value;
document.getElementById("chatmsg").value = "";
ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + "");
}
function keyup(arg1) {
if (arg1 == 13) submit_msg();
}
var intUpdate = setTimeout("ajax_read()", waittime);
var intUpdate = setTimeout("user_read()", 0);
I'm going to avoid the question slightly and suggest you use jQuery =P. 90% of your code would evaporate. For example, your user_read function would become:
function user_read() {
$.ajax({
type: "GET",
url: "methods.php",
data: {method: "u", room: room}
dataType: "html"
success: function (data, status, xhr) {
$("#userwindow").html(data);
setTimeout(user_read, 10000);
}
});
}
Furthermore, jQuery is also designed to work on all browsers, so you shouldn't have IE problems any more.
Try run on IE some example using jQuery library - just for partial test that browser is 'ok' and code have bug.
jQuery would be best for multiple ajax requests. Else, there are quite a few problems that more advanced browsers automatically fix, while IE may fail on. A few missing semicolons.
You also have 2 intUpdate declarations for 2 different intervals at the end. I've also noticed that "xmlhttp2" has no onreadystatechange function.
Using a checker like JSLint will help alot.
I did my best with your code. Try this, it should result in no errors:
var waittime = 400;
chatmsg = document.getElementById("chatmsg");
room = document.getElementById("roomid").value;
sessid = document.getElementById("sessid").value;
chatmsg.focus();
document.getElementById("chatwindow").innerHTML = "loading...";
document.getElementById("userwindow").innerHTML = "Loading User List...";
var xmlhttp = false;
var xmlhttp2 = false;
var xmlhttp3 = false;
function ajax_read() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("chatwindow").innerHTML = xmlhttp.responseText;
setTimeout(function(){ajax_read();}, waittime);
}
};
xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true);
xmlhttp.send();
}
function user_read() {
if(window.XMLHttpRequest){
xmlhttp3=new XMLHttpRequest();
if(xmlhttp3.overrideMimeType){
xmlhttp3.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState==4) {
document.getElementById("userwindow").innerHTML = xmlhttp3.responseText;
setTimeout(function(){user_read();}, 10000);
}
};
xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true);
xmlhttp3.send();
}
function ajax_write(url){
if(window.XMLHttpRequest){
xmlhttp2=new XMLHttpRequest();
if(xmlhttp2.overrideMimeType){
xmlhttp2.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp2.open('GET',url,true);
xmlhttp2.send();
}
function submit_msg(){
nick = document.getElementById("chatnick").value;
msg = document.getElementById("chatmsg").value;
document.getElementById("chatmsg").value = "";
ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + "");
}
function keyup(arg1) {
if (arg1 == 13) {submit_msg();}
}
var intUpdate = setTimeout(function(){ajax_read();}, waittime);
user_read();