How to convert jquery ajax to native javascript? - javascript

here is my ajaxHandler i want to convert this to native javascript i.e
using XMLHttpRequest but i am unable to understand how to convert.`
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
Paper.giffyLoading.style.display = 'block';
if (!attributes.nopopup) {
if (attributes.loadmsg) {
Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
attributes.loadmsg = null;
}
}
$.ajax(attributes);
}
}
i have try to convert the above code like this
XMLRequestDefaultHandler = function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'index.php/request', true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {
} else {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
}
};
xmlHttp.send(null);
}

I extracted ajax function of Jquery, to work without jquery.
And replace $.ajax(attributes); to ajax(attributes);
JQuery's ajax function, without JQuery :
function ajax(option) { // $.ajax(...) without jquery.
if (typeof(option.url) == "undefined") {
try {
option.url = location.href;
} catch(e) {
var ajaxLocation;
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
option.url = ajaxLocation.href;
}
}
if (typeof(option.type) == "undefined") {
option.type = "GET";
}
if (typeof(option.data) == "undefined") {
option.data = null;
} else {
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
}
if (typeof(option.statusCode) == "undefined") { // 4
option.statusCode = {};
}
if (typeof(option.beforeSend) == "undefined") { // 1
option.beforeSend = function () {};
}
if (typeof(option.success) == "undefined") { // 4 et sans erreur
option.success = function () {};
}
if (typeof(option.error) == "undefined") { // 4 et avec erreur
option.error = function () {};
}
if (typeof(option.complete) == "undefined") { // 4
option.complete = function () {};
}
typeof(option.statusCode["404"]);
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
else { xhr = new XMLHttpRequest(); }
} else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
xhr.onreadystatechange = function() {
if (xhr.readyState == 1) {
option.beforeSend();
}
if (xhr.readyState == 4) {
option.complete(xhr, xhr.status);
if (xhr.status == 200 || xhr.status == 0) {
option.success(xhr.responseText);
} else {
option.error(xhr.status);
if (typeof(option.statusCode[xhr.status]) != "undefined") {
option.statusCode[xhr.status]();
}
}
}
};
if (option.type == "POST") {
xhr.open(option.type, option.url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(option.data);
} else {
xhr.open(option.type, option.url+option.data, true);
xhr.send(null);
}
}

Related

How to send data to a server using AJAX?

We know how to get data from a server using ajax's GET method but can we also send data to a server using ajax? If so, how do we do it?
Also, can you show how to do it without jquery?
var xhr = null;
if (typeof XMLHttpRequest != "undefined") {
xhr = new XMLHttpRequest();
} else if (ActiveXObject) {
var aVersions = [
"Msxml2.XMLHttp.5.0",
"Msxml2.XMLHttp.4.0",
"Msxml2.XMLHttp.3.0",
"Msxml2.XMLHttp",
"Microsoft.XMLHttp"
];
for (var i = 0; i < aVersions.length; i++) {
try {
xhr = new ActiveXObject(aVersions[i]);
break;
} catch (error) {
console.log(error);
}
}
}
if(xhr) {
xhr.open('POST', 'your server url', true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
xhr.send();
} else {
console.log('cannot create xhr!');
}

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

undefined type when i turned my code to Object Javascript AJAX

i don't understand why i get TypeError (this.req is undefined) on line :
if (this.req.readyState === 4) {
function RequestCORS(url) {
this.url = "http://crossorigin.me/" + url;
this.req = new XMLHttpRequest();
}
RequestCORS.prototype.send = function () {
this.req.open("GET", this.url);
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
this.req.send();
};
function main() {
var url = "http://www.01net.com/rss/mediaplayer/replay/";
var requete = new RequestCORS(url);
requete.send();
}
window.addEventListener("load", main);
Thanks for reading.
this.req is undefined because you're making an asynchronous request and by the time your onreadystatechange fires this doesn't refer to your RequestCORS instance anymore.
You could declare a local variable that remains in scope inside the onreadystatechange function.
var req = this.req;
this.req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
or use bind
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
}.bind(this);
or get rid of this.req entirely
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};

Javascript / ajax code - works in chrome and firefox but not in IE10

What I'm trying to do is limit the options of one select box based on what the user chooses in a prior select box. It works perfectly in Chrome and Firefox, but in IE 10 the only thing that shows up is the text "Not Found". I'm not sure, but my guess is that something is going wrong in request.status. What it is, however, I have no idea.
function prepForms() {
for (var i = 0; i<document.forms.length; i++) {
var thisform = document.forms[i];
var departCity = document.getElementById("departcity");
departCity.onchange = function() {
var new_content = document.getElementById("ajaxArrive");
if (submitFormWithAjax(thisform, new_content)) return false;
return true;
}
}
}
function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
function submitFormWithAjax(whichform, thetarget) {
var request = getHTTPObject();
if (!request) {return false;}
var dataParts = [];
var element;
for (var i = 0; i<whichform.elements.length; i++) {
element = whichform.elements[i];
dataParts[i] = element.name + "=" + encodeURIComponent(element.value);
}
var data = dataParts.join("&");
request.open("POST", "flightlocationfilter.asp#ajaxArrive", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var matches = request.responseText.match(/<div id="ajaxArrive">([\s\S]+)<\/div>/);
if (matches.length > 0) {
thetarget.innerHTML = matches[1];
} else {
thetarget.innerHTML = "<p>--Error--</p>";
}
} else {
thetarget.innerHTML = "<p>" + request.statusText + "</p>";
}
}
};
request.send(data);
return true;
};
Edit: After walking through with the IE Developer Tools, it looks like the request.readyState is not moving beyond 1 to 4.

How to change ajax get to post

I have read the forums and google but i just dont understand how to change my ajax GET query to POST. It would be great if someone could help me to achive it. Thank you!
Heres my code:
function ajax(query,parameters,progress_div,progress_txt,result_div) {
// Sisend:
// 0 or 1 | (main_error) error string OR (resdiv) result string
var xmlhttp;
if (progress_div) { progdiv = document.getElementById(progress_div); }
if (result_div) { resdiv = document.getElementById(result_div); }
if (progdiv) { progdiv.innerHTML = progress_txt; }
// ajax
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var response = xmlhttp.responseText;
var string = response.split("<?php echo $vs; ?>");
//kui päring oli ok
if (string[0] == '1' || string[0] == '0') {
if (progdiv) { progdiv.innerHTML = ''; }
if (resdiv) { resdiv.innerHTML = string[2]; }
}
else {
errdiv = document.getElementById('main_error');
if (string[0] == '0') { errdiv.innerHTML = string[2]; }
else { errdiv.innerHTML = string[0]+string[1]; }
progdiv.innerHTML = '';
errdiv.style.display = 'block';
}
if (string[0] == '1' && string[1] != '0') {
window.location.href = string[1];
}
}
}
xmlhttp.open('GET','?leht=ajax&query='+query+'&parameters='+parameters,true);
xmlhttp.send();
return false;
}
change the below line
xmlhttp.open('GET','?leht=ajax&query='+query+'&parameters='+parameters,true);
like this
var url = 'http://yoursite.com/yourfile.php?leht=ajax&query='+query+'&parameters='+parameters;
xmlhttp.open("GET", url, true); //GET method
xmlhttp.open("POST", url, true); //POST method
You have missed the filename in your line.
Jquery POST
$.ajax({ url: "yourfilename.php",
data: {leht: 'ajax',"query":query,"parameters":parameters},
type: 'post',
success: function(output) {
//process the output
}
});

Categories