How to Parse JSON object in Django View from Ajax POST - javascript

I'm currently submitting data via a POST request using the below jquery ajax method and I'm successfully getting a return result in my console (see below) that displays the JSON request that was submitted to the server. However I CANNOT figure out how to parse the JSON object in my Django view. What do I write my view so I can Parse my JSON object and get a hold of "schedule_name" to execute the below command in my Django view. Please see a copy of my view below.
Schedule.objects.create(schedule_name = Schedule)
$.ajax({
type: "POST",
url: "{% url 'addSchedule' building_pk %}",
dataType: "json",
data: {"json_items" : JSON.stringify(Schedule_Info)},
success : function(data)
{
$('.todo-item').val(''); // remove the value from the input
console.log(data); // log the returned json to the console
console.log("success"); // another sanity check
alert("Sucess");
},
JSON output in console after submitting request
json-items: "{
"nameOfSchedule":{"schedule_name":"Schedule"},
"Rooms":[
{"room_rank":"1","room_name":"Room 101 "},
{"room_rank":"2","room_name":"Room 102 "},
{"room_rank":"3","room_name":"Room 103 "},
{"room_rank":"4","room_name":"Room 104 "}
],
"Users":[
{"user_name":"test1#yahoo.com"},
{"user_name":"test2#yahoo.com"}
]
}"
Django View
def addSchedule(request, building_id):
building_pk = building_id
b = Building.objects.get(pk=building_pk)
floor_query = b.floor_set.all()
master_query = floor_query.prefetch_related('room_set').all()
if request.is_ajax() and request.POST:
data = request.POST
### Input the schedule name in the datase by parsing the JSON object
return HttpResponse(json.dumps(data),content_type="application/json")
else:
return render(request, 'scheduler/addSchedule.html', {'building_pk' : building_pk,
'building_query': master_query
})

I resolved the issue by making the following changes to my Django
Django view
data = json.loads(request.POST.get('json_items'))
name = data['nameOfSchedule']['schedule_name']
Schedule.objects.create(schedule_name = name)

You could use the JsonResponse for that:
return JsonResponse({'this': "will be converted to json"});
See https://docs.djangoproject.com/el/1.10/ref/request-response/ for more info

Related

How to display search results with ajax in django project?

I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form.
At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax.
Views.py
def indexView (request):
form = FriendForm ()
friends = Friend.objects.all ()
return render (request, "index.html", {"form": form, "friends": friends})
def searchFriend(request):
if request.method =="POST":
form = FriendForm (request.POST)
if form.is_valid():
if request.is_ajax():
name = form.cleaned_data['name']
query = Friend.objects.filer(first_name__contains=name)
print(query)
return JsonResponse(list(query), safe=False)
else:
return JsonResponse(form.errors)
Main.js
$(document).ready(function() {
$("#form1").submit(function() { // catch the form's submit event
var search = $("#searchField").val();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
method: 'post',
dataType: 'json',
url: "search/ajax/friend/",
success: function(data) { // on success..
console.log(data)
}
});
return false;
});
});
Is your query getting printed in terminal ?
Friend.objects.filer use filter instead of filer
and use type: 'post' instead of method: 'post',
and add data: $(search).serialize(), instead of data: $(this).serialize(),

How to make a POST request using jquery and access POST data in a django view (not generic views), without using csrf token?

I have dictionary in javascript something like this:
var data = {"name":"nitin raturi"}
Now I want this data to be accessed in my django view something like this:
def my_view(request):
data = request.POST
How to send data to my url using jquery?
lets do this.
This is your dictionary in javascript:
var data = {"name":"nitin raturi"};
Now define a function that will make a post request using jquery.
function send_data(data, callback) {
// callback is a function that you should pass to handle your response
$.ajax({
type: "POST",
url: '/sample-url/', // change this to your url here
data: {"data": JSON.stringify(data)},
success: function (response) {
callback(response);
},
});
}
Now use the send_data function like this:
send_data(data,function(response){
//handle your response here
console.log(response);
})
Now you can access your data in your django view like this:
import json
#csrf_exempt
def my_view(request):
data = request.POST.get('data')
data = json.loads(data) # this will convert your json data to python dictionary
name = data.get("name")
// Handle your data and return anything you wish
return render(request,"index.html",{})

Problem sending information between Django template and views using AJAX call

I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.
With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.
This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.
var arr = { City: 'Moscow', Age: 25 };
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = norm_data.toString();
alert( norm_data );
}
});
This is my Django URLs code to receive the request:
path('applications/1/normalize', views.normalize, name="normalize")
This is the python view to retrieve the code and send it back to the javascript file:
from django.http import JsonResponse
def normalize(request,*argv,**kwargs):
norm_data = request.POST.get(*argv, 'true')
return JsonResponse(norm_data, safe = False)
You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = JSON.stringify(norm_data);
alert( norm_data );
}});
I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue
from django.http import JsonResponse
def normalize(request):
data = request.body.decode('utf-8')
#data now is a string with all the the JSON data.
#data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
data = data.split("&")
data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
#data is like this now "{'City': 'Moscow', 'Age': '25'}"
return JsonResponse(data, safe= False)

Converting list of objects to a JSON string

UPDATE: It was a programming error, please don't post answers. This question will be deleted. If you've already posted an answer please delete
I'm trying submit a form using jQuery and ajax. One of the fields is a list of objects, like this:
data = [{"id":1},{"id":2}]
I usually use JSON.stringify(data) but that didn't work this time, the server gets [object Object],[object Object]
When I do alert(JSON.stringify(data)) it works but something is changing it back to objects.
I'm using the jQuery form plugin and appending this data to the data attribute of the options object:
function showRequest(formData, jqForm, options) {
return true; //does nothing
}
var options = {
beforeSubmit: showRequest,
url: '/search.php',
iframe: true,
iframeTarget: '#iframe',
type: 'post'
};
options.data.data = JSON.stringify(data);
$('#myForm').ajaxSubmit(options);
How do I convert this to a JSON string that I can send it to the server?
This can be done using jQuery and without using JSON libray.
example using php on back-end
var data = [{"id":1},{"id":2}];
$.ajax({
type : 'POST',
url : 'test.php',
data: {my_array:data},
success : function(data){
//alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//alert("error");
}
});
in php
$my_array= $_REQUEST['my_array'];
print_r($my_array);
it will print
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
)
)

Django/python is converting my post data from JavaScript

When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending:
info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' }
Yet when I access it in the django request I am seeing:
u'{\'mid\':1,\'sid\':27,\'name\':\'aa\',\'desc\':\'Enter Info\'}
When I try to parse this with json.loads it dies with an invalid JSON message.
I am posting with:
data.info = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }";
$.ajax({url: cmdAjaxAddress,
type: "POST",
data: data,
success: function(txt) {
result = txt;
},
async: false });
I am reading the POST in django like this:
if request.is_ajax() and request.method == 'POST':
infoJson = request.POST['info']
info = json.loads(infoJson);
Any help would be appreciated.
How are you encoding your JSON string? The single quotes need to be double quotes, per the spec:
In [40]: s1 = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }"
In [41]: simplejson.loads(s1)
JSONDecodeError: Expecting property name: line 1 column 1 (char 1)
In [42]: s2 = '{"mid":1,"sid":27,"name":"aa","desc":"Enter info" }'
In [43]: simplejson.loads(s2)
Out[43]: {'desc': 'Enter info', 'mid': 1, 'name': 'aa', 'sid': 27}

Categories

Resources