Creating custom JavaScript object from data returned by jQuery AJAX request

I want to create a custom javascript object which contains data returned from a jQuery AJAX request, but I don't know which is the right way to do it. I was thinking maybe one way could be to include the AJAX request inside the constructor function so the object is created like this:

// Constructor function function CustomObject(dataUrl) { var that = this; $.ajax(dataUrl, { success: function (json) { that.data = $.parseJSON(json); } }); } // Creating new custom object var myObject = new CustomObject('http://.....');

Another way may be to use a function which does the AJAX and then returns the new object based on the data from the AJAX response.

function customObject(dataUrl) { // Constructor function function CustomObject(data) { this.data = data; } $.ajax(dataUrl, { success: function (json) { var data = $.parseJSON(json); return new CustomObject(data); } }); } // Creating new custom object var myObject = customObject('http://.....')

I would like to know what is the best practice when doing something like this, as well as advantages/disadvatages of different methods. Maybe you can point me to some article or example on something similiar to what I am trying to do.

Thanks in advance.

-------------Problems Reply------------

I think this would be a better approach, it makes your CustomObject only knowledgeable about the data it contains. Here you delegate the work of creating objects to a factory, and pass in a callback to get a reference to the created object, since ajax is asynchronous. If you don't mind making it synchronous, then the createCustomObject function can just return the instance, and the callback can be removed.

function CustomObject(data) {
this.data = data;
}

var factory = (function(){
function create(dataUrl, objectClass, callback){
$.ajax({
url: dataUrl,
success: function (data) {
callback(new objectClass(data));
}
});
}
return{
createCustomObject: function(dataUrl, callback){
create(dataUrl, CustomObject, callback);
}
};
})();

// Creating new custom object
var myObject = null;
factory.createCustomObject('http://..', function(customObject){
myObject = customObject;
});

I'd argue that the second method is better because then you only create a new CustomObject once the script is actually fully prepared to do so (i.e. it has the data it needs from the AJAX request).

Category:javascript Views:0 Time:2012-02-14

Related post

  • Reload jsTree data return in an Ajax Request 2011-09-13

    My jsTree contains html data that is set when the tree loads (see javascript below). This works correctly. However, I want to be able to reload the entire tree in an Ajax request based on certain user actions. I basically need to reload all the tree

  • Is there a size limit to the amount of data returned by an Ajax Request? 2009-12-18

    I've been having this problem in the Chrome browser. i use jquery's ajax post. Ajax is supposed to return a really long raw html. When I do it in FF3 and IE8 it works fine. But in chrome the data seems to be truncated. --------------Solutions--------

  • cannot display json data returned from jquery ajax call 2010-04-06

    can somebody please tell me, how can I display json data returning from the ajax call. I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { strArray = []; //new A

  • How to create a javascript object like Date()? 2011-10-01

    I wonder how is it possible to create an object for example MyObject() which it can act like javascript Date object when we +(new MyObject()) like: var a = new Date(); alert(+a); --------------Solutions------------- Your object needs to have a valueO

  • Javascript Object Properties go to undefined after ajax request returns 2010-06-17

    if you have an object and set a property for it, you can access that property in a function called on that object. but if you call a function and do an ajax request such that a different function is called from onreadystatechange, that secondary resp

  • handing data returned from jquery get request 2010-06-14

    I have a simple jquery script as follows: $('a').click(function() { //get the id of the song we want to play var song_id = $(this).attr("id"); //do a get request to get the information about the song $.get("http://www.site.com/v4/ajax/get_song_info.p

  • Why do I need to use .d to access data returned by jQuery AJAX? 2010-10-13

    I've put together some jQuery AJAX code using some tutorials I found on the internet. I'm new to jQuery and want to learn how to do things betters. I have a coworker who put together a beautiful web application using a lot of jQuery. The thing I'm mo

  • Passing data from a jquery ajax request to a wcf service fails deserialization? 2009-02-26

    I use the following code to call a wcf service. If i call a (test) method that takes no parameters, but returns a string it works fine. If i add a parameter to my method i get a wierd error: {"ExceptionDetail":{"HelpLink":null,"InnerException":null,"

  • nicEdit behavior when being returned from jQuery AJAX request 2011-08-14

    I am using nicEdit to add rich text editing to a textarea. I am using the Codeigniter MVC framework and jQuery to make a simple AJAX call to create a new textarea then applying nicEdit to this new textarea once it's returned from the AJAX call. Every

  • How to loop through delimited string returned by jQuery AJAX request 2011-03-30

    So the following jQuery is posting some values to a PHP script and getting back a comma delimited string: $.ajax({ type: "POST", url: "_js/changetags.php", dataType:'json', success: function(data){ arr = data.tagsinserted.split(','); $.each(arr, func

  • how do i pass data with & in jquery ajax request 2011-04-22

    Here is a scenario. when ever i pass following in a ajax request. $article = $('#article').val(); $.ajax({ url:'url.php', type:'post', data:'article='+$article, success : function(response){ alert(response) }); so if $article will contain following:

  • loop over the PHP data Returned to jquery AJAX Call 2012-01-30

    below is my $.ajax call to php $(document).ready(function() { $('ul.sub_menu a').click(function(e) { e.preventDefault(); var txt = $(this).attr('href'); $.ajax({ type: "POST", url: "thegamer.php", data:{send_txt: txt}, success: function(data){ $('#co

  • How to create a JavaScript object from JSON data returned from server 2012-02-25

    I need help, I want to create a function which returns an object from an AJAX request, so I can create a new object from data on the server like this: var foo = bar('api.php?x=y'); The function should take a query string as an argument, and the serve

  • Where to create custom IPrincipal object? 2011-04-28

    I am using Application_PostAuthenticateRequest event in global.asax to create custom IPrincipal object void Application_PostAuthenticateRequest(object sender, EventArgs args) { if (Context.User.Identity.IsAuthenticated == true) if (Context.User.Ident

  • Referencing Firebug Console Inside of a Custom Javascript Object 2010-08-10

    I have several custom Javascript objects and want to do some debugging via the Firebug console inside of them. However, if I try to use console.log(), I get an error about console not being defined. I tried referencing console as window.console and i

  • How to store a custom javascript Object in HTML DOM? 2010-10-01

    If I create a custom javascript Object using a constructor, Is it possible to persist the object between HTTP Requests? - like storing it in the DOM and use it conditionally ? Will the DOM Objects persist (all client side Objects) between the HTTP Re

  • custom javascript objects as properties of other custom javascript objects 2012-01-25

    I want to create some custom javascript objects some of which have properties which are other objects. I'm not sure what the syntax would be to do this. My pseudo code is below with the idea that I have a person object and an order object. The order

  • Creating a Javascript object to hold user's geolocation co-ordinates 2012-03-16

    I would like to create a Javascript object, let's name it 'geoloc' and place it inside a Javascript library I have created. This object will use the html5 geolocation API to store the position.coords.latitude and position.coords.longitude values of t

  • Error creating a Javascript Object 2012-03-11

    The line of code below, which I thought creates a javascript object, gives me the following error: Uncaught SyntaxError: Unexpected token { This is the line of code: var flyer2 = {"id":20,"img_url":"http:/

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.084 (s). 11 q(s)