I'm trying to extract some elements from my Json data passed through an Ajax call to my views.py in Python Django.
My ajax call in my js file looks like this:
$.ajax({
url: "update/",
data: {'edited': editedFeature},
dataType: 'json',
type: 'POST',
contentType: "application/json;charset=utf-8",
success: function(data){
alert(data);
}
});
I'll note here that I'm working on Leaflet layers and that editedFeature in the data attribute is of GeoJson value:
var editedFeature = selectedFeature.toGeoJSON();
My views.py simply looks like this to test things out:
def update(request):
#ajax data
line = json.loads(request.body.decode("utf-8"))
rid = line['rid']
print(rid)
print("testing edited route")
return HttpResponse("Success!")
I'm not quite sure if this is correct as I just tried some solutions available in stackoverflow for the similar case. An error occurs stating:
ValueError: No JSON object could be decoded
If I change it to line = json.loads(request.body)
:
ValueError: No JSON object could be decoded
When clearly if I direcly print out print(request.body)
this string would show up:
edited%5Btype%5D=Feature&edited%5Bid%5D=J1276&edited%5Bgeometry%5D%5Btype%5D=LineString&edited%5Bgeometry%5D%5Bcoordinates%5D%5B0%5D%5B%5D=120.965&edited%5Bgeometry%5D%5Bcoordinates%5D%5B0%5D%5B%5D=14.5999&edited%5Bgeometry%5D%5Bcoordinates%5D%5B1%5D%5B%5D=120.964&edited%5Bgeometry%5D%5Bcoordinates%5D%5B1%5D%5B%5D=14.6017&edited%5Bgeometry%5D%5Bcoordinates%5D%5B2%5D%5B%5D=120.963&edited%5Bgeometry%5D%5Bcoordinates%5D%5B2%5D%5B%5D=14.6028&edited%5Bgeometry%5D%5Bcoordinates%5D%5B3%5D%5B%5D=120.962&... %5D%5Bcoordinates%5D%5B9%5D%5B%5D=14.6101&edited%5Bproperties%5D%5Bname%5D=South+Pier+-+Pier+North+via+Del+Pan
I'm wondering why it won't decode or load if there is something in request.body
? and another thing, how can I for example get name
from the json string? Is the line rid = line['rid']
correct?
Thanks to elyashiv, I was able to determine what I was passing to my view and found the solution. From my ajax call I should've made the code like this:
$.ajax({
url: "/plexus/load-map/update/",
data: JSON.stringify(editedFeature),
dataType: 'json',
type: 'POST',
contentType: "application/json;charset=utf-8",
success: function(data){
alert(data);
}
});
data: JSON.stringify(editedFeature),
I was actually passing a string query or something like that from above