Ajax without jQuery [duplicate] - javascript

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

Related

How to execute function with Ajax promise?

I have two functions, I need to execute an Ajax function (function 1) before function 2 runs. I am a little confused on how to do this, I think it needs to be done is via a promise but I am a little unclear on how to do that, can an example be given?
function 1:
function showDetails(str) {
return new Promise(function (resolve, reject) {
if (str == "") {
document.getElementById("txtdetails").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtdetails").innerHTML = this.responseText;
}
};
$("#clientrowtestid").val(str);
xmlhttp.open("GET", "getdetails.php?q=" + str, true);
xmlhttp.send();
}
resolve("done");
});
}
function 2:
function sendLate(str) {
showDetails(str).then(function (response) {
var clientn = $("#txtdetails").find("h2").html();
var result;
var r = confirm("Send client (" + str + ") " + clientn + " a late notice?");
if (r == true) {
var taxcb = $("#taxcb").is(":checked") ? 'y' : 'n';
var taxrate = $('#taxrate').val();
var bcctocb = $("#bcctocb").is(":checked") ? 'y' : 'n';
var bcctotxt = $('#bcctotxt').val();
var duedate = $('#duedate').val();
var issuedate = $('#issuedate').val();
var additemscb = $("#additemscb").is(":checked") ? 'y' : 'n';
var additemname = $('#additemname').val();
var additemprice = $('#additemprice').val();
var dayslate = $('#dayslate').val();
var rowid = str;
$.ajax({
type: 'POST',
url: 'sendlate.php',
data: { taxcb: taxcb, taxrate: taxrate, bcctocb: bcctocb, bcctotxt: bcctotxt, duedate: duedate, issuedate: issuedate, additemscb: additemscb, additemname: additemname, additemprice: additemprice, rowid: rowid, dayslate: dayslate },
success: function (response) {
$('#result').html(response);
}
});
} else {
result = "Late notice aborted";
}
document.getElementById("result").innerHTML = result;
});
}
As you can see I need to execute function 1 to propagate the field in which function 2 is gathering data from. Are promises the best way of doing this? Can someone give me an example?
There are multiple issues in code like,
use the resolve method in appropriate code block
document.getElementById("result").innerHTML = "Late notice aborted"; is always executing.
I've changed your code little bit and let me know if it is working.
// function 1
function showDetails(str) {
return new Promise(function (resolve, reject) {
if (str == "") {
document.getElementById("txtdetails").innerHTML = "";
resolve("");
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtdetails").innerHTML = this.responseText;
resolve(this.responseText);
}
};
$("#clientrowtestid").val(str);
xmlhttp.open("GET", "getdetails.php?q=" + str, true);
xmlhttp.send();
}
});
}
// function 2
function sendLate(str) {
// call function 1 and then execute the below
showDetails(str).then(function (response) {
var clientn = $("#txtdetails").find("h2").html();
var r = confirm("Send client (" + str + ") " + clientn + " a late notice?");
if (r == true) {
var taxcb = $("#taxcb").is(":checked") ? 'y' : 'n';
var taxrate = $('#taxrate').val();
var bcctocb = $("#bcctocb").is(":checked") ? 'y' : 'n';
var bcctotxt = $('#bcctotxt').val();
var duedate = $('#duedate').val();
var issuedate = $('#issuedate').val();
var additemscb = $("#additemscb").is(":checked") ? 'y' : 'n';
var additemname = $('#additemname').val();
var additemprice = $('#additemprice').val();
var dayslate = $('#dayslate').val();
var rowid = str;
$.ajax({
type: 'POST',
url: 'sendlate.php',
data: { taxcb: taxcb, taxrate: taxrate, bcctocb: bcctocb, bcctotxt: bcctotxt, duedate: duedate, issuedate: issuedate, additemscb: additemscb, additemname: additemname, additemprice: additemprice, rowid: rowid, dayslate: dayslate },
// below `respone` is from which scope?
// is it from showDetails or from the ajax call in the current scope ?
success: function (response) {
$('#result').html(response);
}
});
} else {
document.getElementById("result").innerHTML = "Late notice aborted";
}
});
}
Read about promises
Yes Promises are the best way to follow async Javascript
function showDetails(str){
return new Promise(function(resolve,reject){
......//
document.getElementById("txtdetails").innerHTML = this.responseText;
resolve("done")
}
}
and in the function 2
showDetails(str).then(function(response){
// rest of the stuff after first function call
})
Hope this helps you.

Why this XMLHttpRequest doesn't work in IE?

I have a very simple XMLHttpRequest making a POST call. It works on Chrome and Firefox. But when I tried it in IE10, I got this error..
SCRIPT5022: InvalidStateError
Here's the code.
function _ajaxHelper(options) {
var xhr = new XMLHttpRequest();
var opts = _extendHelper({
withCredentials: false,
method: 'GET'
}, options);
xhr.withCredentials = opts.withCredentials;
xhr.open(opts.method, opts.url);
xhr.setRequestHeader('Accept', 'text/plain');
xhr.send(JSON.stringify(options.data));
return {
done: function done(cb) {
xhr.onreadystatechange = function onStateChange() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 300) {
cb(this.responseText);
} else {
cb(false);
}
}
};
xhr.ontimeout = function onTimeout() {
cb(false);
};
xhr.onerror = function onError() {
cb(false);
};
}
};
}
From what I googled, the reason that I would get that error was I set responseText but I didn't set anything and I'm getting instead. So, not sure what I did wrong there.
For _extendHelper this is the code
function _extendHelper() {
var args = arguments;
var res = {};
if (args && args[0]) {
for (var j in args) {
for (var k in args[j]) {
res[k] = args[j][k];
}
}
}
return res;
}

set time out in ajax call while using core javascript

I have a JavaScript function to call ajax. Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message. I don't want to use Jquery in it.
here is my code:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here's an example of how you can handle a timeout:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
In IE8, You can add a timeout event handler to the XMLHttpRequest object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
Use a javascript framework to do this though, i don't know why you're not using one, do you like uneccesary work? :)
If you want to simply add timeout, You can add it in the first function in three places:
setTimeout(function() {callback(this.responseText, params)}, 1000)
And your callback will execute around 1s later. The second palce is second call of callback.
Third place that i would suggest is to wrap this function like above:
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
Usually when i get in to testing internet connection i rather add throttling in the chrome developer tools like this:
Here is your code with first approach:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
console.log(new Date());
setTimeout(function() {callback(this.responseText, params)}, 2000);
} else {
console.error((new Date()).getSeconds());
setTimeout(function() {callback(this.responseText)}, 2000);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); });
Maybe the answer to this question will help.
Timeout XMLHttpRequest
since from what i understand you need to set timeout for xmlhttprequest,
you can use xmlhttp.timeout = /*some number*/

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

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

call generic handler in aspx without jquery

Can i call Generic handler in aspx without using jQuery?
yes, jQuery itself is a javascript, so you can call by writing your own script. The benefit of using jQuery is you don't need to worry about browser compatability, have to write less code, can get advantage of using jquery plugins etc, only the cost of adding jQuery.js.
Example:
<script type="text/javascript">
// Intialize XMLHTTP object
function GetXmlHttpObject() {
var A;
if (window.XMLHttpRequest) {
A = new XMLHttpRequest();
} else {
var msxmlhttp = new Array(
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < msxmlhttp.length; i++) {
try {
A = new ActiveXObject(msxmlhttp[i]);
break;
} catch (e) {
A = null;
}
}
}
return A;
}
function sendAjaxRequest(url, postVars, callbackFunc) {
var isPost = (postVars && postVars.length > 0);
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
if (!isPost) {
if (url.indexOf('?') == -1) {
url += '?' + uncache();
} else {
url += '&' + uncache();
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { //This function will execute on receive
var callback;
var extra_data = false;
var data = xmlHttp.responseText;
callback = callbackFunc;
callbackFunc(data, extra_data);
}
};
//Send data to the url through ajax
if (isPost) {
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-Length", postVars.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postVars);
} else {
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
function uncache() {
var d = new Date();
var time = d.getTime();
return 'time=' + time;
}
function comp(result) {
alert(result);
}
sendAjaxRequest('test.html', '', comp);
</script>

Categories

Resources