What am I doing Wrong? - Django JSON response and JQuery - javascript

I am working on a small website and I need to send thread-post data through JSON.
This is the JSON object django serves:
[{"text":"Some sample text","id":"21","title":"Test Thread"}]
I saved this as a .js file and the following Javascript code works fine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("testjson.js",function(result){
$.each(result, function(i, field){
$("div").append(field.text + " ");
});
});
});
});
</script>
However when I change the getJSON url field to:
//localhost/wall/21/ - format: //localhost/wall/thread_id
It displays nothing. The web console of firefox does not display any errors either.
My view code is the following:
def thread_view(request, wall, Id):
if request.method == 'GET':
thread = api.get_thread(wall, Id)
if thread != None:
return HttpResponse(thread, content_type="application/json")
else:
return HttpResponse("No results")
else:
raise Http404
It takes information from the database and formats it into json using a simple serializer, and then sends the data.
What am I missing?
Extra info below...
Serializer:
from bson import json_util
class JSONSerializer(object):
def dumps(self, obj):
return json_util.dumps(obj, separators=(',', ':')).encode('utf-8')
def loads(self, data):
return json_util.loads(data.decode('utf-8'))
I am using Django 1.6, JQuery 1.1, Python 2.7
P.S
When I enter the following url:
//localhost/wall/21/
firefox displays the JSON object just fine and it's exactly the same as the one in the js file.
Any help will be appreciated.

Related

How to render data in django to AJAX?

I am trying to send a json value to ajax from django class based view and the data i am sending will be appended in html through ajax. but i am not able to send value from back end to front end successfully.
class DetailView(TemplateView):
template_name = 'list.html'
def get_context_data(self,*args, **kwargs):
context = super(DetailView,self).get_context_data()
list_view = GetList().get_data(self.request)
movie_list = list.json()
context['list']= movie_list
print(movie_list)
return context
So this code is sending only template value to the ajax data, when i do the console.log(data) on success call it shows me whole html code of the 'list.html' in both alert and console.log . But it prints all the values in cmd console.
cclass DetailView(TemplateView):
template_name = 'list.html'
def get(self,request):
list_view = GetList().get_data(self.request)
movie_list = list.json()
return HttpResponse(json.dumps(movie_list))
this code prints all the values on respective html, but doesnt call ajax function.so no values showing in console.log.
this is my ajax call,first i am trying to just see weather i'm successfully getting the values on success call or not.
<script>
$(document).ready(function(){
$.ajax({
method :'GET',
url: '/detail',
success: function(data){
alert(data)
console.log(data)
},
})
})
</script>
So, how can i achieve my desired result? I want to get value in ajax call so i cal show those values in a table which is in a list form
You can use JsonResponse to send json data. (You can see detail in docs here)
like below
from django.http import JsonResponse
class DetailView(TemplateView):
template_name = 'list.html'
def get(self,request):
list_view = GetList().get_data(self.request)
movie_list = list.json()
return JsonResponse(movie_list, status=200)
btw, you have to aware your data type. JsonResponse automatically serialize your data so you don't have to use json() for your data.

Failing to pass data from client (JS) to server (Flask) with Ajax

First time ever using jQuery to pass a dictionary filled through a JS script to my server written in Python (Flask) when the user hits a submit button (I read somewhere that AJAX was the way to go).
Something must be broken since in the server function described below, request.get_data() or request.form are None. If any seasoned programmer could give recommendation on how to set up a jQuery request, it would be much appreciated.
In Python, I have the following:
#app.route('/submit',methods=['POST'])
def submit():
info = request.form['info']
action = request.form['action']
...
To handle the dictionary info. On my html file, I load AJAX through:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
Define my "submit" button as followed:
<button class="btn" onclick="send(event,'s')" id="SUBMIT">Submit</button>
And handle the action through the script:
<script>
var dict = [];
function send(event,action) {
$.post('/submit', {
info: dict,
action: action
}).done(function() {
}).fail(function() {
});
}
...
</script>
Convert request.form to dictionary and print it you can able get the values
print(request.form.to_dict())

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.

Django - Ajax without JQuery lib

I am Learning and using Ajax without jQuery Lib. I created a simple view which renders a random number on to the template. I added a button and called the ajax function. However, clicking the button doesn't change the value on the screen. I checked in DOM (firebug) and it shows the someText.responseText is yielding the whole html rather than just the value, however it has the new value in that HTML. I am sharing this to provide more information on what I have found so far. I am new to this and experimented it with a lot for ex; I have checked "request.is_ajax():" but somehow the view does not find ajax in request. I have printed request on command line and the GET querydict is empty.
Obviously I am not doing something in the correct manner for Django. Please assist.
I have a view;
def home(request):
rand_num = random.randint(1,100)
return render(request, 'home.html', {'rand_num':rand_num})
and html and script;
<html>
<head>
<script type='text/javascript'>
var someText;
function helloWorld(){
someText = new XMLHttpRequest();
someText.onreadystatechange = callBack;
someText.open("GET", "{% url 'home' %}", true);
someText.send();
};
// When information comes back from the server.
function callBack(){
if(someText.readyState==4 && someText.status==200){
document.getElementById('result').innerHtml = someText.responseText;
}
};
</script>
</head>
<body>
<div id="result">{{rand_num}}</div>
<input type='button' value='Abraca dabra!' onclick="helloWorld()"/>
</body>
</html>
here is the url for this view;
url(r'^$', 'socialauth.views.home', name='home'),
I am learning this from an online tutorial.
That is because your AJAX endpoint is the whole view - I.e. your AJAX request asks for the whole rendered template.
What you want is just a number, so make a new view and URL to return just the number, and make the AJAX request to that.
AJAX isn't anything special, its just a way to make an asynchronous request to a URL and get the contents returned.
For reference, a view using something like JSONResponse:
from django.http import JsonResponse
def get_random_number_json(request):
random_no = random.randint(1,100)
return JsonResponse({'random_no': random_no})
Then in your frontend Javascript, fetch url for that view, which will give you only the JSON in your javascript variable via your AJAX call, and instead of all that document.getElementById('result') processing, you can just grab the variable from the json object.

Sending Data from Python (Flask) to Javascript?

I am trying to implement a drag and drop file uploader on my website. Files are uploaded immediately after they are dropped, and I would like to generate a URL with flask that will pop up under the previews. I am using dropzone.js. In the documentation for dropzone a sample is provided as a guide for sending data back from the server to be displayed after a file uploads. https://github.com/enyo/dropzone/wiki/FAQ#i-want-to-display-additional-information-after-a-file-uploaded
However, when I try to use url_for in the inline Javascript in my Jinja template that creates the dropzone, I am getting back a link that looks like /%7Bfilename%7D
Just to be sure I popped a quick print statement in there for the URL, and it comes out fine in the console.
My uploader in python:
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
if is_image(file.filename): # generates a shortened UUID name for the image
filename = shortuuid.uuid()[:7] + "." + file.filename.rsplit(".", 1)[1]
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#app.route ('/<filename>')
def uploaded_image(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
and the inline JS in my index.html template:
<script>
var mydropzone = new Dropzone(document.body, {
url: "{{url_for('upload_file')}}",
previewsContainer: "#previews",
clickable: "#clickable",
init: function() {
this.on("success", function(file, responseText) {
var responseText = " {{ url_for('uploaded_image', filename='{filename}')}} ";
var span = document.createElement('span');
span.setAttribute("style", "position: absolute; bottom: -50px; left: 3px; height: 28px; line-height: 28px; ")
span.innerHTML = responseText;
file.previewTemplate.appendChild(span);
});
}
});
Am I missing something fundamental here? Do I need to use something like JSON/Ajax (never worked with these but Googling always brought them up), because the URL is data send back from the server?
Simply:
Return the file path to the client:
def upload_file():
if request.method == 'POST':
# ... snip ...
return url_for('uploaded_image', filename=filename)
Remove the var responseText line in your on('success') function, since you will be getting the URL back in the response.
You are very close to getting it, but you will have to send the URL over JSON.
The issue is that you call url_for('uploaded_image') when the page first loads (in the Jinja template), before the URL is actually available. It is thinking you are asking for the url for a file called {filename}.
Try returning a JSON response from your POST request which has the new URL:
return jsonify({'fileURL':url_for('uploaded_image', filename=filename)})
From there, you can do whatever you would like with JS. What you have should work, just get the URL from responseText.
EDIT: Fixed return.

Categories

Resources