can't get answer of ajax with Javascript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
i have this:
var something = makeRequest(url);
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
console.log('Falla :( No es posible crear una instancia XMLHTTP');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null);
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//console.log(http_request.responseText); //this show a string result
//return http_request.responseText; //this not return nothing
//var something = http_request.responseText; // this return a undefined variable
} else {
console.log('Hubo problemas con la petición.');
}
}
}
}
look just under "if (http_request.status == 200)" the three things i prove and NOTHING.
i don't know how to get out of the function the result of the call. please help me

Your alertContents() function is executed asynchronously. You cannot return a value from the function. You can declare a global variable and assign the reponseText value to it and then process it.
var result ;
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText ;
process(result) ; // guaranteed that there will be some response
}
}
}
process(result); // Does not guarantee that result will have the
// returned value (response) and may result in failure

Related

JavaScript - Asynchronous request issue [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
A common Asynchronous request is made by the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
abc = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
a = JSON.parse(abc);
I get the following error:
Uncaught ReferenceError: abc is not defined
What is going wrong here?
You are trying to call abc outside onload that might be the only issue.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var abc = xhr.responseText;
var a = JSON.parse(abc); // moved it here
} else {
console.error(xhr.statusText);
}
}
};
to return value from a function, Use it this way
function getResult(myFunction) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var abc = xhr.responseText;
myFunction(abc);
} else {
console.error(xhr.statusText);
}
}
};
}
function myFunction(jsonData) {
//do whatever you wish to do here
}
Now how you are going to call it.
getResult(myFunction); //callback;

How to know how many asynchronous calls are pending

I'm using the following code to make multiple async. calls and I need to know how many of those calls are pending for validating purposes.
function llenarComboMetodos(cell) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Las llamandas asincronas no son soportadas por este navegador.");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var combo = '<select name="metodos[]">';
var opciones=xhr.responseText;
combo+= opciones+"</select>";
cell.innerHTML = combo;
}
}
}
xhr.open('POST', 'includes/get_metodos.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("completar=1");
}
Is there a way to know that?
Thank you (:
You can intercept the XMLHttpRequest.send and do your counting of active calls:
var activeXhr = (function(){
var count = 0;
XMLHttpRequest.prototype.nativeSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
this.onreadystatechange = function(){
switch(this.readyState){
case 2: count++; break
case 4: count--; break
}
};
this.nativeSend(body);
};
return count;
})();
console.log(activeXhr);

Ajax without jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to make an ajax call without jquery?
I have code in js(Ajax) but I want to make it without Ajax(XMLHttpRequest)
$.ajax({
type:'POST',
data:'slug='+prize,
url:'/wybrana-nagroda/',
success:function(msg)
{
$('#whaiting').hide();
if(msg==='winner')
$(window.location).attr('href','/formularz');
}
});
How it should look?
function send(post, url) {
var client = new XMLHttpRequest();
client.open("POST", url);
client.send(message);
}
?
Thanks.
If you want it to be compatible on all browsers, you'll need to do something like the following:
function sendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
Credit: quirksmode

Ajax response xml is null Java script

Servlet response:
for (int i = 0; i < projNames.size(); i++) {
sb.append("<project>");
sb.append("<projectName>" + projNames.get(i) + "</projectName>");
sb.append("</project>");
res.setContentType("text/xml");
res.setHeader("Cache-Control", "no-cache");
System.out.println(" test="+test);
res.getWriter().write(sb.toString());
}
System.out.println shows "sb" value as
<project><projectName>sample</projectName></project><project><projectName>sample 2</projectName></project>
I'm trying to retrieve the response XML and but when I checked the length "object value is null" ( debugged in IE 8 )
function displayValues()
{
var response;
if (req.responseXML != null)
alert("res xml is ther=="+ response); //displays UNDEFINED
else
alert("no res xml");
response = req.responseXML.getElementsByTagName("project")[0];
alert("child node"+response.childNodes.length); // alert is not displayed
}
Please enlighten. Thanks
AJAX code:
<SCRIPT type="text/javascript">
var response;
var firstName;
var icdatevalue;
function getProject()
{
var url ="DBActionServlet?action=getProject";
initRequest(url);
req.onreadystatechange = processRequest;
req.open("POST", url, true);
req.send(null);
}
function initRequest(url)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
alert("status="+req.status);//status is shown as 200
displayValues(); //this function code mentioned above
}
}
}
</SCRIPT>

ajax form issue IE

I have the following code that works in every browser but IE. When click on the submit button of the form I get no response at all from IE.
form has this value: onsubmit="sendform(this);return false;"
<script type="text/javascript">
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.status);
//alert(http_request.responseText);
toggleDiv('stylized');
showtoggleDiv('success');
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('GET', url, true);
http_request.send(null);
}
function sendform(el) {
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
query = '?' + query.join('&');
makeRequest("http://markburnettinternational.com/sitelokpw/members/test.php" + query);
}
</script>
<script language="javascript">
function toggleDiv(divid) {
if (document.getElementById(divid).style.display == 'none') {
document.getElementById(divid).style.display = 'block';
} else {
document.getElementById(divid).style.display = 'none';
}
}
</script>
<script>
function showtoggleDiv(divid) {
document.getElementById(divid).style.display = 'block';
}
</script>
Turn on the browser's debugger and put a breakpoint in sendform() and walk through it and see what happens. Alternately turning on the javascript console can give you vital feedback about what's going on.
There are at least three problems with this piece of code:
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
First, always declare your variables within the local scope using var, so use
var query = new Array();
for (var i in sub) {
Second, getElementsByTagName returns a NodeList, which is an array-like object. Never iterate over array(-like object)s using a for … in loop, always use an ordinary for loop.
Third, always use encodeURIComponent to properly encode query parameters:
for (var i = 0, len = sub.length; i < len; i++) {
if (sub[i].name) {
query.push(sub[i].name + '=' + encodeURIComponent(sub[i].value));
}
}
This might solve your IE issue.

Categories

Resources