Passing json object to python using angularjs - javascript

I'm new to angularjs and python and I have this problem. I've been trying to pass in the data of a form to Python server side using angularjs. I've converted the form to a json object before sending it over in my .js controller.
controller.js:
jsonObj = this.form.toJson;
$xhr('POST','/form/processform',jsonObj,function() {
alert("Done!");
window.load("/");
}, function(){
"Request failed";
});
Python:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json
class processForm(webapp.RequestHandler):
def post(self):
form = json.loads(self.request.body)
# process forms
self.redirect("#/")#redirects to main page
I recieved an error called "JSONDecodeError: No JSON object could be decoded". I've tried to replace the 'POST' to 'JSON' but it does not seem to work as well. I've also read up on $resource in angularjs, but i'm not sure how to use it.
Is this because of the wrong usage of $xhr? Any help will be greatly appreciated! :)

Acording to JSONDecodeError the jsonObj variable is not containing a valid JSON object.
I believe problem is here:
jsonObj = this.form.toJson;
You shoud call the toJson method instead of assiging it to a variable:
jsonObj = angular.toJson(this.form);

Related

How to save Json in the django database from Javascript

I will generate a json and save it in a string variable, and I need to save the whole json in my database.
I have a view
class DashboardView(TemplateView):
template_name = 'votes/dashboard.html'
in this template, I have javascript, and in this javascript I'm generating Json and saving it in a js variable, and I want to put the json in the variable into the DB.
As I'm gonna create a object for the jsons, I'll change templateview to CreateView as It's gonna save.
But how is this json going to become available for the view to be saved ?
brief instruction
using jquery ajax:
$.post( "/your/url/for/store/json/data", { jsonField: jsonData } );
in your view:
def save_json_data(request):
...
data = request.POST.get("jsonField", "")
model = YourModel(json_field=data)
model.save()
...

Passing Javascript Variable to Python Flask [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
Submit a form using jQuery [closed]
(22 answers)
Closed 5 years ago.
I have read several postings on different examples for passing a javascript variable to flask through post/get forms. I still don't understand how to do this. From my understanding, the form creates a post/get that can then be called and received by the python flask script. Can someone write up a very simple example on what this should look like?
Starting from creating a variable with any value in javascript and then making the post/get. Lastly what should the receiving end on python should look like and finally print the variable from python.
How I did this was using an ajax request from the javascript which would look something like this. I think the easiest way would be using JQuery as well since it might be a bit more verbose with pure javascript.
// some movie data
var movies = {
'title': movie_title,
'release_date': movie_release_date
}
$.ajax({
url: Flask.url_for('my_function'),
type: 'POST',
data: JSON.stringify(movies), // converts js value to JSON string
})
.done(function(result){ // on success get the return object from server
console.log(result) // do whatever with it. In this case see it in console
})
Flask.url requires JSGlue which basically let's you use Flask's
url_for but with javascript. Look it up, easy install and usage. Otherwise I think you could just replace it with the url e.g '/function_url'
Then on the server side you might have something like this:
from flask import request, jsonify, render_template
import sys
#app.route("/function_route", methods=["GET", "POST"])
def my_function():
if request.method == "POST":
data = {} // empty dict to store data
data['title'] = request.json['title']
data['release_date'] = request.json['movie_release_date']
// do whatever you want with the data here e.g look up in database or something
// if you want to print to console
print(data, file=sys.stderr)
// then return something back to frontend on success
// this returns back received data and you should see it in browser console
// because of the console.log() in the script.
return jsonify(data)
else:
return render_template('the_page_i_was_on.html')
I think the main points are to look up ajax requests in jquery, flask's request.json() and jsonify() functions.
Edit: Corrected syntax

JSON to JS with Django: SyntaxError: missing : after property id

I'm attempting to get a JSON file into a script. I can't seem to be able to get it there by serving it from the filesystem so I made a view that returns the JSON data to the page like so:
def graph(request, d): #d.data is the file in the database
data = json.load(d.data)
return render(request, 'temp/template.html', {'json': data})
In my JS:
var j = {{ json|safe }};
When I look at the source for the JS it shows the data in this format:
{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}
Which I read shouldn't be a problem. I don't have any variables called 'id' and yet I get the error in the title pointing to the provided line of JS.
Why could this be? Also how do I then use the objects from the JSON in my script?
Solved by using simplejson:
import simplejson as json
And everything else as above. This is because the built in json.dumps returns an array of unicode like:
{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}
When using simplejson that shouldn't be a problem.

Passing Python Objects to JavaScript through Django Template Variable

I have been able to pass primitive types such as integers like this, but I would like to pass more complicated objects, such as some the Django models that I have created. What is the correct way of doing this?
I know I'm a little late to the party but I've stumbled upon this question in my own work.
This is the code that worked for me.
This is in my views.py file.
from django.shortcuts import render
from django.http import HttpResponse
from .models import Model
#This is the django module which allows the Django object to become JSON
from django.core import serializers
# Create your views here.
def posts_home(request):
json_data = serializers.serialize("json",Model.objects.all())
context = {
"json" : json_data,
}
return render(request, "HTMLPage.html",context)
Then when I'm accessing the data in my html file it looks like this:
<script type = 'text/javascript'>
var data = {{json|safe}}
data[0]["fields"].ATTRIBUTE
</script>
data is a list of JSON objects so I'm accessing the first one so that's why it's data[0]. Each JSON object has three properties: “pk”, “model” and “fields”. The "fields" attribute are the fields from your database. This information is found here: https://docs.djangoproject.com/es/1.9/topics/serialization/#serialization-formats-json
For Django model instances in particular, you can serialize them into JSON and use the serialized value in your template context.
From there, you can simply do:
var myObject = eval('(' + '{{ serialized_model_instance }}' + ')');
or
var myObject = JSON.parse('{{ serialized_model_instance }}');
if using JSON-js (which is safer).
For Python objects in general see How to make a class JSON serializable

How can I pass JSON to client using Node.js + HBS + Express?

Consider, I am sending JSON to client as follows in render page of Express (using hbs as a view engine):
res.render('MyPage.html', { layout: false, PageTitle: 'Project Name', JSON_Data: {field1:'value',field2:'value2'}});
I am able to access and set title of html page by using {{PageTitle}}, following is the code.
<title>{{PageTitle}}</title>
Now I want to show JSON_data into alert popup.
I've tried following way, but getting Uncaught SyntaxError: Unexpected token {, while debugging in chrome is shows var jsonobj = [object Object]
function fbOnBodyLoad() {
var jsonobj = {{JSON_data}};
alert(jsonobj);
}
Could any body give some idea on How to access JSON_data and show in alert
Advance Thanks
to access the inner elements of the json object, try like this
var jsonobj = "{{JSON_data.field1}}";
may be this might solve the issue.
refer
Handlebars.js parse object instead of [Object object]
You could always register a Handlebars helper to format the object into a string format (such as by using JSON.stringify), and then use that helper in your view. http://handlebarsjs.com/block_helpers.html
For me it worked by doing in the server:
res.render('pages/register', {
title: 'Register Form',
messages: req.flash('error'),
countries:JSON.stringify(countries)
});
and then I used this countries variables to assign in angular controller like this:
angular.module('languagesApp', []).controller('DemoController', function($scope) {
$scope.algo = {{-countries}};
...

Categories

Resources