AJAX make Array Global - javascript

I'm trying to store corresponding data values from a XML returning AJAX into global array and then letter call function that will remove some elements from it but have problem to do it.
Array is not global.
Here is the bad code.
Thanks for help.
var someArray=new Array();
function refreshPage() {
downloadUrl("page.php", function(data) {
markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var value=markers[i].getAttribute("Value");
someArray.push(value);
}
});
window.setTimeout("refreshPage()",5000);
}
function removeElement(value){
someArray.slice(value,1);
}
function downloadUrl(url, callback) {
var status = -1;
var request = createXmlHttpRequest();
if (!request) {
return false;
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
try {
status = request.status;
} catch (e) {
}
if (status == 200) {
callback(request.responseXML, request.status);
request.onreadystatechange = function() {};
}
}
}
request.open('GET', url, true);
try {
request.send(null);
} catch (e) {
changeStatus(e);
}
};

have you thought about using local storage?
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
localStorage.getItem("lastname");
If you want to stay with ajax do something like this
var it_works = false;
$.ajax({
type: 'POST',
async: false,
url: "some_file.php",
data: "",
success: function() {it_works = true;}
});
alert(it_works);

Related

how i can convert this request call in javascript to ajax code

I have a request code in te javascript .. and i want to convert it to ajax call .. because i think that my code is very old ? can you help please ?
my function in the js is :
function loadRest() {
const request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState === 4) {
let result = parseResponse(this.status, this.responseText);
if (result != null) {
Rest.rests = result;
createTable();
}
}
};
request.open("GET", Rest.baseURL + "/byCompany/" + logginedCompanyId, true);
request.send();
}
function parseResponse(status, responseText) {
log(responseText);
let responseObject = JSON.parse(responseText);
if (status !== 200 || (responseObject.error && responseObject.error != null)) {
alert("Error: " + responseObject.error);
return null;
}
return responseObject.result;
}
you can use $.get()
something like this
$.get('Rest.baseURL', function(response){
//
});
Here is what you wanted.
$('#ajax').click(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "localhost:8080/restws/json/product/get",
success: function(data){
let result = JSON.parse(data);
if(result != null) {
Rest.rests = result;
createTable();
}
}
});
});

How to make an AJAX call with pure 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});
}

Trouble with ajax request response handler

Very new to ajax and trying to make an ajax request function to be reused. Firebug says the request is going through and returning the correct data from my php file. However, the response is not being inserted into the div in my html. here is my code:
function ajaxRequest(url, method, data, asynch, responseHandler)
{
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST"){
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
request.onreadystatechange = function()
{
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
}
request.send(data);
}
function changeText() {
var data = "";
ajaxRequest("../PHP/CODE/changeText.php", "Get", data, true, insertNewText);
}
function insertNewText() {
var response = request.responseText;
var testDiv = document.getElementById("rightColumn");
testDiv.innerHTML = response;
}
You use insertNewText as a response handler.
Take a look at:
if (request.status == 200) {
responseHandler(request.responseText);
}
in this block of code responseHandler is the function callback, in your context, this is insertNewText
as you can see in
responseHandler(request.responseText);
The responseText is passed to it
However in your insertNewText signature, you dont handle this
In conclusion:
function insertNewText() {
var response = request.responseText;
var testDiv = document.getElementById("rightColumn");
testDiv.innerHTML = response;
}
Should be :
function insertNewText(response) {
var testDiv = document.getElementById("rightColumn");
testDiv.innerHTML = response;
}
Voila!
Change:
function insertNewText() {
var response = request.responseText;
var testDiv = document.getElementById("rightColumn");
testDiv.innerHTML = response;
}
to
function insertNewText(html) {
var testDiv = document.getElementById("rightColumn");
testDiv.innerHTML = html;
}

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

How can I change this variable with ajax?

I'm curious as to why this isn't working, here's the code:
function Ajax(sUrl, fCallback) {
var url = sUrl || '';
var callback = fCallback || function () {};
var xmlhttp = (function () {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (err) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
} else {
return null;
}
}());
this.setUrl = function (newUrl) {
url = newUrl;
};
this.setCallback = function (func) {
callback = func;
};
this.request = function (method, data) {
if (xmlhttp === null) { return false; }
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
callback(xmlhttp.status, xmlhttp.responseXML, xmlhttp.responseText);
}
};
data = data || '';
data = encodeURIComponent(data);
if ((/post/i).test(method)) {
xmlhttp.open('POST', url);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
} else {
var uri = data === '' ? url : url + '?' + data;
xmlhttp.open('GET', uri);
xmlhttp.send();
}
return true;
};
return this;
}
var ajax = new Ajax(''); // sets the url, not necessary for this demonstration
var changed = false;
function change() {
changed = true;
}
function foo() {
ajax.setCallback(change);
ajax.request();
alert(changed);
}
foo();
There is a fiddle here: http://jsfiddle.net/dTqKG/
I feel like the change function would create a closure that would indeed change the changed variable. Does anyone know what's going on?
The ajax.request(); will return before change() is called. That is the async nature of the AJAX calls, and the reason why you need the callback as opposed to just getting return value from send() method.
Other than that there might be some other issues in the code. I question why wouldn't you use one of the many AJAX frameworks readily available instead of writing your own.

Categories