Problem sending information between Django template and views using AJAX call - javascript

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)

Related

Access ajax elements with django

i am using ajax to fetch django model and get results
views.py
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data':data,})
ajax request
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
if (data) {
console.log(data.title);
}
}
});
and i am getting this response from django
{"data": "[{\"model\": \"app.company\", \"pk\": 1, \"fields\": {\"title\": \"Facebook\"}}, {\"model\": \"app.company\", \"pk\": 2, \"fields\": {\"title\": \"Fabook\"}}]"}
my question is how i can access the title.
You here double serialized the value for the "data" key: first by the serializers.serialize(..) that constructed a string, and the you again serialize it (constructing an string literal), making it harder to obtain the elements.
We can prevent this, for examply by turning the JSON blob back into a vanilla Python object first:
from json import loads as json_loads
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data': json_loads(data), })
Then the AJAX call will receive a JSON blob where "data" does not map to a string, but a list of subdictionaries, making it easier accessible.
Here there are two results for your query, you can print the first title with:
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
console.log(data.data[0].fields.title);
}
});

Bad Request Error (400) in json while posting to restful api in javascript

I am getting the below error while sending post request ,
{"readyState":4,"responseText":"{\"error\":\"No of Planet names has to
be 4\"}\n","responseJSON":{"error":"No of Planet names has to be
4"},"status":400,"statusText":"Bad Request"}
My code
var myPlanets=['Sapir','Jebing','Enchai','Pingasor'];
var myVehicles=['Space rocket','Space rocket','Space rocket','Space rocket'];
$(function()
{
$.ajax({
type:'POST',
url:'https://findfalcone.herokuapp.com/find',
headers:{
Accept:'application/json',
},
data:JSON.stringify({key:"keyToken", myPlanets:"myPlanets",myVehicles:"myVehicles"}),
success:function(status){
alert('success');
},
error:function(status){
alert(JSON.stringify(status));
}
});
});
Your use of stringifying the fields is incorrect as it points myPlanets to the string "myPlanets" instead of the variable.
It probably because you aren't sending any data to the API. In your data attribute's value, you have written like key: "keyToken" which sends the string "keyToken" to the API. Instead if you intend to send the value of a variable, send it like this:
data: JSON.stringify({
key: keyToken,
myPlanets: myPlanets,
myVehicles: myVehicles // Note that I've removed quotes
})
while, the page is 404.
and try again with
headers:{
Accept:'*/*',
},

AJAX request cannot pass DateTime to server if using GET method

I have a form which uses Kendo controls, and when user click the button, an AJAX request gathering these controls' value will be sent to server and download a file based on these criteria. One of the controls is DateTimePicker.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '#Url.Action("MyGenerateReportMethod")',
async: true,
data: getViewModel(),
...
});
function getViewModel() {
...
viewModel.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return JSON.stringify({ para: viewModel });
}
public ActionResult MyGenerateReportMethod(MyModel para)
{
try{
...
}
}
public class MyModel
{
public DateTime? DateFrom { get; set; }
}
The above simplified code demonstrate my situation.
I have a POST ajax request to server, which passes a serialized JSON object including a Kendo DateTimePicker Value.
The server side action try to catch this JSON object as parameter and do the stuff which is irrelevant to this question.
My question is, for some reason I have to changed the request from POST to GET.
While it works using POST method, it does not work if I change "POST" to "GET".
I checked the request sent in Chrome's Developer Tools, It does sent the JSON object in the following format: (In Query String Parameters section in the Network Tab)
{"para": {
...
"DateFrom":"2016-04-13T16:00:00.000Z"
...
}
}
However, at server side, MyModel para does not seems to catch this object successfully (if I change from "POST" to "GET"). Other fields still can be bound while all DateTime fields become null.
Why is this happening, and how can I change the request from "POST" to "GET"?
Thanks.
EDITED
Based on some comments / answers, I have tried to modified the AJAX request to the following code, but it is still not working... (Same behavior)
$.ajax({
type: 'GET',
url: '#Url.Action("SumbitOutstandingReportList")',
data: getPlanViewModel(),
async: true,
...
}
function getPlanViewModel(){
var obj = {};
...
obj.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return { para: obj };
}
A GET does not have a body, so remove the contentType: "application/json; charset=utf-8", option (does no harm but its only applicable to a POST) and adjust the data so that the ajax call is
$.ajax({
type: 'Get',
url: '#Url.Action("MyGenerateReportMethod")',
data: getViewModel(),
...
});
function getViewModel() {
var obj = {};
...
obj.DateFrom = $("#DateRangeFrom").data("kendoDatePicker").value();
...
return obj; // return the object, not a stringified object containing another object
}
Note this assumes the value is in a format that matches your server culture, or in ISO format (e.g. the request will be DateFrom: '2016-04-13T16:00:00.000Z')
This is happening because of, GET method is pass data in a header or url, while json data can not passed through header, change the method of passing data, which is currently in a json format.
You could do like even :
var fd = new FormData();
fd.append('data', yourData);
and send fd as a directly data object, it will work.
GET request has no body, it passes the parameters in either cookies or URL query string, so pass the data you want in a query string parameter like below:
var url = #Url.Action("MyGenerateReportMethod",new {DateFrom="_X_"});
url = url.replace("_X_",$("#DateRangeFrom").data("kendoDatePicker").value());
$.ajax({
type: 'GET',
url: url,
async: true
});

How to Parse JSON object in Django View from Ajax POST

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

Pass objects in ajax request

I need to pass objects in ajax request in order to "PUT" files or data to my rest service. How can i do it? Thank you.
update
i have this code:
var invoice = {};
invoice.POSWorkstationID = "POS7";
invoice.POSClerkID = "admin";
invoice.CustomerName = "Alice in Wonderland Tours";
invoice.IsFreightOverwrite = true;
should i do this:
parameter = "{BillToCode:"+invoice.CustomerName+",POSWorkstationID:"+invoice.POSWorkstationID+",POSClerkID:"+invoice.POSClerkID+",IsFreightOverwrite:"+invoice.IsFrieghtOverwrite+"}";
and this:
data: JSON.stringify(parameter),
Normally, you can use jquery to do this may be like this:
$.ajax(
{
type: "PUT",
dataType: "json",
data:POSTData,
url: 'www.youurlhere.com/path',
complete: function(xhr, statusText)
{
switch(xhr.status)
{
//here handle the response
}
}
});
POSTData is the data in json format that u supply to the rest, you can turn an object into a json format by simply pushing the attributes but respecting JSON Format syntax
Take a look at jQuery post http://api.jquery.com/jQuery.post/
you have few options there:
$.post("test.php", $("#testform").serialize());
$.post("test.php", { name: "John", time: "2pm" } );
The best way to communicate client and server side is (IMHO) JSON.
You could serialize your object into json format, with this lightweight library =>
http://www.json.org/js.html
Look for stringify method.

Categories

Resources