Loop Calling Function in Native Ajax - javascript

Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...

You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}

Related

AJAX does not return object

I am using AJAX GET to get a local JSON file and it does that, but once i try to return it says undefined.
ScoreHandler = function () {
this.getScores = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler;
var scores = this.scoreHandler.getScores();
//This logs undefined
console.log(scores);
}
Just implement a callback for response, something like this
ScoreHandler = function () {
this.getScores = function(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
if(typeof callback === 'function')
callback(data);
//return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler; //why this line use it directly
var scores = this.scoreHandler.getScores(function(data){
console.log("response", data); //you can see the data here
});
//This logs undefined
console.log(scores);
}

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*/

Return value from AJAX onreadystatechange Event

I have some problems with returning a value from a function into a variable. It is apparently "undefined". This apparently happens due to the asynchronity of JavaScript. But in my case I don't know how to circumvent it with "callbacks" or "promises". Please see code below. I would like to return the exchange rate saved in "value" back to "rate" and use it further in my code. Any ideas?
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
return value;
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
alert("The return statement somehow didn't work: "+ rate);
I'm a newbie, by the way. So sorry, if this question has already been asked like a million times before.
Thanks
René
You can't return anything from a async function in JS. So create a new function and use it as a callback function. See the below example.
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
function valueCallBack(value){
console.log("value is " + value);
}
Update : You can use the Promise API introduced in the ES6 or use JQUERY deferred objects.
xmlhttp.send() shouldn't be empty. Try this. I hope it will do the job!
xmlhttp.send(null);
You can send the response value to another function so when you have a value it will be displayed without it being undefined.
Try this:
rateCalc();
var currency = "EUR";
function rateCalc() {
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
show(value);
}
};
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
} else {
value = 1;
show(value);
}
}
function show(rate) {
alert("Value: "+ rate);
}
So this is how I changed the code now. The call back function is used for all further calculations with the called back value. Thanks again to #Jijo John and #nx0side.
var currency = "HKD";
var value;
if (currency != "EUR")
{
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else
{
valueCallBack(1);
}
//in this function all further calculations with "value" need to take place.
function valueCallBack(value)
{
//example
var result = 70000/value;
console.log("Result is " + result);
}

update ajax send() content

I'm trying to receive data from ajax call and then send this data back using ajax.
javascript code:setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
var content = "data=1";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);
the problem now is that it keeps sending the old content. how can I update content variable with ajax response text?
Move the line var content = "data=1"; out of the function:
var content = "data=1";
setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);

Browser freeze when calling an ajax post / get methods

I have two ajax functions which freeze the window whenever they are called.
Is there a way to prevent such behaviour ? (Pure javascript).
Here's the two functions:
function fetch_json_data(a)
{
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() }
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json_response = JSON.parse(xmlhttp.responseText);
for (var key in json_response)
{
if(json_response[key] != null && json_response[key].length > 0)
{
var e = document.getElementById(key+".div");
e.innerHTML = "<pre>"+json_response[key]+"</pre>";
var e = document.getElementById(key);
e.setAttribute("class", "active");
e.parentNode.parentNode.previousElementSibling.setAttribute("class", "active");
results_status[key] = true;
if (key.match("sh"))
{
quick_info.children[2].innerHTML += key + ", ";
}
quick_info.setAttribute("class", "show-data");
close_alert();
}
}
}
}
xmlhttp.open("POST","ajax.php", false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(a);
}
function number 2:
function fetch_data(a, b)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (last_fetched_element != null) { last_fetched_element.removeAttribute("class") }
last_fetched_element = document.getElementById(b.id+".div");
var t = last_fetched_element;
var response = xmlhttp.responseText;
if (xmlhttp.responseText.length == 0) response = "No Data";
t.innerHTML = "<pre>" + response + "</pre>";
t.setAttribute("class", "show-data");
document.getElementById(b.id).setAttribute("class", "active");
close_alert();
results_status[b.id] = true;
}
}
xmlhttp.open("POST","ajax.php", false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(a); // "fname=Henry&lname=Ford"
}
I can't tell why this is happening. the response arrive rather quickly, but still,
I would be nice to avoid that freeze.
it is because you are using a synchronous call, try asynchronous
set the third parameter of open to true
The XMLHttpRequest.open() function. The third parameter sets Async or Normal. With Async set to true the browser won't freeze. With normal, the browser will freeze and wait for everything to be loaded. So change your lines.
xmlhttp.open("POST","ajax.php", false);
To:
xmlhttp.open("POST","ajax.php", true);

Categories

Resources