Django/python is converting my post data from JavaScript - 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}

Related

How do I get the JSON values from the response in Groovy

I'm using the below function in Jenkins Shared Library.
/* The below function will list the groups */
def list_groups(server_url,each_group_name,authentication){
def groups_url = server_url + "/api/v1/groups"
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'GET', ignoreSslErrors: true, responseHandle: 'NONE', url: groups_url,
validResponseCodes: '100:599'
if(response.status == 404){
throw new Exception("Server url not found! Please provide correct server URL.")
}
else{
if(response.status == 400 || response.status == 403){
throw new Exception("Invalid Access token or Access token expired!")
}
}
def result = readJSON text: """${response.content}"""
}
=====================================================================
I'm getting the below response,
Response Code: HTTP/1.1 200 OK
Response:
[{"id":2,"name":"Default User"},{"id":3,"name":"fos"},{"id":4,"name": "kXR"},{"id":5,"name": "Sgh"},{"id":6,"name":"ksn"},{"id":7,"name":"ALb"}]
Success: Status code 200 is in the accepted range: 100:599
Requirement:
I need to get the last output from the JSON body (id & name) ---> {"id":7,"name":"ALb"} from the response and to be printed and stored in a variable using groovy.
First, you need to Parse the response String to a JSON object, for this you can either use Jenkins native method readJSON, or something like JsonSlurperClassic. Then you can use JSON path expressions to extract the values. Check the following example.
def jsonObj = readJSON text: response.getContent()
def id = jsonObj.id[-1]
def name = jsonObj.name[-1]
echo "ID: $id | NAME: $name"

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)

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 just one field via AJAX with Flask

I have a VERY simple HTML form with just one <input type='text'> field, an email address, that I need to pass back to a Python script via AJAX. I can't seem to receive the value on the other end. (And can all the JSON encoding/decoding be avoided, since there's just one field?)
Here's the code:
from flask import Flask, render_template, request, json
import logging
app = Flask(__name__)
#app.route('/')
def hello():
return render_template('index.htm')
#app.route('/start', methods=['POST'])
def start():
# next line outputs "email=myemail#gmail.com"
app.logger.debug(request.json);
email = request.json['email'];
# next line ALSO outputs "email=myemail#gmail.com"
app.logger.debug(email);
return json.dumps({ 'status': 'OK', 'email': email })
if __name__ == "__main__":
app.run()
And the Javascript that sends the AJAX from the HTML side--
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
d = "email=" + $('#email').val(); // this works correctly
// next line outputs 'sending data: myemail#gmail.com'
console.log("sending data: "+d);
$.ajax({
type: "POST",
url: "{{ url_for('start') }}",
data: JSON.stringify(d),
dataType: 'JSON',
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log("SUCCESS: ");
// next line outputs 'Object {email: "email=myemail#gmail.com", status: "OK"}'
console.log(result);
}
});
});
JSON.stringify is used to turn an object into a JSON-formatted string, but you don't have an object, just a string. Try this:
var d = { email: $('#email').val() };
JSON.stringify(d) will now turn that into a JSON-formatted string:
{email: "myemail#gmail.com"} which can be parsed by flask.
To do this without JSON:
var d = { email: $('#email').val() };
...
// AJAX
data: d,
success: ...
This will turn {email: "myemail#gmail.com"} into email=mymail#gmail.com and send that as body of the POST request. In Flask, use request.form['email'].

Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

I've use token input in my website, and here's how I initialize the token input:
$(document).ready(function () {
var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value
$("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", {
deleteText: "X",
theme: "facebook",
preventDuplicates: true,
tokenDelimiter: ";",
minChars: 3,
tokenLimit: 1,
prePopulate: populateValue
});
});
The script was stuck on this line:
prePopulate: populateValue
When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The populateValue is:
[{
"id": "11566",
"name": "Smith - White"
}]
There was a javascript error:
Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`
How can I fix this error?
You need to parse the string in your populateValue variable to an object:
prePopulate: $.parseJSON(populateValue)
Or alternatively, in plain JS:
prePopulate: JSON.parse(populateValue)
You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.
Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json
Here is my .CS page code:
WebMethod
public static string PopulateDetails(Guid id){
var prx = new ProductProxy();
var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type
return JsonConvert.SerializeObject(result);
}
Then in my jQuery post method:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Productjq.aspx/PopulateDetails",
data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data
success: function(result) {
var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234"
$.each(rspns, function() {
$('#<%=txtProductName.ClientID %>').val(this.Name);
});
},
error: function(xhr, textStatus, error) {
alert('Error' + error);
}
});
I was getting this error as well.
C# Api returning Serialized Dictionary data.
return JsonConvert.SerializeObject(dic_data);
return new JavaScriptSerializer().Serialize(dic_data);
Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize
return dic_data;
No more errors on the browser side. Not sure why.

Categories

Resources