RawPostException: You cannot access body after reading from request's data stream - json

I am trying to get the data from ajax to django post view, I create the cart with items now I need to get the cart to backend
My js code is:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({'order_data':order}),
contentType: 'application/json; charset=UTF-8',
success: function (data) {
if (data['success']) {
alert(data['success']);
}
},
error: function (request, error, status) {
if (request) {
}
}
});
My View code that I am using in Django view:
if request.method == "POST":
data = json.loads(request.body)
cart = data['order_data']
Then I am getting that error
RawPostException: You cannot access body after reading from request's data stream
your suggestions will be preferred

You can get values from POST via:
order_data = request.POST.get('order_data')

I found the solution for it where I need to do the little change in Django view
order_data = json.loads(request.POST.get('order_data'))
and my work is done

Related

ASP MVC Areas and JSON POST

I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',

Steam Web API: Get CSGO inventory/ CrossDomainRequest

I am having issues making the ajax request from my localhost to http://steamcommunity.com/profiles/{steamid}/inventory/json/730/2
The issue seems to be that they do not have CORS headers enabled, so I have to use jsonp. Since the GET request returns json, but my ajax function is expecting json-p I receive an error:
Uncaught SyntaxError: Unexpected token :
2?callback=jQuery22005740937136579305_1452887017109&_=1452887017110:1
I need this resource, but I am unsure how to get around this. I've looked around on SO, but haven't found anything that matches this issue specifically. There are a few sites that are able to obtain a specific user's inventory, so in some respect it has to be possible.
My Ajax call
$.ajax({
url: "http://steamcommunity.com/profiles/76561198064153275/inventory/json/730/2",
type: 'GET',
dataType: 'jsonp',
success: function(response) {
console.log(response);
if(response.error){
alert(response.error_text);
}else {
console.log("SUCCESS!!");
}
}
});
I have figured out a workaround! I am using django for my web application and so I tried to make the request server side.
I installed the requests library through pip (The library: http://docs.python-requests.org/en/latest/)
In my django app I made a view that would be called by my AJAX request
def get_steam_inv(request):
user_steam_profile = SteamProfile.objects.get(brokerr_user_id = request.user.id)
r = requests.get("http://steamcommunity.com/profiles/76561198064153275/inventory/json/730/2")
return JsonResponse(r.json())
Then my ajax request for this view:
$.ajax({
url: "/ajax_get_steam_inv/",
type: 'GET',
success: function(response) {
console.log(response);
// result = JSON.parse(response);
if (response.error){
alert(response.error_text);
} else {
console.log(response);
}
}
});
And now I have the data I needed !

How to send multiple parameters from kendo data source read operation to WebApi controller

I have the following scenario: I have a kendo.dataSource which is populated via read request to a WebApi Controller. In addition to the read, I am sending a couple of parameters, which then I use in my controller to do some server logic. I was able to send as many simple parameters as I want via the parameterMap property of the transport function. Till now it was a simple get request. However now I need to send additional json object to the controller as a parameter. I read that I have to transform the Get request to Post and put the Json onto the body of the request but I don't know how to do it.
The code that I have so far:
var gridDataSource = new kendo.data.DataSource({
type: 'odata-v4',
transport: {
read: {
url: wave.alarmsAndEvents.api('api/alarmsAndEventsSearch/post'),
type: "POST",
data: {
SearchModel: JSON.stringify(vm.searchModel)
},
contentType: 'application/json; charset=utf-8',
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.startDate = kendo.toString(vm.selectedTimeInterval.start, "G");
data.endDate = kendo.toString(vm.selectedTimeInterval.end, "G");
data.alarmsToDisplay = vm.maxRecords;
}
return kendo.stringify(data);
}
},
pageSize: vm.maxRecords,
error: function (e) {
alert(e.xhr.responseText);
}
});
The SearchModel is the thing that I want to send as JSon. The rest are simple DateTime and int parameters.
My controller:
[HttpPost]
public IQueryable<AlarmsSearchViewModel> Post(DateTime startDate, DateTime endDate, int alarmsToDisplay, [FromBody]JToken jsonbody)
{
....
return something;
}
I end up with Not Found 404, but I am pretty sure that I have messed up the parameters. And from the Network window I can see that the json object is not sent at all. Any help will be much appreciated!

How to read a Json file in jQuery

I'm using VS2012, and running an ASP.NET MVC4 project.
I cannot seem to get this to fire below :
$.ajax({
url: "~/xml/JsonTest.json",
type: "GET",
dataType: "json",
success: function (json) {
alert("HI");
}
});
I also tried it this way , but to no avail :
$.getJSON('../xml/JsonTest.json', function (json) {
alert("GET JSON !");
});
Is it somehow not finding the directory structure ?
thanks.
Bob
The first one definitely won't work, since ~ doesn't mean anything client-side. What actual URL is requested by the second example? Does it send an AJAX request at all? What is the response?
If you have a dynamic server-side URL then you'll want to use server-side code to dynamically build it in the rendered output. Something like this:
$.ajax({
url: '#Url.Content("~/xml/JsonTest.json")',
type: 'GET',
dataType: 'json',
success: function (json) {
alert("HI");
}
});
This would result in the client-side JavaScript being rendered with the full URL for the server-side path "~/xml/JsonTest.json".
Best solution for my case was to properly code it up in a C# method as follows :
public string getJsonParameters()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
string jsonStr = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/myKeys.json"));
JsonParameters jsonData = (JsonParameters)ser.Deserialize(jsonStr, typeof(JsonParameters));
return jsonStr;
}

Cross Domain JSON Request Failing

I am trying to run this code in my browser's console:
$.ajax({
dataType: 'json',
url: 'http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json?callback=?',
success: function (data) {
if(data.resultcode == 1) {
console.log(true);
} else {
console.log(false);
}
},
});
However, I am getting a Cross Domain Request Error. when I try to make a simple JSON request then also same error occurs, because JSON request cannot be made on Cross Domains. however, when you go to this URL:
http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json
You'll be able to see the JSON data. However, a key point written in the documentation of this websites API says that:
json - all conversion data are returned as JSON object. Also JSONP cross domain communication supported usign jQuery.
Thanks in advance.
Use jsonp instead:
$.ajax({
dataType: 'jsonp',
url: 'http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json',
jsonp: "callback",
success: function (data) {
if(data.resultcode == 1) {
console.log(true);
} else {
console.log(false);
}
},
});