I have to build an ajax site without the use of JQuery (which is a pain), So I have been trying to build ajax requests in a similar fashion.
Currently I have this:
function $ajax(json) {
var xmlhtml;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhtml = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhtml = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhtml.onreadystatechange = function () {
if (xmlhtml.readyState == 4) {
if (xmlhtml.status == 200) {
alert(xmlhtml.responseText);
}
else if (xmlhtml.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhtml.open(json.type, json.url, true);
xmlhtml.send();
};
and I call it like so:
(function () {
$ajax({
type: "GET",
url: "/api/stock"
});
})();
which is fine, it returns my records. What I need to do is create callback functions for complete (status == 200) and error (status != 200).
How can I do this?
Please note, I can not use jQuery.
Well, the simplest way would be for your function to accept another parameter which is the function:
function $ajax(json, callback) {
var xmlhtml;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhtml = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhtml = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhtml.onreadystatechange = function () {
if (xmlhtml.readyState == 4) {
if (xmlhtml.status == 200) {
callback(xmlhttp.responseText)
}
else if (xmlhtml.status == 400) {
// don't ignore an error!
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhtml.open(json.type, json.url, true);
xmlhtml.send();
}
Which would let you do
$ajax({...}, function(response){
// done here
})
As for your function itself, if you can use modern web browsers I'd do this slightly differently using promises. Like the above code this requires no external references but it does require a modern browser:
function xhr(params){
var xhr = new XMLHttpRequest()
xhr.open(params.type || "GET", params.url);
return new Promise(function(resolve, reject){
xhr.onload = function(e){
if(xhr.status === 200) return resolve(xhr.responseText);
return reject(new Error("XHR response not 200 " + xhr.status);
};
xhr.onerror = reject;
xhr.send(params.data)
});
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have been trying to solve this problem whole day,but it seems I am not able.
Here is my code:
function mailcheckajax(email){
//var add = $('#mail').val();
//window.location = "index.php?address="+add;
//alert(window.location.pathname);
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if(xmlhttp.responseText != "valid"){
window.mailerror = "true";
} else {
window.mailerror="false";
}
}
}
xmlhttp.open("GET","/application/views/client/mailvalidate.php?address="+$('#'+email).val(),true);
xmlhttp.send();
return "true";
}
It calls this function and comes another line of code:
mailcheckajax('studentEmail');
if (checkvalidate == "true") {
if (validateStep(oldstep) == false) {
$("html, body").animate({
scrollTop: 0
}, "slow");
return false;
}
}
I need that on onclick() firstly was executed mailcheckajax function fully in order to get response from server using ajax and only after that other code.Or do not exit from function before it gets ajax response.
Can anyone help?
You should add the other code you need to execute after the response to another function and call that function inside the handler:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if(xmlhttp.responseText != "valid"){
window.mailerror = "true";
//CALL HERE THE FUNCTION YOU WANT TO EXECUTE AFTER THE RESPONSE IS RECEIVED
} else {
window.mailerror="false";
}
}
}
Hopte that helps!
I am working with javascript cross domain ajax request. my code is working fine on chrome and other devices like android browser and android native app using phonegap.
But i was facing issue with Firefox..
Firefox does not support my PUT and DELETE requests.
Is there any solution for firefox to make put and delete request to my server.
firefox does support my post and get request. both request working fine.
here is my working code.
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;
}
For send Put request..
var xhr = createXMLHTTPObject();
xhr.open("PUT", url,true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
if(xhr.status==200){
request.success(xhr.responseText);
}else if(xhr.status!=200){
request.error(xhr.responseText)
}
}
}
xhr.send(body);
The following is working just fine on Firefox 22.0 (& 23.0 too):
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;
}
var xhr = createXMLHTTPObject();
xhr.open("PUT", "/echo/html/", true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
alert("Request completed, with the following status code: " + xhr.status);
}
xhr.send("");
Here is a jsFiddle: http://jsfiddle.net/qXQtD/
To better understand your situation, please answer the following:
What is the data you are trying to send?
What are your complete response headers (especially the "Access-Control-Allow-Origin" header)?
Im trying to setup a redirect for a chat script. If the chat goes unanswered after x amount of time the page will redirect.
I posted a question here yesterday regarding the same thing, but at the time knowing little in regards to JS I was trying to mix php with js. I have changed tactics.
Here is what I got thus far:
function opCheck()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
opCheck();
// alert('working2');
}
}
opjoined = "newchattimer.php";
xmlhttp.open("GET",opjoined,true);
xmlhttp.send(null);
}
function opResult()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//alert('state = 4');
var op = xmlhttp.responseText;
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET",ajaxurl,true);
xmlhttp.send(null);
}
setTimeout(function() {
opCheck();
opResult();
//alert(op);
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
It creates the text file properly but ultimately no redirect. I used the chrome deveolpers tool and no errors. I also tried to alert(op); to see if the result is being grabbed, but I get no alert.
What is wrong with this code?
Thanks.
If you had taken the time to indent your code, you'd see that var op is declared inside the scope of the onreadystatechange function, which is both out of scope and asynchronous.
function opResult() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var op = xmlhttp.responseText; //declared here
}
}
ajaxurl = "ajaxfiles/opAnswer_12.txt";
xmlhttp.open("GET", ajaxurl, true);
xmlhttp.send(null);
}
setTimeout(function () {
opCheck();
opResult();
// op is out of scope here
if (op == 'n') window.location.replace("chatnoop.php");
}, 3000);
Since timeouts aren't generally the way to handle async functions, and doing ajax request when all you intend to do when it finishes is to redirect anyway is'nt really neccessary, you could just do a regular form submit, which will redirect all by itself, or move the redirecting inside the right scope!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if(xmlhttp.responseText == 'n') window.location.href = 'chatnoop.php';
}
}
You may find what you want here http://www.tizag.com/javascriptT/javascriptredirect.php but basically i don't think that window.location.replace("chatnoop.php"); is correct. You should consider using JQuery to manage all the Ajax stuff in addition, but it should work like you've done anyway
I wrote an AJAX function and with this function I am populating the <option> tag of a particular <select> tag. This function runs fine on all leading web browsers but when I try to run it on IE7 it gives me the runtime error on following line in the browser:
document.getElementById("box2View").innerHTML = req.responseText;
My code is
function retrieveURL(url)
{
var newUrl = 'showStates.do?country='+url;
req = GetXmlHttpObject();
req.onreadystatechange = processStateChange;
try {
req.open("GET", newUrl, true);
} catch (e) {
alert(e);
}
req.send();
}
function processStateChange() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
alert(req.responseText);
document.getElementById("box2View").innerHTML = req.responseText;
var x = document.getElementsByName("countryid");
} else {
alert("Problem: " + req.statusText);
}
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
When I debug it I found that I got a HTML from in req.responseText
which is
So can anyone tell me what should I do to make it work with IE7.
function processAjaxStateChangeForRowAdd() {
alert(0);
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
processForRowAdd(req.responseText);
} else {
alert("Problem: " + req.statusText);
}
}
}
This code is working fine for IE, Safari and Firefox, but if I remove the alert, then the code will not work in Firefox, though it still works in IE and Safari.
Can anybody give me suggestion why it not working in Firefox without alert?
EDIT: Code that adds a row:
if (window.XMLHttpRequest && browserVersion.indexOf("Microsoft") == -1 ) {
// code for Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest("");
if (req) {
ajaxProcessed = false;
req.onreadystatechange = processAjaxStateChangeForRowAdd;
req.open("POST", url, true);
req.send();
// alert("1");
}
}
The alert is blocking. What this means is that your script is temporarily suspended (even if it's for a few milliseconds). During this time, your AJAX request completes and your req object is being set. You can add a delay (using setTimeout) to your callback to verify this.
I would suggest you post more of your script so that we can help you set up your callback properly. Alternatively, use a library such as jQuery to set up AJAX calls in a cross-browser manner easily.
EDIT: You need to either declare req as a global variable, or use an anonymous function. The following code demonstrates the first method (using a global variable):
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
if (req) {
req.onreadystatechange = processAjaxStateChangeForRowAdd;
req.open("POST", url, true);
req.send();
}
}
function processAjaxStateChangeForRowAdd() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
processForRowAdd(req.responseText);
} else {
alert("Problem: " + req.statusText);
}
}
}
function getHttp()
{
var xmlhttp;
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
if(typeof XMLHttpRequest != 'undefiend')
{
xmlhttp = new XMLHttpRequest();
}
}
}
return xmlhttp;
}
can you try this:
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
} else
alert("status: " + request.status);
}
You should also check for the readyState , the following code might help
req.onreadystatechange=function()
{
if (req.readyState==4 && req.status==200)
{
processForRowAdd(req.responseText)
}
}
Read this for the different values of readyState