Passing For Loop Variable into AJAX Success - javascript

I have an issue with passing my for loop index variable into ajax success function.. I know this is a duplicate, but I've tried several other solutions that I've found and none seem to work for me..
Anyway, I have this code right here :
embeds = document.getElementsByClassName('kcode');
for (i = 0, l = embeds.length; i < l; i++) {
if (typeof embeds[i] != 'undefined' && typeof embeds[i].classList != 'undefined' && !embeds[i].classList.contains('filled')) {
embeds[i].classList.add('filled');
var embed = window.intext[embeds[i].getAttribute('data-k-kid')];
if (embed) {
embeds[i].classList.add('embed');
switch (embed.type.toLowerCase()) {
case 'sport_plugin':
if(sportData.selectedType.name == "Ranking Table") {
(function(i) {
jQuery.ajax({
url: url,
dataType: 'json',
success: function(response) {
var content = '';
if (table.name == "Western Conference" || table.name == "Eastern Conference") {
content+= '</div>';
embeds[i].innerHTML = content;
}
}
});
})(i);
}
break;
default:
embeds[i].style.display = "none";
}
embeds[i].classList.remove('kcode');
i--;
}
}
}
Now, what I'm trying to achieve -
I want to pass the embeds variable and the i variable of for loops index into my ajax response, so I could set the innerhtml of embeds[i] after the response is finished. I tried wrapping the ajax function in (function (i) {})(i); closure but it didint help. Any ideas? Thank You!

I think i variable should be global in that scope, so I would try to use it like this:
case 'sport_plugin':
if(sportData.selectedType.name == "Ranking Table") {
jQuery.ajax({
url: url,
dataType: 'json',
success: function(response) {
var content = '';
if (table.name == "Western Conference" || table.name == "Eastern Conference") {
content+= '</div>';
embeds[i].innerHTML = content;
}
}
});
}
break;

You can try to create a callback success function for the ajax. Before the ajax call. Something like this
var successCallback = function() {
var content = '';
if (table.name == "Western Conference" || table.name == "Eastern Conference") {
content+= '</div>';
this.embeds[this.i].innerHTML = content;
}
};
successCallback.i = i;
successCallback.embeds = embeds;
Note the "this." in front of the i.
And then your ajax:
jQuery.ajax({
url: url,
dataType: 'json',
success: successCallback
});
I have not tried it but it might work

I solved this problem myself, nontheless thanks for all the help and replies!
I simply used this function for getting my data, instead of usual ajax response..
_get = {
'sync': function (url) {
var xhr = typeof XDomainRequest != 'undefined' ? new XDomainRequest() : new XMLHttpRequest();
xhr.open('get', url, false);
xhr.send(null);
console.log('sync url ' + url);
//console.log(xhr.responseText); return {};
var data = {};
if (xhr.status == 200) {
data = JSON.parse(xhr.responseText);
}
return data;
}
};
And then just
var response = _lr.get.sync(url);

Related

Function with AJAX run last, how to make it run first

I have one function with AJAX Call(Below Code):
function get_type(Name) {
var field_name;
$.ajax({
type: "GET",
url: "../home/Asset/MR/MR.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('pub').each(function() {
if (Name == $(this).find('pro').text()) {
$(this).find('metadata field').each(function() {
field_name = $(this).find('name').text();
if (field_name == "little") {
type = "L";
} else if (field_name == "Big") {
type = "b";
}
});
}
});
}
});
}
This code works well but the problem is it run after all the functions finished. I want to run this code first I need to get data from the XML. I need to stop the loop of $(xml).find('pub').each(function() this once the Name== $(this).find('pro').text() text is matched. Because this loop execute even I get the answers.
Calling Function codes:
var rd = new FileReader();
rd.onload = function(e) {
var xmlDoc = $.parseXML(this.result);
var $xml = $(xmlDoc);
var J_Name = $xml.find('meta').text();
get_type(J_Name);
//check allowed child of front tag
check_allowed_direct_child("places", "Tirunelveli,Tiruchendur,Alwar", "RULE_002", "Fail");
};
rd.readAsText(this.files[i]);
Callbacks to the rescue!
function get_type(name, cb) {
cb = cb || function () {};
var field_name;
var type;
var types_map = {
'little': 'L',
'Big': 'b'
};
$.ajax({
type: 'GET',
url: '../home/Asset/MR/MR.xml',
dataType: 'xml',
success: function (xml) {
$(xml)
.find('pub')
.each(function () {
if (name == $(this).find('pro').text()) {
$(this)
.find('metadata field')
.each(function () {
field_name = $(this)
.find('name')
.text();
if (types_map.hasOwnProperty(field_name)) {
type = types_map[field_name];
return false; // break out of each()
}
});
return false; // break out of each()
}
});
cb(type); // execute provided callback
}
});
}
var rd = new FileReader();
rd.onload = function (e) {
var xmlDoc = $.parseXML(this.result);
var $xml = $(xmlDoc);
var J_Name = $xml.find('meta').text();
get_type(J_Name, function (type) {
// do stuff once get_type() resolves, type being either matched type or undefined
check_allowed_direct_child('places', 'Tirunelveli,Tiruchendur,Alwar', 'RULE_002', 'Fail');
});
};
rd.readAsText(this.files[i]);
If interested, read on how to make use of Promises, to make callback code a lot more digest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
If still interested, read on how to use async / await to make Promises code a lot more digest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

YQL AJAX cross domain request stopped working

I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any data?

using javascript to load json data from google maps

So, this is the code I have, console.log gives me the right value, but the function doesn't return the value, even if the return is inside the timeout. I must be doing something wrong.
function countyfinder(address){
var rr =$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address.replace(" ", "%20")).done(function(data) {
var county = data.results[0].address_components[3].short_name;
//return county;//data is the JSON string
});return rr;};
function calculatetax(address, price){
var j = countyfinder(address);
setTimeout(function(){var k = j["responseJSON"]['results'][0]['address_components'][3]['short_name'];
console.log(k);//return k won't work in here either
}, 1000); return k
};
this is what I ended up with:
var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
function getCounty(address) {
var country;
var baseApiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
var query = "?address=" + encodeURIComponent(address);
var queryUrl = baseApiUrl + query;
$.ajax({
url: queryUrl,
async: false,
dataType: 'json',
success: function(data) {
county = gmapsExtractByType(data, "administrative_area_level_2 political");
}
});
return countr.long_name;
}
function gmapsExtractByType(json, type) {
return json.results[0].address_components.filter(function(element) {
return element.types.join(" ") === type;
})[0];
}
console.log( getCounty("100 wacko lane ohio") );
I had to use a synchronous request by changing some settings in the ajax request. The drawback of this is that the browser will be locked up until you get a request response, which can be bad on a slow connection or a connection with an unreliable server. With google, most of the time, I don't think that will happen.

Ajax call inside a while loop

I want Ajax to get information while the information is valid. So if I do
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp;
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
If I do this without while (putting 0 instead of get var), I get the information I need, but if I put it like this, I enter an infinite loop and the page breaks. By the way, I tested and the if(data != '') statement works as intended.
I don't know why temp doesn't change the state of the ses variable. I tried putting an else statement inside $.get(..)
else ses = false;
but it doesn't do the trick neither.
Thanks for reading!
jQuery ajax (as most ajax implementations), which $.get() is a shorthand for, is asynchronouos be default. The callback function is only executed once the request is complete. The while continues indefinitely since without yielding control out to the JS engine the callback doesn't get a chance to do it's work - even if the request(s) are done.
In order to continuously send requests, try like this:
function requestMore(i) {
$.get('/my/url/?get=' + i, function (data) {
if (data != '') {
sortArticles(data);
requestMore(i + 1);
}
});
}
(document).ready(function () {
requestMore(1);
});
The way you wrote your code temp will never be ''.
The problem is temp is not a string. It's undefined.
Instead of:
if(temp == '') ses = false;
write:
if(typeof(temp) == 'undefined') ses = false;
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp='';
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
This will work.Initialize temp as a blank string as shown :)

Javascript global variable not being set from ajax call [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return Value from inside of $.ajax() function
I'm working on a CakePHP app that makes use of widespread AJAX calls to controllers. I'm stuck with one particular AJAX call in which I'm trying to assign the response from the controller to a JS global variable. Here is the code:
window.errors = "";
function setErrors(err) {
window.errors = err;
}
function ajaxCall(u, t, d, dt) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
var success = false;
var err = "";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
console.log(err); //<=== displays correct value
setErrors(err); //<=== but somehow this seems to be failing??
}
else {
if(d.success === "1") {
success = true;
}
}
}
});
return success; //<=== I suspect this might be the culprit
}
And this is how ajaxCall() is used:
function register() {
var data = {};
var $inputs = $("#regForm :input");
$inputs.each(function(){
data[this.name] = $(this).val();
});
data = {"User" : data }; //CakePHP compatible object
data = JSON.stringify(data);
//Here's the AJAX call
if(ajaxCall('https://localhost/users/add', 'post', data, 'json')) {
alert("Registered!");
}
else {
alert(window.errors); // <=== empty string
console.log("window.errors is: " + window.errors); // <=== empty string
}
}
But on the Chrome JS console, window.errors returns the correct value (non-empty, validation error string).
I found a similar question that possibly might be addressing my issue (the return success immediately following the $.ajax() is being executed before the success: callback). How can I fix this without drastically changing the code (also, I don't want to make this a synchronous call)?
Yes, you are right that the return statement runs before the success callback. You can't return the result from the function, as the function has to return before the success event can be handled.
Add a callback to the ajaxCall function, and call that instead of setting the success variable:
function ajaxCall(u, t, d, dt, callback) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
callback(false, err);
} else {
callback(d.success === "1", "");
}
}
});
}
Send the code for handling the result into the ajaxCall function:
ajaxCall('https://localhost/users/add', 'post', data, 'json', function(success, err){
if (success) {
alert("Registered!");
} else {
alert(err);
}
});

Categories

Resources