Charset encoding of $.ajax json data - ajax

I make simple ajax request.
code is like this.
var paramObject = new Object();
paramObject.cd_nm01 = 'farm';
paramObject.cd_nm02 = 'server';
paramObject.cd_nm03 = 'cpu_num';
paramObject.cd_nm04 = 'mem_size';
paramObject.cd_nm05 = 'user_hdd';
paramObject.cd_nm06 = 'net_sprt';
paramObject.cd_nm07 = 'net_type';
var codes = JSON.stringify(paramObject);
$.ajax({
type: 'POST',
async: false,
cache: true,
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded; charset=UTF-8');
},
url: '/common/getCodes',
data: {
'jParam' : codes
},
success: function(data, status ,xhr) {
console.log(data);
},
error: function(xhr){
}
});
I want send data of this: "'cd_nm':'farm','cd_nm':'server','cd_nm':'cpu_num','cd_nm':'mem_size','cd_nm':'user_hdd','cd_nm':'net_sprt','cd_nm':'net_type'}"
but in controller(Spring 3.1),
if I get those values from request,
they looks like below.
%7B%22cd_nm01%22%3A%22farm%22%2C%22cd_nm02%22%3A%22server%22%2C%22cd_nm03%22%3A%22cpu_num%22%2C%22cd_nm04%22%3A%22mem_size%22%2C%22cd_nm05%22%3A%22user_hdd%22%2C%22cd_nm06%22%3A%22net_sprt%22%2C%22cd_nm07%22%3A%22net_type%22%7D
How can I solve this problem?

Your request is just url encoded, like it should be. If you decode it it looks like this:
{"cd_nm01":"farm","cd_nm02":"server","cd_nm03":"cpu_num","cd_nm04":"mem_size","cd_nm05":"user_hdd","cd_nm06":"net_sprt","cd_nm07":"net_type"}
That looks like valid json to me. The form that you want to send the data in doesn't look right. You want to use single quotes and you don't have a leading bracket. If you don't want the 01, 02, 03 suffixes you probably need to change the JSON.stringify method to accept an array of strings instead of an object.

Related

JS/JSON file upload immutable dictionary is empty

I know, similar questions had been asked before.
All questions I found concerns upload within a form and need a submit button. This I don't want. I want upload to start after file selection is made (I'm aware of security risks).
Why is the contend of the file dictionary not send?
The button itself is created by JS:
downLoadBtn = document.createElement('INPUT');
downLoadBtn.id = 'downloadBtn';
downLoadBtn.type = 'file';
downLoadBtn.onchange = function(){upload()}
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: JSON.file,
success: function (response){
console.log(response);
}
});
}
python:
#app.route('/upload', methods = ['POST'])
def upload():
if request.method == 'POST':
data = request.files
print(data)
return jsonify(data)
What I'm doing wrong?
You pass JSON.file as the data parameter which is not defined in the code you posted, it should be the file tat was selected.
Since your server side code expects multipart from data, you'll have to use a FormData object.
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
var fd = new FormData();
fd.append('file', file['files']['0']);
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: fd,
contentType: false,
processData: false,
success: function (response){
console.log(response);
}
});
}

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.

$.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.

how do you make ajax data key dynamic in jquery?

I'm trying to make my inline edit to be dynamic so it will just depend on some data- attributes from my markup so here's the code for now:
$(".inline-edit").editable(
function(value, settings) {
var editableField = $(this);
$.ajax({
type: 'PUT',
url: editableField.attr('data-href'),
dataType: 'html',
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
},
data: { 'regression_test_environment[name]' : value }
});
return(value);
},
{
event: 'click',
width: '80%',
height: '20',
submit : 'OK'
}
)
i want the name in regression_test_environment[name] to be editableField.attr('data-column-name') but it always fails in compiling because it keeps taking the key as a string. I tried making a variable after the editable field variable assignment and building the string as a different variable but it doesn't want to evaluate the key as a function.
Is there a way to do this? or am i stuck in creating a separate .editable call for each of my editable fields?
You may try like this:
var name = editableField.data('column-name');
var values = { };
values['regression_test_environment[' + name + ']'] = value;
$.ajax({
type: 'PUT',
url: editableField.data('href'),
dataType: 'html',
data: values,
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
}
});
Better, less confusing answer:
var data = {};
data[thisField] = $(this).text();
$.ajax({
data: data
});
Best is to pass dynamic values by serializing it :
var data = $('#formid').serialize(); // serialize all the data in the form
$.ajax({
url: 'test.php', // php script to retern json encoded string
data: data, // serialized data to send on server
...
});

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

Resources