json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ajax request - ajax

I have an ajax request, and in django view, i have following prints and outputs.
I have the error in this line and i cant figured it out why.
parsed_json = json.loads(request.body)
I trid to decode request body with utf8 but nothing has changed
AJAX CALL:
$("#add_user_button").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/user/',
data:
{
'action': "addUser",
'username': $('#id_username').val(),
'password': $('#id_password').val(),
'groups': $('#id_groups').val()
}
,
contentType: 'application/json; charset=utf-8',
processData: false,
});
}
DJANGO VIEW PRINTS:
print(request.POST.get("username"))
#print(request.encoding) #returns none
print("Request body is :")
print(request.body)
print(type(request.body))
OUTPUTS:
hello
Request body is :
b'username=hello&password=world&csrfmiddlewaretoken=&addUser=Add+User'
<class 'bytes'>

If you analyse your request body you'll notice it is not JSON, to send JSON you have to encode it in your ajax request from your object.
$("#add_user_button").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/user/',
data:
JSON.stringify({ // <--here
'action': "addUser",
'username': $('#id_username').val(),
'password': $('#id_password').val(),
'groups': $('#id_groups').val()
})
,
contentType: 'application/json; charset=utf-8'
});
}

Related

Ajax request response code 419 even csrf token is available in request

I have a simple ajax request which is returning 419 even csrf token is available in both the ajax setup header and inform data as well here is my code.
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var formData = new FormData();
formData.append('_token', $("input[name='_token']").val());
formData.append('request_id', $('#request_id').val());
var request = $.ajax({
url: appUrl + "/admin/schedule-detailing-requests",
type: "POST",
data: formData,
processData: false,
contentType: false,
cache: false,
dataType: "json",
// headers: headers
});

ASP.NET Core FromBody is null on AJAX POST but populates in Postman

I'm trying to perform an AJAX post but I keep getting a null FromBody in my .NET controller. I think it has to do with how I'm formatting my AJAX post.
When I attempt to post with AJAX I get a null FromBody.
var data = {
Date: "2016-12-01",
BurnIdx: 23,
BurnStatIdx1: 3,
BurnStatIdx2: 3,
BurnStatIdx3: 3,
BurnSevIdx: 5,
WorkOrder: 32426,
Comment: "Hi"
};
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (result) {
console.log('Data received');
console.log(result);
}
});
});
However, when I attempt a post in Postman it's successful.
Figured out my problem. Needed to use JSON.stringify on my data.
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
console.log('Data received');
console.log(result);
}
});
Not only the JSON.stringify().
If your data don't match with csharp class data it doesn't receive anything.
Like if you define in the class a field with int type, and send it in the json like "1", it happens to receive the whole data as null
I know you are already figured out of this problem. But I faced with the same just right now. My mistake was I used BODY parameter instead DATA in ajax request.
My Invalid ajax:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
body: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
Valid:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
data: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
}

django ajax MultiValueDictKeyError

I am receiving this error:
MultiValueDictKeyError at /orders/ajax/add_order_line
"'cart'"
Here is my script
var cart = {
0: {
id: "1",
quantity: 50
}
}
$.ajax({
url: myURL,
type: "post",
data: {cart: cart},
success: function() {},
error: function(){}
});
Meanwhile in my django views, the error was found in this line:
def something(request):
cart = request.POST['cart']
Use get method of multivaluedict
request.POST.get('cart')
Your data is a nested array, so you can't send it using the default default application/x-www-form-urlencoded content type.
You can send the data as json:
$.ajax({
url: myURL,
type: "post",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({cart: cart}),
success: function() {},
error: function(){}
});
Then in your view, you have to load the json string from request.body instead of using request.POST (which is for form-encoded data only).
import json
def my_view(reqest):
data = json.loads(request.body.decode('utf-8'))
cart = data.get('cart')

How to Display Json Data when ajax request is success

Here I am using Ajax+Mvc when I call my data from database it comes in Json format but how can I display that data in div?
Html
<div id="Div1">
</div>
<b>Get data</b><input type="button" id="BtnGetData" value="GetData" />
When user click on BtnGetData the data should be display in #Div1 Here my AJax working fine.But please suggest me where to write $('#Div1').load();
$('#BtnGetData').click(function () {
alert('ok data')
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(),
})
})
MvcController
public JsonResult Getdata()
{
var x = Objrepo.GetEmplo();
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
You can write to the div on the success function of your $.ajax call.
eg:
$('#BtnGetData').click(function () {
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(),
success: function (data) {
console.log(data);
}
})
});
You need to add a success callback to your ajax:
$('#BtnGetData').click(function () {
alert('ok data')
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
success: function(data){
$("#Div1").append(data);
}
})
})
There is no need to add the data property to the ajax if your are not sending anything.
May be, you can add this function in your script.
$('#BtnGetData').click(function () {
alert('ok data')
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(),
writeResponse(data)
})
});
writeResponse(data){
$("Div1").html(data);
};

Can't pass data from attributes using ajax laravel 5.1

var formData = new FormData();
formData.append('name', name.val());
formData.append('email', email.val());
formData.append('contact_number', contact_number.val());
formData.append('barangay', barangay.val());
formData.append('landmark', landmark.val());
formData.append('password', password.val());
formData.append('confirm_password', confirm_password.val());
//Problem start here it came from attributes but I can alert the data and it was fine.
formData.append('image_pin', img_top);
formData.append('img_left', img_left);
formData.append('img_z_index', img_z_index);
formData.append('input_value', input_value);
formData.append('input_top', input_top);
formData.append('input_left', input_left);
$.ajax({
url: 'register',
headers: {'X-CSRF-TOKEN': token.val() },
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: formData,
success: function(data){
console.log(data);
},
error: function(){
}
});
//The input works fine but the attributes data is undefined
$request->input('img_top');
$request->input('img_left');

Resources