Returning a Javascript object from server - javascript

Apologies for what is most likely an obvious question. In general terms, I would like write a client-side Javascript function that makes a request to my server; this would then return a Javascript object.
This seems to be a common thing, but I'm not entirely sure which techniques I should be using. Do I need to be running something like Node on my server to do this, or am I missing something basic? And is it possible to return a Javascript object directly, or would I return JSON and then convert this client-side into an object?
Googling seems to bring up a vast number of Ajax PHP \ ASP techniques, but I'm just using javascript.
Thank you very much in advance, and please do accept my apologies if it's a dense question.

The server would return JSON and JSON is javascript in object notation. The difference between JSON and a javascript object, is that JSON is a standard and has strict requirements, for example that property names and values are wrapped in double quotes.
You don't need a special server to return JSON. JSON is should be treated like XML or any other data format.
Returning JSON from a server is best done with JSONP if you want to avoid cross site scripting issues. You can read more about JSONP on
http://json-p.org/
http://remysharp.com/2007/10/08/what-is-jsonp/ and
What is JSONP all about?
Either way, JSONP or JSON and Ajax, you'll need to make sure your JSON is valid and the correct headers are sent.
Content-Type: application/json

if you send request to server, the application running at server will send back some data to browser, Json,XML,HTML, etc. what you should know is the data returned by server may have many types.
if you have no idea about the application in server, i suggest you can write some code running at server by using nodejs. in this way you do not have to study another language like php,java,python.

Loading a javascript from the server via AJAX/PHP as a kind of dynamic plug-in to the current page is an obvious technique to keep code in the page small and maintainable (and generic ...?)
I use jQuery.getScript for this. It has a callback function which will be executed when the code is loaded an has been initially run. Just look at http://api.jquery.com/jQuery.getScript/

Related

Pass Java ArrayList to javascript

I know this issue have been already discussed Get Request Attributes in JavaScript, but it still doesn't work for me. So, it isn't duplicate.
I renew my page asynchronously via javascript: send request (XMLHttpRequest object) and set XMLHttpRequest.onreadystatechange = handleResponse().
Question: It is possible to handle java ArrayList request attribute (that come from server with response) in my handleResponse() function?
All iteraction preceed in the same way as in the link above
It is possible and actually quite simple. Just use an encoding format, like JSON. There are plenty of Java JSON libraries out there. Have a look here as well. Then from inside JavaScript, you can convert JSON to actual JavaScript objects and do whatever you want with them.

How is this realtime database filter done?

On this page there is a form on the left side that filters MySql query results in real time.
My guess it has something to do with AJAX or similar language.
Can someone point me at what direction should I look to make a realtime-changing search results filter form.
Or what should I search for to find a working example or tutorial to make something like that?
Yeah, it's definetly AJAX, but AJAX is not a programming language, it's Asynchronous Javascript and XML. Take a look at http://api.jquery.com/jQuery.ajax/. jQuery is probably the easiest way to do something like that.
if($('#checkbox').is('::checked')){
//code to be executed
}
Yes, this is Ajax, but Ajax is not a language.
Ajax is:
Asynchronous
Javascript
And
XML
You use normal standard-methods of Javascript to send requests to a server and then process the results to update the content of the html-document. For communication with the server you can use XML, but there is no need the stick on XML. I prefere JSON because it produces less traffic.
XML:
eXtended
Markup
Language
JSON:
Java-
Script
Object
Notation

Is getting JSON data with jQuery safe?

JSON allows you to retrieve data in multiple formats from an AJAX call. For example:
$.get(sourceUrl, data, callBack, 'json');
could be used to get and parse JSON code from sourceUrl.
JSON is the simply JavaScript code used to describe data. This could be evaled by a JavaScript interpreter to get a data structure back.
It's generally a bad idea to evaluate code from remote sources. I know the JSON spec doesn't specifically allow for function declarations, but there's no reason you couldn't include one in code and have an unsafe and naive consumer compile/execute the code.
How does jQuery handle the parsing? Does it evaluate this code? What safeguards are in place to stop someone from hacking sourceUrl and distributing malicious code?
The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.
Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.
You can find such a function at https://github.com/douglascrockford/JSON-js/blob/master/json2.js.
See JSON and Broswer Security for a good discussion of this area.
In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.
NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?".
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback.
$.getJSON() is used to execute (rather than using eval) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).
From Douglas Crockford site about The Script Tag Hack (jsonp):
So the script can access and use
its cookies. It can access the
originating server using the user's
authorization. It can inspect the DOM
and the JavaScript global object, and
send any information it finds anywhere
in the world. The Script Tag Hack is
not secure and should be avoided.
Both IE 8 and Firefox 3.1 will have native JSON support, which will provide a safe alternative to eval(). I would expect other browsers to follow suit. I would also expect jQuery to change its implementation to use these native methods.
All browsers I know of disable cross-site requests through Ajax. That is, if your page sits on my.example.com, you can't load anything using Ajax unless its URL is also at my.example.com.
This actually can be something of a nuisance, and there are ways for an attacker to inject source in other ways, but ostensibly this restriction is in place to address exactly the concern you mention.

Generate JavaScript objects out of Django Models

I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions get(), save(), all() and count() available to the client. Additionally, it would be great to have the field list of the model already available in the generated JavaScript object.
Whether the current user can read or write the records is a separate issue I will deal with using Django's authentication. For the time being, retrieval would be a start.
In short, is there code that would generate a JavaScript model from a Django model?
Thanks.
It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the methods) but you'd need to expose a web service that can handle every kind of DB-API call. I can't even begin to imagine where to start and the security issues may be too numerous to easily overcome.
The alternative (and much simpler) approach would be to use one of the various Django REST modules and JSON serialization. You could perform an AJAX GET request on a resource, which can be identified by a series of query parameters that would be equivalent to chained queryset filters. This would return the JSON representation of the model's values. You can then modify the JavaScript object and use an overloaded AJAX POST request to persist the changes back to the server. You wouldn't have access to the model's methods, so that functionality would have to be reimplemented but making any changes to a model should be straightforward enough - This is basically the JavaScript equivalent of using an HTML form to modify data.
You need a data serializer. You can do it with django built in serializers. It is documented on official django site. djangoproject_topics-serialization
I've started a project that I think does exactly what you're looking for. You can find it at
github_bumby_jslib. It currently only supports get(), but I'm hoping to extend this soon. Feel free to contribute patches :)
jslib is a Django application aiming to simplify AJAX integration with your Django projects.
It sounds like you want to JSON encode your object data. See JSON.org for more on the data format.
So it's been a while since I posted the original question and since then there has been a number of developments in Djangoland. Not least of which is a great little library called Django REST Framework. I will be using it on a new project and it's looking pretty kewl.
http://www.django-rest-framework.org

XmlHttpRequest return values

I'm looking for (arguably) the correct way to return data from a XmlHttpRequest. Options I see are:
Plain HTML. Let the request format the data and return it in a usable format.
Advantage: easy to consume by the calling page.Disadvantage: Very rigid, stuck with a fixed layout.
XML. Let the request return XML, format it using XSLT on the calling page.Advantage: the requested service is easily consumed by other sources.Disadvantage: Is browser support for XSLT good enough?
JSON. Let the request return JSON, consume it using javascript, render HTML accordingly.Advantage: easier to 'OO-ify' the javascript making the request. Disadvantage: Probably not as easy to use as the previous two options.
I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons.
While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?
If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works.
If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a proxy to provide the information in JSON or HTML too, but having XML as the main source is definitly worth the time and effort while building the app.
Like #John Topley said: it depends.
I'd agree with John Topley - it depends on the application. There's a good article on quirksmode that discusses the advantages and disadvantages of each format that you might want to read: http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html
I think this sort of depends on the level of "ajaxyness" your app is going to have. If your front end is a "rich client", al'a gmail, I'd go with the JSON solution, as you'd have to solve the problem of having client side view generation anyway. If you're using ajax sparingly, to provide simple messages to the user, update a few fields now and then, etc, then I'd go with option 1, since most of your view logic is already on the server.
I think trying to use XmlHttpRequest will be a huge headache, unless its the type of headache you don't mind - to do it properly you're almost reinventing the wheel. Then again, people like to reinvent wheels in their spare time, just to say, "Hey, I did it". Not me...
I would get a framework like prototype or Extjs, that has alot of data loading functions built in for XML and JSON, plus you'll get more predictable results, as the frameworks have event handlers to make sure your XmlHttpRequest succeeded or failed. Plus you get support for all the various browsers.
Different response format shouldn't be difficult to produce.
JSON works best for me, i like to keep OO in js, and don't know how to parse XML well :)

Categories

Resources