How to create a JavaScript object from JSON data returned from server

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 server returns data as JSON.

Can you show me how to do this using jQuery, do you have any ideas/examples?

I will expand on my question because it seems I am doing it all wrong. I am trying to create a web application based on live data (stock quotes) so it has to constantly request updated information from the server. When the app is initialized the first step is getting static data from the stocks to be included (such as ticker symbol and issuer), I am thinking the best way to do this is to have a database on the server and an API which does the query and returns the selected stock data as JSON. The next step is to make a request to another API on the server which returns live data (such as price and volume) on the selected stocks, when the complete data is returned it is rendered to html using a template engine. Then the app has to constantly call the second API on some interval to update the live data and render again. Also you should be able to make a new selection of stocks and start the process again.

I think the best way to structure an app like this is to have the data inside a custom object which has its own methods to modify the data later (for example sorting and filtering), so if foo is my object with the stock data I can do something like foo.sort(), or something like foo.render() to create the html representation of the data. That is why I thought the best way was to create an object from the data returned by the AJAX call. Could you please tell me if this is the right way to structure an app like this or point me in the right direction?

Thanks

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

AJAX is asynchronous by definition, so it doesn't fit your question particularly well. I would recommend using jQuery.ajax (see reference) with a callback instead:

$.ajax({
url: 'api.php?x=y',
dataType: 'json',
success: function (foo) {
// Do stuff here using 'foo'
}
});

If JSON string is what server responds with, it's easy to transform it into JS-object with just...

var resp_object = JSON.parse(response);

You are thinking synchronously in your approach.

This means that you think that your function call "bar('api.php?x=y')" should immediately return the retrieved data/object. This has the disadvantage that the code execution in the browser is blocked while waiting for the answer.

To overcome this, you would need to create an asynchronous callback handler (the "success" handler when working with "jQuery.ajax"), as user595228 pointed out before. The code that renders the returned information would go into this handler.

For the question how to structure the code, it depends on how complex the data you get is and how often you use it on your application. If its complex and gets used in several places, it may make sense to create a data object with helper function, to avoid code duplication and put the code regarding your data in one place. If you only render them in one place and the only thing you do is a simple sort and display, i'd go with placing that logic in a simple function, to reduce complexity.

You can create a Jquery plugin and hook your object into. Example:

var foo = tablesort({}); // tablesort is plugin Jquery
foo.sort();

You need implement sort method in Jquery plugin, it mean: get data using ajax from server and fill object's attribute or do something

Is the live data being pushed to you? By that I mean if you don't have something listening at the moment the data goes out over the wire you miss it? Or does it build up in a queue waiting for you to poll it and get it?

If you have the first situation, you can either have your server get the data from the stock service and queue it for you - which brings into question how do you handle the queues for multiple users. Or you can set up either a websocket (HTML5 not supported in all browsers) or take a look at a comet solution (which may involve either a flash object or lots of fast polling).

If you have situation number two, then you can use Ajax to grab the data blocks that are available on a timer. You need to use the asynchronous aspect of ajax or your screen can freeze up waiting on responses. Use something like jquery to help you with that process - no need to reinvent the wheel.

I usually prefer to keep the presentation of the data separate from the data itself. Instead of adding functions to the object after receiving it from the server, I suggest passing the data objects around.

Example:

function renderStockData(data) {
// build and return HTML from data
}

function loadStockData(url, callback) {
$.ajax({
url: url,
dataType: 'json',
success: callback
});
}

// Later that day...
loadStockData('api?stock=GOOG', function (data) {
var renderedHtml = renderStockData(data);
// ...
});

Is this the type of advice that you're looking for?

Category:javascript Views:1 Time:2012-02-25

Related post

  • Create new NSDate object from the date returned from UIDatePicker 2010-07-24

    How to create new NSDate object from [myUIDatePicker date] ? --------------Solutions------------- You don't need to create a new NSDate object, you can just use the one it gives you. NSDate *chosenDate = myDatePicker.date; If you really need to creat

  • Creating custom JavaScript object from data returned by jQuery AJAX request 2012-02-14

    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 s

  • What's the difference between Javascript Object and JSON object 2011-06-27

    Can anyone tell me the difference between Javascript Object and JSON object with an example? --------------Solutions------------- A Javascript object is a data type in Javascript - it makes sense only in Javascript. Often you see a Javascript object

  • Reading a javascript object as JSON on POST 2011-09-13

    I read that "javascript is JSON" in other SO posts. I am having difficulty translating this theory to my application. I perform a POST with jQuery $.ajax({ type: 'POST', url: 'Pricing/Create', data: items, success: function () { alert('successfully c

  • Javascript object Vs JSON 2011-11-28

    I want to understand the basic differences clearly between Javascript object and JSON string. Let's say I create the following JS variable: var testObject = {one: 1,"two":2,"three":3}; Q1. Is the key/property name valid both with/without quotes? (e.g

  • Complex Javascript objects to JSON Objects 2010-05-24

    Duplicate: http://stackoverflow.com/questions/2891476/converting-html-tag-object-to-json-object Hi, Is there is any Javascript API that converts complex Javascript Objects To JSON String??? --------------Solutions------------- I don't think what you'

  • convert javascript object into json string apart from using JSON.Stringify 2011-04-13

    hii i am trying to convert a javascript object to JSON string . are there any alternative apart from JSON.stringify() ?? cause the method is giving error in IE 7 .... its works perfect in IE8 onwards and other browsers . so just wanna know are there

  • 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:/

  • 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

  • Retrieve json data from a server without using jsonp? 2012-04-16

    I need to write a JS, which is able to request and display json data from a server in the company I work. This server just represents json data, it does not handle any callback-function, therefore I can't request via jsonp. I try to request the data

  • CSRF: can the JSON data returned by a POST request be stolen? 2008-12-27

    Can the JSON data, returned by a POST request be stolen by a cross-site request forgery attack? --------------Solutions------------- It cannot be done using JS, but I'm not sure about Flash's cross-domain request. In JS POST request can be made via f

  • 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

  • getting json data from php server with """ 2011-06-30

    My iphone app getting json data from php server. 2 basic questions, just to be sure : 1-In some of the json data fields, i see """, is this how json send Quotes, and I need to clean it in the iphone app ? or there is elegant and clean way to

  • IE 8 partially cut of my JSON data return from WCF service 2012-10-28

    Hi All, I am using ExtJS treepanel and ajax call to wcf webservice and return JSON array. My service return array. If array count is less than 2, then IE partially cut of my JSON data return from WCF service. But FireFox is working fine with same JSO

  • How would I save my Javascript objects with JSON/PHP/Mysql, to re-load them upon user return? 2011-01-29

    I'm working to create a "sandbox" of sorts, where numerous users will login and create draggable "nodes" on their own "sandbox." I'd love to be able to have the app auto-save after every modification, but first things first--I'm trying to get my Java

  • Encoding Javascript Object to Json string 2011-07-24

    I want to encode a javascript object into a json string and I am having considerable difficulties. The Object looks something like this new_tweets[k]['tweet_id'] = 98745521; new_tweets[k]['user_id'] = 54875; new_tweets[k]['data']['in_reply_to_screen_

  • Re-populate complex javascript objects from JSON 2009-10-08

    Say I have a web form that consists of a input text field, an Add button, and a Submit button. A user can add text to a div by typing some input and clicking Add, which will dynamically (using javascript) append the div with whatever they typed. Also

  • create new javascript object from variable 2011-04-30

    i would like to create a new object in javascript (using simple inheritance) such that the class of the object is defined from a variable: var class = 'Person'; var inst = new class any ideas? --------------Solutions------------- You can do something

  • Javascript Object to Json. PHP can't decode serialized JSON 2011-09-16

    I have a javascript object which I am encoding to Json and sending data to PHP. Unfortunately, PHP can't decode JSON string to array. I am lost at this point. Jquery sendData = {city: 48, fullName: 'John'}; sendData = JSON.stringify(sendData); $.get(

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

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