How to make an AJAX call with pure javascript? - javascript

I am new to Ajax and Javascript so i need this example to be converted into ajax using pure javascript.How I can call this javascript as ajax and its functionality.need method like Common.prototype.ajax = function(method, url, data, callback) {};
Common.prototype.ajaxGet = function(url, callback) {};
Common.prototype.ajaxPost = function(url, data, callback) {};
function Common() {
console.log("Common Contructor fires!");
}
Common.prototype.setEvent = function(evt, element, callback) {
var obj_idfier = element.charAt(0);
var elementName = element.split(obj_idfier)[1];
if (obj_idfier == '#') {
var _ele = document.getElementById(elementName);
_ele.addEventListener(evt, callback, false);
} else if (obj_idfier == '.') {
var _els = document.getElementsByClassName(elementName);
for (var i=0; i<_els.length; i++) {
_els[i].addEventListener(evt, callback, false);
}
} else {
console.log("Undefined element");
return false;
}
return this;
};
Common.prototype.getInnerHtml = function(id){
return document.getElementById(id).innerHTML;
};
Common.prototype.setInnerHtml = function(ele, val){
ele.innerHTML = val;
};
Common.prototype.getVal = function(ele){
return ele.value;
};
Common.prototype.setVal = function(ele, val){
ele.value = val;
};
function Calculator() {
console.log("Calculater Constructor");
}
Calculator.prototype = new Common;
Calculator.prototype.init = function() {
var _this = this;
var _ele = document.getElementById("math");
var _numEle = document.getElementById("number");
this.setEvent("click", ".control", function() {
console.log(this.value);
var _num = _this.getInnerHtml('math');
_num = _num + "" + _this.getVal(this);
_this.setInnerHtml(_ele, _num);
});
this.setEvent("click", ".input", function() {
console.log(this.value);
var _num = _this.getInnerHtml('math');
_num = _num + "" + _this.getVal(this);
_this.setInnerHtml(_ele, _num);
});
this.setEvent("click", ".clear", function() {
console.log(this.value);
_this.setInnerHtml(_ele, "");
_this.setInnerHtml(_numEle, "");
});
this.setEvent("click", ".submit", function() {
console.log(this.value);
var _num = _this.getInnerHtml('math');
_num = eval(_num+""+ _this.getVal(this));
_this.setInnerHtml(_numEle, _num);
});
};
var calcObj = new Calculator();
calcObj.init();

You can build a general method for xhr calls:
function xhr (type, url, data, options) {
options = options || {};
var request = new XMLHttpRequest();
request.open(type, url, true);
if(type === "POST"){
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
options.success && option.success(parse(this.responseText));
} else {
options.error && options.error(this.status);
}
}
};
request.send(data);
}
function parse(text){
try {
return JSON.parse(text);
} catch(e){
return text;
}
}
And then user it for specific HTTP methods:
Common.prototype.ajax = function(method, url, data, callback) {
return xhr(method, url, data, {success:callback});
}
Common.prototype.ajaxGet = function(url, callback) {
return xhr("GET", url, undefined, {success:callback});
}
Common.prototype.ajaxPost = function(url, data, callback) {
return xhr("POST", url, data, {success:callback});
}

Related

WinJS Virtualized Data Source + nested asynchronous requests

Hi i'm relatively new to JavaScript and i'm working on a winjs app project where i want to use the Bing image search data source example in my project to virtualize the datasource of a listview.
My problem is understanding how the asynchronous functions work together and how to implement an async xhr request within the existing one.
Currently i'm using a synchronous request but i would like to change that into a asynchronous one.
This is my data adapter:
(function () {
var xxxDataAdapter = WinJS.Class.define(
function (devkey, query, delay) {
this._minPageSize = 2;
this._maxPageSize = 5;
this._maxCount = 50;
this._devkey = devkey;
this._query = query;
this._delay = 0;
},
{
getCount: function () {
var that = this;
var requestStr = 'http://xxx/' + that._query;
return WinJS.xhr({ url: requestStr, type: "GET", /*user: "foo", password: that._devkey,*/ }).then(
function (request) {
var obj = JSON.parse(request.responseText);
if (typeof obj.error === "undefined") {
var count = obj.length;
if (count === 0) { console.log("The search returned 0 results.", "sample", "error"); }
return count;
} else {
console.log("Error fetching results from API", "sample", "error");
return 0;
}
},
function (request) {
if (request && request.name === "Canceled") {
return WinJS.Promise.wrapError(request);
} else {
if (request.status === 401) {
console.log(request.statusText, "sample", "error");
} else {
console.log("Error fetching data from the service. " + request.responseText, "sample", "error");
}
return 0;
}
});
},
itemsFromIndex: function (requestIndex, countBefore, countAfter)
{
var that = this;
if (requestIndex >= that._maxCount) {
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist));
}
var fetchSize, fetchIndex;
if (countBefore > countAfter) {
//Limit the overlap
countAfter = Math.min(countAfter, 0);
//Bound the request size based on the minimum and maximum sizes
var fetchBefore = Math.max(Math.min(countBefore, that._maxPageSize - (countAfter + 1)), that._minPageSize - (countAfter + 1));
fetchSize = fetchBefore + countAfter + 1;
fetchIndex = requestIndex - fetchBefore;
} else {
countBefore = Math.min(countBefore, 10);
var fetchAfter = Math.max(Math.min(countAfter, that._maxPageSize - (countBefore + 1)), that._minPageSize - (countBefore + 1));
fetchSize = countBefore + fetchAfter + 1;
fetchIndex = requestIndex - countBefore;
}
var requestStr = 'http://xxx/' + that._query;
return WinJS.xhr({ url: requestStr, type: "GET", /*user: "foo", password: that._devkey,*/ }).then(
function (request)
{
var results = [], count;
var obj = JSON.parse(request.responseText);
if (typeof obj.error === "undefined")
{
var items = obj;
for (var i = 0, itemsLength = items.length; i < itemsLength; i++)
{
var dataItem = items[i];
var req = new XMLHttpRequest();
// false = synchronous
req.open("get", "http://xxxxx/" + dataItem.id, false);
req.send();
var jobj = JSON.parse(req.response);
if (typeof jobj.error === "undefined")
{
results.push({
key: (fetchIndex + i).toString(),
data: {
title: jobj.name.normal,
date: Date.jsonFormat(dataItem.calculatedAt, "Do, MMM HH:mm Z"),
result: "",
status: "",
}
});
}
}
return {
items: results, // The array of items
offset: requestIndex - fetchIndex, // The offset into the array for the requested item
};
} else {
console.log(request.statusText, "sample", "error");
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist));
}
},
function (request)
{
if (request.status === 401) {
console.log(request.statusText, "sample", "error");
} else {
console.log("Error fetching data from the service. " + request.responseText, "sample", "error");
}
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.noResponse));
}
);
}
});
WinJS.Namespace.define("xxx", {
datasource: WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (devkey, query, delay) {
this._baseDataSourceConstructor(new xxxDataAdapter(devkey, query, delay));
})
});
})();
And this is the synchronous request i would like to change to an asynchronous one:
var req = new XMLHttpRequest();
// false = synchronous
req.open("get", "http://xxxxx/" + dataItem.id, false);
req.send();
you can use then function to chain promises. In your scenario, then function need to simple have a if statement.
return WinJS.xhr(params).then(function (req)
{
if (..)
return WinJS.xhr(params2);
else
return; // then function ensures wrapping your sync result in a completed promise
}, function onerror(e)
{
// todo - error handling code e.g. showing a message box based on your app requirement
});
This is what i came up with. Map the json objects received asynchronously and make another asynchronous call for each object to get additional data. Then the nested async calls are joined and returned when all are finished.
return WinJS.xhr({ url: 'http://xxx=' + that._query }).then(function (request) {
var results = [];
var obj = JSON.parse(request.responseText);
var xhrs = obj.map(function (dataItem, index) {
return WinJS.xhr({ url: 'http://xxxx' + dataItem.attrx }).then(
function completed(nestedRequest) {
var xxJobj = JSON.parse(nestedRequest.responseText);
var dataObj = {};
dataObj.title = xxJobj.name;
dataObj.date = Date.jsonFormat(dataItem.attrtrxx, "Do, MMM HH:mm Z");
dataObj.result = "open";
dataObj.status = "foo";
if (dataItem.xx.hasOwnProperty("attrx5")) {
dataObj.opponent = dataItem.attrx4;
} else {
dataObj.opponent = dataItem.attrx3;
}
dataObj.page_title = "xXx";
dataObj.match_id = dataItem.id;
dataObj.type = "largeListIconTextItem";
dataObj.bg_image = "http://xxx/" + xxJobj.attrx2 + "-portrait.jpg";
results.push({
key: (fetchIndex + index).toString(),
data: dataObj
});
},
function (err) {
console.log(err.status);
console.log(err.responseText);
}
);
});
return WinJS.Promise.join(xhrs).then(
function (promises) {
return {
items: results, // The array of items
offset: requestIndex - fetchIndex, // The offset into the array for the requested item
};
},
function (err) {
console.log(JSON.stringify(err));
}
);
});

Jquery quicksearch issue with Sharepoint 2013

I'm using a jquery plugin called quicksearch within Sharepoint 2010 and it works perfectly. Unfortunately were being forced to migrate onto sharepoint 2013 and it's stopped working. An error is shown saying that the function is undefined. I believe I've narrowed this down to the quicksearch function itself.
Here is the preliminary code:
_spBodyOnLoadFunctionNames.push("Load");
$('[name=search]').on('keyup', function(){
Load();
});
function Load() {
var searchArea = "#cbqwpctl00_ctl22_g_ca6bb172_1ab4_430d_ae38_a32cfa03b56b ul li";
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
$('.filter input').on('change', function(){
checkAndHide()
//$(searchArea).unhighlight();
});
function checkAndHide(){
var inputs = $('.filter input');
var i =0;
for (var i = 0; i < inputs.length; i++){
if (!inputs[i].checked){
$('.' + inputs[i].name).addClass('filter-hide');
} else {
$('.' + inputs[i].name).removeClass('filter-hide');
};
};
};
}
Here is an example of the quicksearch library I'm using:
(function($, window, document, undefined) {
$.fn.quicksearch = function (target, opt) {
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 300,
selector: null,
stripeRows: null,
loader: null,
noResults: 'div#noresults',
bind: 'keyup keydown',
onBefore: function () {
var ar = $('input#id_search_list').val()
if (ar.length > 2) {
var i=0;
var ar2 = $('input#id_search_list').val().split(" ");
for (i = 0; i < ar2.length; i++) {
$(searchArea + ':visible');
}
return true;
}
return false;
checkAndHide()
},
onAfter: function () {
return;
},
show: function () {
this.style.display = "block";
},
hide: function () {
this.style.display = "none";
},
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
testQuery: function (query, txt, _row) {
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
}, opt);
this.go = function () {
var i = 0,
noresults = true,
query = options.prepareQuery(val),
val_empty = (val.replace(' ', '').length === 0);
for (var i = 0, len = rowcache.length; i < len; i++) {
if (val_empty) {
options.hide.apply(rowcache[i]);
noresults = false;
} else if (options.testQuery(query, cache[i], rowcache[i])){
options.show.apply(rowcache[i]);
noresults = false;
} else {
options.hide.apply(rowcache[i]);
}
}
if (noresults) {
this.results(false);
} else {
this.results(true);
this.stripe();
}
this.loader(false);
options.onAfter();
return this;
};
this.stripe = function () {
if (typeof options.stripeRows === "object" && options.stripeRows !== null)
{
var joined = options.stripeRows.join(' ');
var stripeRows_length = options.stripeRows.length;
jq_results.not(':hidden').each(function (i) {
$(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
});
}
return this;
};
this.strip_html = function (input) {
var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
output = $.trim(output.toLowerCase());
return output;
};
this.results = function (bool) {
if (typeof options.noResults === "string" && options.noResults !== "") {
if (bool) {
$(options.noResults).hide();
} else {
$(options.noResults).show();
}
}
return this;
};
this.loader = function (bool) {
if (typeof options.loader === "string" && options.loader !== "") {
(bool) ? $(options.loader).show() : $(options.loader).hide();
}
return this;
};
this.cache = function () {
jq_results = $(target);
if (typeof options.noResults === "string" && options.noResults !== "") {
jq_results = jq_results.not(options.noResults);
}
var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
cache = t.map(function () {
return e.strip_html(this.innerHTML);
});
rowcache = jq_results.map(function () {
return this;
});
return this.go();
};
this.trigger = function () {
this.loader(true);
if (options.onBefore()) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
e.go();
}, options.delay);
}
return this;
};
this.cache();
this.results(true);
this.stripe();
this.loader(false);
return this.each(function () {
$(this).bind(options.bind, function () {
val = $(this).val();
e.trigger();
});
});
};
}(jQuery, this, document));
`
This is where the error comes up:
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
Any help would be appreciated
Turns out was a small issue in the code and major css as sharepoint plays differently in 2013

Maintaining state of variables when changed inside a timer

I am using JavaScript.
I amusing a setInterval timer method.
Inside that method I am changing the values of module variables.
The thing is in IE the changes to the variables are not 'saved'. But in Chrome they are.
What is the accepted practice to do what I need to do?
this is my code:
function start()
{
var myVar = setInterval(function () { GetTimings() }, 100);
}
var currentts1;
var currentts2;
var currentts3;
var currentts4;
var frameCounter;
function GetTimings() {
if (frameCounter < 1) {
frameCounter++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var nextts = xmlhttp.responseText;
var bits = nextts.split('|');
if (currentts1 != bits[0]) {
currentts1 = bits[0];
postMessage("0|" + bits[0]);
}
if (currentts2 != bits[1]) {
currentts2 = bits[1];
postMessage("1|" + bits[1]);
}
if (currentts3 != bits[2]) {
currentts3 = bits[2];
postMessage("2|" + bits[2]);
}
if (currentts4 != bits[3]) {
currentts4 = bits[3];
postMessage("3|" + bits[3]);
}
frameCounter--;
}
}
xmlhttp.send();
}
}
The variables:
currentts1
currentts2
currentts3
currentts4
frameCounter
values are not preserved...
Try this, but notice I changed the currentts* to an Array when you try to view them
function start() {
var myVar = setInterval(GetTimings, 100);
}
var currentts = [null, null, null, null];
var in_progress = 0; // clear name
function GetTimings() {
var xhr;
if (in_progress > 0) return; // die
++in_progress;
xhr = new XMLHttpRequest();
xhr.open('GET', urlTS);
function ready() {
var nextts = this.responseText,
bits = nextts.split('|'),
i;
for (i = 0; i < currentts.length; ++i)
if (currentts[i] !== bits[i])
currentts[i] = bits[i], postMessage(i + '|' + bits[i]);
--in_progress;
}
if ('onload' in xhr) // modern browser
xhr.addEventListener('load', ready);
else // ancient browser
xhr.onreadystatechange = function () {
if (this.readyState === 4 && xhr.status === 200)
ready.call(this);
};
// listen for error, too?
// begin request
xhr.send();
}

XMLHttpRequest loop memory leak

I'm trying to check many items against information on ajax URL. But when I'm running this function in browser, memory usage goes above 2 gigs and then browser crashes (Chrome, Firefox). What am I doing wrong? items variable is really big - >200 000 and also includes some large strings.
var items = [1,2,3,4,5,6,7,8,9,10,...,300000]
var activeItems = {}
function loopAjax(){
for (i=0; i < items.length; i++) {
var currItem = items[i];
var request = new XMLHttpRequest();
var found = 0
request.open("GET", "/item=" + currItem);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var response = JSON.parse(request.responseText);
var active = response[0].active;
if (active) {
console.log("FOUND ACTIVE! " + currItem);
activeItems[found] = {"active": true, "item": currItem};
found++;
}
}
}
request.send();
}
}
Thank goodness the browser stalls and dies. If it didn't you just created a denial of service attack!
The problem needs to be reapproached. You better off creating a state machine which has a stack of requests in it. That way you only doing say 5 concurrent requests at a time.
function ItemChecker(sample_size, max_threads) {
this.sample_size = sample_size;
this.max_threads = max_threads;
this.counter = 0;
this.activeItems = [];
this.isRunning = false;
this.running_count = 0;
}
ItemChecker.prototype.start = function start() {
this.isRunning = true;
while (this.running_count < this.max_threads) {
this.next();
}
return this;
};
ItemChecker.prototype.stop = fucntion stop() {
this.isRunning = false;
return this;
};
ItemChecker.prototype.next = function next() {
var request, item_id, _this = this;
function xhrFinished(req) {
var response;
if (req.readyState !== 4) {
return;
}
_this.counter--;
if (req.status === 200) {
try {
response = JSON.parse(request.responseText);
if (response[0].active) {
_this.activeItems.push({
active: true,
item: item_id;
});
}
} catch(e) {
console.error(e);
}
// When finished call a callback
if (_this.onDone && _this.counter >= _this.sample_size) {
_this.onDone(_this.activeItems);
}
}
else {
console.warn("Server returned " + req.status);
}
}
if (!this.isRunning || this.counter >= this.sample_size) {
return;
}
item_id = this.counter;
this.counter++;
request = new XMLHttpRequest();
request.onreadystatechange = xhrFinished;
request.open("GET", "item=" + item_id);
request.send();
};
ItemChecker.prototype.whenDone = function whenDone(callback) {
this.onDone = callback;
return this;
};
This might work? Didn't try it for real. But you would call it with:
var item_checker = new ItemChecker(300000, 5);
item_checker.whenDone(function(active) {
// Do something with active
}).start();

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.

Categories