Set a variable to the data element - javascript

Setting up a Flickr script... In my ajax success function, how would I put a var in with the actual this element? I know this and $(this) represent different things. Hard to write out, so I'll use my code examples to explain better.
I have my function set with the defined variables: function flickr_feed(flickrID, flickr_count, photo_size) {, which the variable in question is the photo_size
Using a condition to set the getSize variable from the readable format in photo_size:
if (photo_size == 'square') var getSize = 'url_sq';
I then dump that getSize into the ajax url:
url: 'http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + flickrAPI + '&user_id=' + flickrID + '&per_page=' + flickr_count + '&page=0&extras=' + getSize + '&format=json&jsoncallback=?',
The problem I'm having in the success function is setting that getSize var to the element.
success: function(data) {
$.each(data.photos.photo, function() {
var photoID = 'http://www.flickr.com/photos/' + flickrID + '/' + this.id;
var photoSrc = this.getSize;
console.log(photoSrc);
});
}
In this result, photoSrc returns undefined. But if I manually set photoSrc to this.url_sq, it's fine. Just can't figure out how to get the variable in there to work the same way.
Apologies for the horrible explanation. If it makes sense at all, any help would be greatly appreciated.
EDIT: My experience with $.ajax is limited. But from what I gather, this refers to the returned data. So in that sense, the photoSrc returns undefined as it is thinking getSize is a result within the data, which it isn't. So how would that be written so that it would use the actual getSize value?
EDIT: Here's a pastebin of the script: http://pastebin.com/KGCUgAet

Cache your this before your ajaxRequest
var originalContext = this;
$.ajax({
success: function() {
$.each(data.photos.photo, function() {
originalContext // Available here
this // Current object under iteration
});
}

Sorted it out with writing the photoSrc var like this: var photoSrc = this[getSize];
Thanks Sushanth for confirming my question about this and the returned data. That helped figure it out.

Related

JQuery ajax success callback never garbage collected

Please excuse my funny looking JS. Its compiled Coffee Script.
When some specific things on my WebApp happen, I run the following callback function to start a JSON get request:
GmScreen.prototype.requestPcUpdate = function(id) {
var currentUrl, self, url;
currentUrl = window.location.href;
url = currentUrl.substr(0, currentUrl.lastIndexOf('/')) + '.json';
self = this;
return $.ajax({
url: "/chars/" + id + ".json",
type: "GET",
error: function() {
return self.onPcUpdateError(this);
},
success: function(pc) {
return self.onPcUpdateReceived(pc);
}
});
};
The success callback function is as follows:
GmScreen.prototype.onPcUpdateReceived = function(receivedPc) {
var pcObj;
if (!(receivedPc['id'] in this.allPcs)) {
console.error("No PC with ID " + receivedPc['id'] + " known!");
}
pcObj = this.allPcs[receivedPc['id']];
pcObj['cmlNode'] = new CmlCharacter((new DOMParser()).parseFromString(receivedPc['cml'], 'text/xml').documentElement);
return this.notifyPcChangeListeners();
};
In the callback function, I create an XML document (and a wrapper object based on it) and assign it. When the next update for the same id arrives, the document and the wrapper object can be garbage collected.
But that never happens.
In Firefox, I see that the Dominator keeping this from being garbage collected is something called mPromiseObj.
This is drastically impacting the performance of my web app over time. How can I get this thing deleted?
Turns out, I screwed up my callbacks. In the cause of notifyPcChangeListeners, a new Listener was created that would have called onPcUpdateReceived eventually.
So keeping the garbage collection from cleaning this up is completely correct.

Ajax Request wont work unless I use alert() [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've been trying for hours to get this to work, but it's just not budging; I have the following code:
var text = "";
function getText(c1, c2)
{
url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=" + c1 + "-" + c2 + "_relations&prop=revisions&rvprop=content"
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: url,
success: function (data) {
var obj = (data.query.pages );
var keys = [];
for(var k in obj) keys.push(k);
if (keys[0] == -1) {
//Link doesnt exist
text = "-1";
return text;
}
//Link Exists
else {
link = "http://en.wikipedia.org/wiki/" + c1 + "-" + c2 + "_relations"
text = c1 + "-" + c2 + " Relations"
return text;
}
}
});
return text;
}
var a = (getText(country1, country2))
alert(text);
alert(a);
I'm making an ajax request; a simple inquiry to see if wiki has a page between any 2 given countrie.
If I use alert inside, it works fine, and it returns the correct data inside the text variable. However, when the getText function is called outside, the text variable is always empty. I've tried everything I can think of, including getting the app to sleep for some time, but even that didn't work. I know the async doesn't work from ajax 1.8 onwards, but is there anyway around this?
Thanks in advance.
It is because the asynchronous behavior of ajax. You can't return values from ajax like this way. Because the function will not wait for the success event to happen.
When you put an alert inside that function, success event may occur before the user clicks on alert. That is why it returning value. Otherwise it will not return the value.
Its not a good practice to use async : false in ajax calls. It will freeze the browser.
Good practice is to call a method from the ajax success with the returned data, then do operations with that data inside the function.

Ajax Prototype To Jquery Conversion For Innerhtml Updates

I am attempted to use jquery instead of prototype for the first time. I have a form, when you change the country on my dropdown I would like to then call another script that will bring up the appropriate list of states/provinces. In prototype I would have just used:
function getstates(form) {
document.getElementById("stateresult").innerHTML="<img src='images/ajaxshippingload.gif' border='0'> Processing...";
var checkingurl="shopgetstates.asp";
var pars = 'country=' + form.country.value + '';
var url = checkingurl + '?' + pars;
var target = 'stateresult';
var myAjax = new Ajax.Updater(target, checkingurl, {method: 'post',parameters: pars});
}
I am attempting to convert this into query with little success. I have come up with:
function getstates() {
$.ajax({type:'POST', url: 'shopgetstates.asp', data:$('#ListingForm').serialize(), success: function(response) {
$('#ListingForm').find('.stateresult').html(response);
}});
return false;
}
But I think this is overkill considering I only need to grab the selected value of 1 dropdown. Is there any easier way to accomplish what I am looking to do?

Javascript Array loses data

I'm having trouble getting my information into an array in an ajax call, if I alert the information right after I insert it into the array it works fine, but if I do it at the end it alerts unidentified. I made sure that books is declared outside so it doesn't interfere.
var books = [];
$.ajax({
url: 'getFolderContents.php',
dataType: 'json',
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
},
error: function()
{
alert("error");
}
});
alert(books[0]);
Your
alert(books[0]);
will be executed while the Ajax call is running and therefore will not have any elements at this point of execution yet. Ajax is asynchronous - while you are doing a request to your PHP script your script continues execution.
Put all actions with books in your success function.
Another hint: As of jQuery version 1.8 you cannot longer use the parameter async: false to create a synchronous "A"jax call. You have to use the callback functions. Have a look at the docs for $.ajax
Your array hasn't lost any data; the data hasn't been put in there yet. The 'A' stands for "asynchronous", meaning your success callback hasn't run yet at the time you call the alert.
Put the alert inside your callback instead:
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
alert(books[0]);
},
Your alert is executing before the success function is called. Perhaps seeing the same code using a promise will make things clearer.
$.ajax( url: 'getFolderContents.php', dataType: "json" )
//the then function's first argument is the success handler
.then(function( data ) {
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
alert(books[0]
});
});
I always feel this syntax makes async stuff make more sense. Otherwise this code functions exactly like Blazemonger's correct answer.
Your AJAX call is asynchronous, that's why it is undefined.
The alert at the end happens before the ajax success callback, because ajax is asynchronous.

Setting object properties using AJAX

I am newbie in OOP and I try to build an object using ajax request. What I need is to get 'responseArray' in JSON format and than work on it.
function adres(adres) {
this.adres_string = adres;
var self = this
$.ajax({
type: 'POST',
url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0",
success: function(data) {
self.responseArray = eval('(' + data + ')')
}
})
//Method returning point coordinates in EPSG:4326 system
this.getLonLat = function() {
var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat);
return lonlat;
}
}
The problem starts when in appilcation code I write:
var adr = new adres('Zimna 3, Warszawa');
adr.getLonLat();
This returns nothing as there is no time get the response from the server.
How to write it properly in the best way? I've read about when().then() method in jQuery. This may be OK for me. I just want to get know best practise
This is how AJAX works (notice the A-synchronous part). You are right, the moment you call adr.getLonLat() response did not yet came back. This is the design I would suggest: just pass callback function reference to adres constructor:
function adres(adres, callbackFun) {
//...
success: function(data) {
var responseArray = eval('(' + data + ')')
var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat);
callbackFun(lonlat)
}
and call it like this:
adres('Zimna 3, Warszawa', function(lonlat) {
//...
})
Few remarks:
adres is now basically a function, you don't need an object here.
do not use eval to parse JSON, use JSON object.
Are you sure you can POST to http://nominatim.openstreetmap.org? You might hit the same origin policy problem
where is the i variable coming from in responseArray[i]?

Categories

Resources