Django request.DATA gets corrupt value - javascript

My problem
My problem is that when sending a json document via post to a rest framework api, the document converts a key and adds an empty value.
file.js
function SaveFiles(task_id) {
data = {'taskid': task_id,'file_list': file_list};
$.ajax({
url: '/tarjet/save.../',
type: 'POST',
data: JSON.stringify(data),
async:false,
success:function(data){
},
complete:function(){},
error:function (xhr, textStatus, thrownError){
}
});
}
api.py
class SaveTaskFiles(APIView):
authentication_classes = (TokenAuthentication,)
def post(self, request):
a = request.DATA
javascript output
{"taskid":"1198792","file_list":[{"id":0,"file_name":"image2.png","upload_date":"11/16/2016","file_description":"","download_link":"a6175ab4-ac58-11e6-8e10-00dbdfd54837.png","isdeactivate":"0","sft_f":"svt"}]}
actual input request.DATA
{u'{"taskid":"1198792","file_list":[{"id":0,"file_name":"image2.png","upload_date":"11/16/2016","file_description":"","download_link":"a6175ab4-ac58-11e6-8e10-00dbdfd54837.png","isdeactivate":"0","sft_f":"svt"}]}': [u'']}
Is a Querydict type.
I can not explain why my json file becomes a key,and this value is a empty list, i have solved it using request.body, but I know it's not the convention. I've tried dumps, loads, but it did not work, although I could get the key and use it, I do not think that's a good idea.
Beforehand thank you very much ¡

You need to send the correct content-type header to tell DRF that you are sending a JSON document, not a plain string.
$.ajax({
contentType: 'application/json',
...
});
See the DRF parsers docs.

Related

Node.js endpoint ampersand is getting appended when making an ajax call

I've the below code which I'm using to hit a node.js endpoint. However when it is getting hit, the endpoint URL appends an & to it like this,
http://localhost:3004/expenses/?q=&12/02/2014
Hence I'm not getting the desired result back.
Here is how my code looks like,
$('#myForm').on('submit', (e)=>{
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/?q=',
processData: false,
data: $('#startDate').val(),
contentType: 'application/json',
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
})
})
Can someone shed some light?
The issue is most likely related to the processData: false telling jQuery to not format the data for the request, and the GET url already containing ? in it. Given that you are not giving the request json, I would suggest reducing your call to simplify the issue.
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/',
data: { q: $('#startDate').val() },
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
});
If you do not give the processData in the options, it will convert the data you give it to a query param for the request. Given that this is a GET request, it will generate the ?q=<value> for you. And as mentioned in the comments, you do not need contentType: application/json on the options as that is telling jQuery to put the content type on the request so the server knows you are sending it json in the body. Which you are not, :)

Submitting a JS array via AJAX to Django view returns TypeError

I have an array of objects that needs to be submitted to Django view.
I stringify it and checked result in console log. Up to this point it works. However, when I try to retrieve it in my view I get some errors.
I tried to edit my code similarly to what I've found on the topic, unfortunately nothing helped.
I tried ast.literal_eval instead of json.loads, passing 'items[]' and collecting data via request.POST.getlist as well as solution with request.body and request.is_ajax(). Yet, neither allowed me to retrieve the data.
var items = [];
var formInput = $('#inputbox').val();
items.push({'item': formInput , 'metrics': metrics.toString()});
$('#id_search').click(function( event ) {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '{% url "list_of_items" %}',
data: {'items': JSON.stringify(items),},
success: function (response) {
console.log(data);
}
});
event.preventDefault();
});
and in views.py:
def list_of_items(request):
data = request.POST.get('items')
data_received = json.loads(data)
#another approach:
response_json = request.body
struct = {}
try:
response_json = response_json.decode('utf-8').replace('\0', '')
struct = json.loads(response_json)
except:
print('bad json: ', response_json)
#(...)
I looks like an empty object is passed.
TypeError at /list_of_items
the JSON object must be str, not 'NoneType'
This view receives another POST request from the JS form within same template (list_of_items.html) and I wonder if it's interfering with my ajax POST.
You are not sending the data correctly. From the docs:
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data.
You need to send the data as key:value pair or you need to decode the request.body as
data = request.body.decode('utf-8')
data_received = json.loads(data)
This is the correct way to send ajax request.
$.ajax({
type: 'POST',
url: '{% url "list_of_items" %}',
data: {'items': JSON.stringify(items),},
success: function (response) {
console.log(data);
}
});
I also think that you have bound the submit event and click event incorrectly. Also you are sending ajax request on submit event without preventDefault

Why error function is always fired on my ajax call? [duplicate]

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

AJAX Post to store JSON with Python and javascript

I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.
Python
mainPage = """
<html>
html is included in my python file.
</html>
"""
class JSONInterface(webapp2.RequestHandler):
def post(self):
name =self.request.get('name')
nickname =self.request.get('nickname')
callback = self.request.get('callback')
if len(name) > 0 and len(nickname) >0:
newmsg = Entry(name=name, nickname=nickname)
newmsg.put()
if len(name)>0:
self.response.out.write(getJSONMessages(callback))
else:
self.response.out.write("something didnt work")
def get(self):
callback = self.request.get('callback')
self.response.out.write(getJSONMessages(callback))
This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.
Javascript
$(document).ready( function() {
$("#post").bind('click', function(event){
var name = $("#name").val();
var nickname = $("#nickname").val();
postData = {name: name, nickname: nickname, callback: "newMessage"};
$.ajax({
type: "POST",
url: "http://localhost:27080/json",
data: postData,
dataType: "json",
done: function() {
// Clear out the posted message...
$("#nickname").val('');
},
fail: function(e) {
confirm("Error", e.message);
}
});
// prevent default posting of form (since we're making an Ajax call)...
event.preventDefault();
});
The Javascript for the post
Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.
Did you ask the same question yesterday and then delete it? I swear I just answered the same question.
You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.
data: JSON.stringify(postdata),
HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.
For starters, the ajax call is pretty close. The full path
"http:://localhost:27080/json"
is not necessary, the relative path will work, but that is not the problem.
Your callback, as it stands, will work as 'success':
success: function(response) {
alert(response);
// Clear out the posted message...
$("#nickname").val('');
}
However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:
$.ajax({
type: "POST",
url: "/json",
data: postData,
dataType: "json"
}).done(function(data){
console.log(data);
});
Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.
import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
name = self.request.get('name')
logging.info(name) ## will print the value of 'name'
Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter.
In your python code:
import json
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
callback = self.request.get('callback')
logging.info(callback) # will print correctly
self.response.out.write(json.dumps(callback))
Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.

jQuery.post is not sending data to the specified URL

I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.

Categories