Sending JavaScript Array or Object to Django View - ajax

I am trying to send via AJAX an array (or object) to my Django View.
In JS File:
var dataArr = [];
dataArr.push({'status':'active'});
...
var json = JSON.stringify(dataArr);
...
$.ajax({
type: "POST",
url: "/filter/",
data: {
'filter_text' : json,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: filterSuccess,
dataType: 'json',
contentType: 'application/json'
});
I am getting a 403 Forbidden error in Javascript. I tried several things, e.g. omitting the dataType / contentType, sending a Javascript object instead of an array, etc.

You can't pass the array directly to url,
Use jQuery.param(yourObject).
The param() method creates a serialized representation of an array or an object that can be understandable by various frameworks like php, ruby, django etc.
For again converting it to python
from urllib import parse
value = parse.parse_qs(self.request.POST.get('name'))
Note that using prase you can lost some information, so recheck your data after getting it in python.

Related

Send normal variables along with mulitdimensional array to AJAX call to PHP

I'm sending some variables to AJAX call with POST method to PHP file as below -
$.ajax({
type: "POST",
url: "sendEmail.php",
data: {
'v1':mailto,
'v2':pname,
'v3':ptype
},
Now in addition to this, I've some data as below -
DataArray = {"name",value1, value2},{"name",value1, value2},{"name",value1, value2}.
How can I send above array (array of array objects) in above AJAX call. Also how can I get array in PHP file.
Any inputs will be helpful. Thanks!

Why is ajax parsing json to the form "a=b&c=d"?

$.ajax({
url: '/metadata/hg_billing_cycle',
data: {"a":"b", "c":"d"},
datatype: "json",
contentType: "application/json",
type: 'POST',
error: handleError,
});
I'm using ruby on the server:
post "/" do
puts "ummm: #{request.body.read}"
end
I get the following output:
ummm: a=b&c=d instead of ummm : {"a":"b", "c":"d"}. Why is it doing this?
You are passing an object as the data parameter, from the $.ajax docs
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So your object is converted to a query string.
If you want to send json, then you'll have to well send json.
Convert your object to json (with JSON.stringify) and pass that as the data parameter.
$.ajax({
url: '/metadata/hg_billing_cycle',
data: JSON.stringify({"a":"b", "c":"d"}),
datatype: "json",
contentType: "application/json",
type: 'POST',
error: handleError,
});

How to parse a nested json ajax object in Django views?

I need to make a request as follows:
var url="http://127.0.0.1:8080/simulate/";
$.ajax({
url: url,
type: 'POST',
data:{ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
},
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
But in this way, the request.POST object is not organizing the companies into a nested json array. Instead it makes it into a 2D array as follows:
<QueryDict: {u'student_num': [u'10'], u'students': [u''], u'companies[2][weight]': [u'9'], u'companies[1][weight]': [u'11'], u'company_num': [u'10'], u'companies[0][weight]': [u'10'], u'csrfmiddlewaretoken': [u'RpLfyEnZaU2o4ExxCVSJkTJ2ws6WoPrs']}>
In this way, I feel hard to reorganize the companies into a list of objects. I checked some other questions, some people say we should do this:
companies:"[{weight:10},{weight:11},{weight:9}]"
And then use json.loads to parse the string back to a list of objects. But I am keep getting parsing error if I use codes like this:
company_array = request.POST['company_array']
company_array = json.loads(company_array)
or this:
company_array = json.load(StringIO(company_array))
So what should be the correct way to handle nested JSON object?
You should use JSON.stringify() to stringify your data before sending it:
$.ajax({
url: url,
type: 'POST',
data: { data: JSON.stringify({ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
}) },
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
Then you can parse with json.loads() on the server side:
data = json.loads(request.POST.get('data'))
You might find the answers here useful: Reading multidimensional arrays from a POST request in Django
You can try look to django-SplitJSONWidget-form and get decision from it.

Attach requestbody to jQuery ajax

I am trying to attach data to my requestbody while sendign using jQuery ajax.
If I tried to do it using the extension RESTCLient is either firefox or chrome it works fine, which means that my method on the serverside is working fine.
That is why I am pretty sure that it the ajax call I am making
$.ajax({
url: 'lingosnacks/delete/'+ id,
type: 'POST',
data: $('#email').val() + $('#password').val()
dataType: "json",
success: function(data) {
console.log("FILL| Sucess| ");
console.log("FILL| Sucess| Data| " + data);
fill(data);
}
});
The data line is wrong, it should be very similar to a JSON string, like this:
data: {email: $('#email').val(), password: $('#password').val()},
You need to have the data you are sending in this format:
email=blah%40blah.com&password=pass123
You can do that with jQuery using $('form').serialize()
Also, you are missing a , after your data string in the Ajax call.
Actually data param in jQuery Ajax method is for sending url params.
You can send the same by appending then into the url but to make the code more readable e and organized i would prefer to use data variable.
So your data content should look like :
data : "email="+$('#email').val()+"&password="+$('#password').val();
I am not pretty sure if sending params like a json object will work or not because i never used it.

$.ajax() vs $.getJSON() with YQL and cross domain requests

I'm trying to execute a cross domain request for data from a wordpress blog using YQL. This is the code from my first attempt:
var g = {data:""}
function getWP() {
var targeturl = "http://www.mysite.com";
var url = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(targeturl)+
"%22&format=xml'&callback=?";
var successfunc = function(data) {
if(data.results[0]){
g.data = data.results[o];
} else {
var errormsg = '<p>Error: could not load the page.</p>';
alert(errormsg);
}
}
$.ajax({
url: url,
success: successfunc
});
}
When I tried this ajax call, the data object returned was an empty string. However, when I did this:
$.getJSON(url, successfunc);
the proper JSON object was returned. What is the difference between the two calls? And more importantly, why did only the second one work?
The difference is that you are not specifying your data type or content type
Add
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successfunc
});
to your ajax call
$.getJSON() uses data type json while the $.ajax() doesn't. If you want to use standard $.ajax() you'll have to specify datatype explicitly. For cross-domail calls use datatype jsonp instead of json. But I think YQL works with json as well.

Resources