How to use Django list of objects variable in AngularJS? - javascript

So I have a variable like this from Django:
[<Topic object>, <Topic object>]
I pass it to Angular using ng-init like this:
<div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} ">
I got syntax parsing error instead of a success.
angular.js:12520 Error: [$parse:syntax] http://errors.angularjs.org/1.4.8/$parse/syntax?p0=%3C&p1=not%20a%20primary%20expression&p2=16&p3=ProfileTopics%3D%5B%3CTopic%3A%20Topic""bject%3E%2C%20%3CTopic%3A%20Topic%object%3E%5D&p4=%3CTopic%3A%20Topic%object%3E%2C%20%3CTopic%3A%20Topic%object%3E%5D
at Error (native)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:6:416
at Object.s.throwError (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:210:32)
at Object.s.primary (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:207:6)
at Object.s.unary (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:206:174)
at Object.s.multiplicative (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:205:434)
at Object.s.additive (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:205:261)
at Object.s.relational (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:205:96)
at Object.s.equality (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:204:425)
at Object.s.logicalAND (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js:204:278)

You can't just send an object from Django to Angular. You need to serialize it to JSON first.
You can do that in a basic way with Django's built-in serializers, but the third-party project Django Rest Framework is more customizable and easier to use.

In order to get on Angular, I found this as an amazing guide.
In order to send it from Django, you might need to:
Convert those objects to dicts
Use JSONResponse to return data

Related

Access sessionStorage in template EmberJS

I have saved some data in sessionStorage (a large JSON response from ajax) in EmberJS, and wanted to know if there was a way to access that directly in template handlebars. If not, what would be my alternatives? I have tried {{sessionStorage.getItem("data"}} in template but it gives me an error saying "Expecting 'ID', got 'INVALID'".
You should set the item in sessionStorage to a variable in your component.js like this:
init:function(){
this.set('sessionStorageData', sessionStorage.getItem('data'));
}
and use it in your hbs like this:
{{sessionStorageData}}

Underscore.js: TypeError: rc is undefined when using templates

I'm using underscore.js to create templates. I am utilizing the rc variable discussed here and I'm getting rc is undefined messages in my firebug console along with this tidbit:
((__t=( rc.siteid ))==null?'':_.escape(__t))+
I tried sending in empty json as specified like so: var mytemplate = _.template([code], {}) as the issue comment suggested, but the error still persists and my templates don't work.
The solution for me was to always explicitly send in an empty json {} if I didn't have any options to send in. The code would look like this:
var mytemplate = _.template([code]);
$('body').append(mytemplate({}));
I'm creating this question/answer because I did not find a solution on SO or via google.

Converting PHP object to JSON object using only Javascript

I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!

building a tree/ nested tree view using html and javascript

I have the following JSON data. I would like to build a tree/ nested tree view using the following data.
The desirable output would be as follows:
["carbon.agents.vagrant-ubuntu-precise-64-a.avgUpdateTime", "carbon.agents.vagrant-ubuntu-precise-64-a.cache.overflow", "carbon.agents.vagrant-ubuntu-precise-64-a.cache.queries", "carbon.agents.vagrant-ubuntu-precise-64-a.cache.queues", "carbon.agents.vagrant-ubuntu-precise-64-a.cache.size", "carbon.agents.vagrant-ubuntu-precise-64-a.committedPoints", "carbon.agents.vagrant-ubuntu-precise-64-a.cpuUsage", "carbon.agents.vagrant-ubuntu-precise-64-a.creates", "carbon.agents.vagrant-ubuntu-precise-64-a.errors", "carbon.agents.vagrant-ubuntu-precise-64-a.memUsage", "carbon.agents.vagrant-ubuntu-precise-64-a.metricsReceived", "carbon.agents.vagrant-ubuntu-precise-64-a.pointsPerUpdate", "carbon.agents.vagrant-ubuntu-precise-64-a.updateOperations", "carbon.aggregator.vagrant-ubuntu-precise-64-a.aggregateDatapointsSent", "carbon.aggregator.vagrant-ubuntu-precise-64-a.allocatedBuffers", "carbon.aggregator.vagrant-ubuntu-precise-64-a.bufferedDatapoints", "carbon.aggregator.vagrant-ubuntu-precise-64-a.cpuUsage", "carbon.aggregator.vagrant-ubuntu-precise-64-a.memUsage", "carbon.aggregator.vagrant-ubuntu-precise-64-a.metricsReceived", "stats.gauges.echo_server.throughput", "stats.gauges.logstash.host.10.0.1.8.cpu", "stats.gauges.logstash.host.10.0.1.8.memory_free", "stats.gauges.logstash.host.10.0.1.8.memory_total", "stats.gauges.logstash.host.10.0.1.8.rx_byte", "stats.gauges.logstash.host.10.0.1.8.rx_packets", "stats.gauges.logstash.host.10.0.1.8.tx_byte", "stats.gauges.logstash.host.10.0.1.8.tx_packets", "stats.gauges.logstash.host.general.request_time", "stats.gauges.logstash.host.nginx-lb0.act_conns"]
I would like to achieve the following output:
I am able to parse the json, How would we achieve the view as above using HTML and JS in particular the folder and nested folder tree view?
Thanks
There's an online tool to do that. http://jsontree.com/ . You can try this to visualize you json data.
Also since you are interested in implementing a html/js solution. Try jsTree jquery plugin.
You can use this tool http://codedestine.com/json-editor.html to visualize your json. It has many more features to edit and create json.

How to exclude an object's id property before or during $.toJSON

I'm writing a custom REST adapter for ember-data users with a django rest framework app and need to build a JSON string to do POST/PUT. The only problem is I can't seem to chain another jQuery method after the $.toJSON that removes this.
So far I have an ember.js object that I plan to extract each property from, except my django app doesn't want the id to go along with the HTTP POST
I can get a legit string like so
$.param(record.toJSON());
This results in the following
id=0&username=dat
I'd like a quick way to exclude id when I do this toJSON (does this exist w/ out writing it by hand?) Using jQuery 1.8+
Thank you in advance
Turns out this was really simple
var json_data = record.toJSON();
delete json_data.id;
var data = $.param(json_data);
Now instead of
id=0&username=dat
I now get
username=dat

Categories

Resources