I am having a hard time getting the correct field out of an object from an ajax get request. The ajax request is in a Django app and corresponds with the view. The line:
console.log(data);
displays all the data in the object. I am trying to output the username in console.log() but I am not able to get it done.
I tried many variations i.e. I used filter instead of get in the Django view section. I tried to for loop over the data and use [i] but so far nothing worked.
Hopefully someone has an idea on how to solve this issue. I attached the django view, the template view and the chrome dev tools console output.
The django section view:
def Data(request, user_id):
if request.is_ajax():
sidebar_data = serializers.serialize("json",
[User.objects.get(id=user_id)])
return HttpResponse(
JsonResponse({'sidebar_data': sidebar_data}),
content_type="application/json"
)
return HttpResponse("not a ajax request")
The template view:
$( ".test{{ user.user.id }}" ).click(function() {
$.ajax({
url : ‘xxx/‘,
dataType : 'json',
method : 'GET',
success: function(data)
{
// this works - outputs all data
console.log(data);
// this does not work
console.log(data.sidebar_data.fields[1].username);
},
failure: function(){
}
});
});
The output for the browser in chrome console:
Object {
sidebar_data: "[{"fields": {"username": “xxx”, "first_name": “xxx”}, "model": "auth.user", "pk": 989}]”}
If i use console.log(data.sidebar_data); i get the following output which is a step closer. But as soon as i try any combination with fields or username i get the undefined error.
[{"fields": {"username": “xx”, "first_name": “xxx”}, "model": "auth.user", "pk": 989}]
change views.py like this:
from django.core import serializers
def data(request):
if request.is_ajax():
user = User.objects.filter(id=1)
data = serializers.serialize('json', user)
return HttpResponse(data, content_type ="application/json")
return HttpResponse("not a ajax request")
and change template like this:
$( ".test{{ user.user.id }}" ).click(function() {
$.ajax({
url : ‘xxx/‘,
dataType : 'json',
method : 'GET',
success: function(data)
{
console.log(data[0].fields.username);
},
failure: function(){
}
});
});
Try data[1].fields[1] instead of data.sidebar_data.fields[1].username
Related
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"})',
Developing with laravel 5.4.
In the web file I have this route:
Route::get('cart/calcShipping/{shipping_method}', 'CartController#calcShipping');
I have a view with ajax call like this:
$.ajax({
type: "GET",
headers: { 'X-XSRF-TOKEN' : $_token },
url: '{{ url("cart/calcShipping") }}' + '/1',
success: function(data) {
$('#shippingCost').val(data);
$('#shippingCostText').text(data);
}
});
In my controller I have this function (I do some calculations that I did not include in the example. For testing I'm sending back hard coded values):
public function calcShipping($shipping_method)
{
return response()->json(['shipping_cost' => 100, 'order_total' => 200]);
}
The problem is I get [object Object] back on these lines, instead of the values:
$('#shippingCost').val(data);
$('#shippingCostText').text(data);
What am I doing wrong?
Thanks
My mistake, duh, I have this call in two places, and in one of them I was only calling data.... pffff....
This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'
I'm doing an ajax request to an own rest api and trying to print in an alert the message I get.
The point is I'm getting the following error: SyntaxError: Unexpected token :
The code that makes the call is:
$.ajax({
url:"${g.createLink(controller:'report',action:'show')}",
dataType: 'json',
data: {
data: jSon,
},
success: function(data) {
alert(data)
},
error: function(request, status, error) {
alert(error)
},
complete: function() {
}
});
The return value i'm printing in the controller is:
JSON: {"results":"SELECT cliente.edad FROM Cliente cliente,Local local WHERE Local.numero==3 GROUP BY Cliente.edad ORDER BY Cliente.edad undefined""}
And what I'm doing in the controller is:
println "JSON: " + java.net.URLDecoder.decode((String)apiResponse.json)
render java.net.URLDecoder.decode((String)apiResponse.json)
I have also tried with respond instead of render but same error
Try using render as JSON
def results = ['a':'AA','b':'BB']
render results as JSON
I'm a newbie with rest and angular, so my hope answer to my question is super easy.
I'm having problem working with JSON response I get from new Neo4j post transaction/commit query.
I want to access response data for each item I have in the response. I've searched how others handle this, but have found no same cases. I think I do not parse the response at all, and can not access the specific row.
Here is my code, that just prints all the json.
JS controller
function restcall($scope, $http) {
var call = '{ "statements" : [ { "statement" : "MATCH (n:Cars) RETURN n ORDER BY n.initRank DESC LIMIT 10" } ] }';
$http({
method: 'POST',
url: 'http://myserver:7474/db/data/transaction/commit',
data: call,
})
.success(function (data, status) {
$scope.status = status;
$scope.response = data.results;
})
.error(function (data, status) {
$scope.response = data || "Request failed";
$scope.status = status;
})
};
HTML that just prints out complete response
<section ng-controller="restcall">
<h2>{{status}}</h2>
</br></br>
<h3>{{response}}</h3>
</section>
And most importantly the JSON response I get
{
"results":[{
"columns":[
"n"
],
"data":[
{"row":[{"name":"Car1","initRank":"..."}]},
{"row":[{"name":"Car2","initRank":"..."}]},
{"row":[{"name":"Car3","initRank":"..."}]},
{"row":[{"name":"Car4","initRank":"..."}]},
{"row":[{"name":"Car5","initRank":"..."}]},
{"row":[{"name":"Car6","initRank":"..."}]}]
}],
"errors":[]
}
So basically now I just print out in html my json response.
Now, how do I access individual rows to get i.e. Car3 properties??
I tried the data.results[0][0].data... and also to parse my string, but when I add next .data it just doesn't show a thing, same thing with parsing.. Can someone help please.
Based on that JSON response, you would use data.results[0].data[2].row[0].initRank to access the "initRank" of Car3. You shouldn't need to do any extra parsing of the response. It should already be an object in your callback.