I have the below code to create a class in javascript…. Now i will only pass the ID of the ‘website’ and then via an ajax call i will get the rest of the information from the database (JSON ENCODED).
Now my only problem is that when i see whats in the object at the end its only showing the id.
The ajax calls works fine because if i alert this.address after success (ajax) its displaying the result.
What I presume is that I cannot set a property with an ajax request… Can you help?
function website(id) {
this.id = id; //id
$.ajax({ //website_information
type: "GET",
url: '/proc.php?proc=website_name&id=' + this.id + '',
success: function(data){
var tmp = $.parseJSON(data);
this.address = tmp.website_address;
this.name = tmp.website_name;
}
});
}
var obj = new website('20');
obj.alertwebsite();
console.log(obj);
There are two problems here. The first is that
$.ajaxis asynchronous. That means it returns before the request is complete. Thesuccessfunction is run when the request is complete, butobj.alertwebsite()will be run before.The second problem is the value of
thiswithin an AJAX callback. Within the callback,thisis set to an object containing all the settings for the AJAX call. This means you are settingaddressandnameproperties on this object. There are two ways around this. The first isthat = thisas in other answers. The nicer way is to use thecontextsetting in the AJAX call:This allows you to customise what
thismeans inside the callback. This is documented in the jQuery AJAX documentation.