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....
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"})',
The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}
If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.
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
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!
I'm setting up a select2 with the following JavaScript
$j("#" + name).select2({
placeholder: "",
width:"300px",
minimumInputLength: 3,
ajax: {
url: "/MyService.asmx/ServiceMethod",
dataType: 'json',
data: function (term) {
return {
q: term // search term
};
},
results: function (data) {
alert('results');
return {results: data};
},
success: function() {
alert('success');
},
error: function () {
alert('error');
},
},
});
The method I'm calling is the following:
<WebMethod(enableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function ServiceMethod(q as String) As String
Dim temp As String = "[{'id':'35','text':'Drew'}]"
Return temp
End Function
I also have <ScriptService()> around the class. The enableSession is there because eventually I'm going to be running a lot of logic in the service that requires it, but for now I'm just trying to return a simple string with JSON.
I've put a breakpoint in the webservice, and I know it is being called. I know it is returning the JSON. I also know that the select2 expects "id" and "text" in the JSON return
My problem is the following: after I input 3 characters, the data function calls (I put an alert in it), the webservice breakpoint is hit, but none of the results, success, or error events fire afterwards. The select2 just spins and nothing ever happens. No javascript errors are entered in the console, and I'm at a loss about even where to look for information as to why the ajax isn't handling the returned value from the service.
Can anyone point me in the direction of at least where to look to see why this isn't working?
So I fixed this myself after getting a hint to look at the network log. The service was returning correctly, but it was returning XML, not JSON. I had to make 2 modifications and everything worked.
My working ajax:
ajax: {
url: "/MyService.asmx/ServiceMethod",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
The important changes were the type, putting the contentType in the params wrapper, and JSON.stringify-ing the data. I'm going to change what's passed and how its passed, but things are at least communicating now. Hope this helps anyone else who was looking for a similar solution.