Edit: I thought this function was calling the wrong api, however after commenting it out I realize that the function does not work at all. The page was generating the call itself.
So why doesn't this function send a call to the controller at all when the same function without a parameter, and wrapped in Ko.computed works ok?
I am using Knockoutjs and ASP.net MVC 5 to make a webpage. There are two calls to the server passing a parameter one works well, the other never works.
I am using this exercise as a base for my own project. using-web-api-with-entity-framework/part-6
I have a single ajax helper from the exercise
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
This function below works and sends GET /api/Guests/20 using the API of GET api/Guests/{id} returning back data
self.getGuestDetail = function(item) {
ajaxHelper(guestUri + item.GuestID, "GET").done(function(data) {
self.detail(data);
});
Yet this function, which is pretty much identical doesn't return any data, basically the same server call is being sent differently.
The api it wants is GET api/RoomBooking?DateFrom={DateFrom} (server side datefrom at this stage is a string)
self.RoomList = ko.observableArray(); //an array that will hold each room when foreached ko.computed(
self.ShowFreeRoomsFunction = function (item) {
ajaxHelper(roombookingUri + item.BookingFrom, "GET").done(function (data) {
self.RoomList(data);
});
I have been looking at this all day, and am totally lost. I have replaced the Datefrom with just simple strings to get something to pass, but it seems as soon as I try to pass a parameter, the method never sees it.
When I don't pass a parameter and wrap in ko.computed the method works returning data.
Here is the same call working by wrapping it in a ko.computed function. It sends off the GET /api/RoomBooking/ api which is what I want
self.RoomList = ko.observableArray(); //an array that will hold each room when foreached ko.computed(
self.ShowFreeRoomsFunction = ko.computed(function () {
ajaxHelper(roombookingUri, "GET").done(function (data) {
self.RoomList(data);
});
});
Close to Success achieved the url has to be http://localhost:50524/api/RoomBooking/?textA=asdfghjkl with the ? in it. Now all that needs fixing is how to pass the variable to replace asdghjkl and then move dates.
If I manually enter the url into the browser I can see it moving across in fiddler and it returns data as a json file.
But if I try to do it through the program it never shows in fiddler nor runs.
Fiddler result:
Result Protocol Host URL Body Caching Content-Type Process Comments
Custom 51 200 HTTP localhost:50524 /api/RoomBooking/?textA=asdfghjkl
117 no-cache; Expires: -1 application/json; charset=utf-8
iexplore:10040
What might I be doing wrong in my Get call that stops it ever showing even when hard coded in like this?
self.RoomList = ko.observableArray(); //an array that will hold each room when foreach
self.ShowFreeRoomsFunction = function (item) {
ajaxHelper("/api/RoomBooking/?textA=asdfghj", "GET").done(function (data) {
self.RoomList(data);
});
};
Thanks guys.
Related
Hello I got a service that is made for sending html mails, it will be called from a method "SendMail(data) about 1500 characters.
I access the service though JQuery with AJAX call and JSON:
var data = encodeURIComponent(JSON.stringify(dataArray));
$.ajax({
type: "GET",
url: "http://localhost:53334/Service.svc/SendMail?data=" + data,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function () {
alert("Reklamationen er blevet sendt!");
},
error: function (err) {
alert("Kunne ikke sende reklamation! Der opstod en fejl.");
}
});
I got alot of fields and if I fill everything out it gives a 404 not found response but then if I leave some random fields empty it gets to the API and executes the method it should? So I think its about the data size. I have tried many settings in webconfig but i havent managed to find a solution.
I hope there will be someone who can help me.
You should really be using POST as indicated by Tikkes. Semantically you aren't requesting a resource from the server, so GET doesn't make sense. Also, as noted here there is a maximum length that is enforced for Urls which is what GET uses to pass params(as you can see in your code as well). POST on the other hand uses the request body to send its data. Also, as noted here POST and GET sizes are usually configurable on the server, but POST is generally much larger(2KB vs 10MB defaults) as stated in one of the answers. Hope this helps.
I have an AJAX POST request which is supposed to send a user's search filters off to a controller action and return appropriate results. This was working perfectly, then it just stopped working. I haven't changed a thing, it was working fine, the model was binding exactly as intended, then it just broke and now it will only bind to the non-array items.
Here is my full Jquery AJAX code:
var parent = $('.recipe-search > .search-form > .filter-panel > .area');
var searchobj = {
SearchTerm: $(parent).find('input.search-terms').val(),
TimeRange:
[
$(parent).find('div.time-range').slider("values", 0),
$(parent).find('div.time-range').slider("values", 1)
],
DifficultyRange: [
$(parent).find('div.difficulty-range').slider("values", 0),
$(parent).find('div.difficulty-range').slider("values", 1)
],
Vegetarian: $(parent).find('input.vegetarian').is(':checked'),
Vegan: $(parent).find('input.vegan').is(':checked'),
DietTags: $(parent).find('input.diet-tags').val().split(' ')
};
$.ajax({
type: "POST",
url: $('.recipe-search > .search-form').attr('action'),
data: searchobj,
error: function () {
alert("There was an error getting your search results, please try again");
},
success: function (result) {
popresults(result);
}
});
Here is the C# model:
For anyone wondering the sliders are JQuery UI sliders.
In the Chrome networking tab, I can see the request gets sent off as intended
However looking at the debug watch window when a breakpoint is hit, it is clear that they are not being bound to the model correctly
I'll repeat myself, and I know some of you will call me out on this saying that I did change something, I must have, but I did not change a thing between it working exactly as intended, and it not working.
Something that does strike me as odd is that the arrays sent in the request (look at the network tab photo) appear to be sending the two values as individual properties instead of values in an array.
Well it seems that adding two lines to the AJAX code fixed this:
datatype: "json",
traditional: true
Now it works completely as intended.
I have an application where I fetch a list of requests made by the user based on the idNo provided. The android application uses AJAX to make a request to a .NET WCF Service which in turn returns a IEnumerable of DTO for that request.
Following is the AJAX Code:
$.ajax({
url: baseURL + "RequestStatusList/"+idNo,
cache : false,
type : "GET",
dataType : "json",
contentType : "application/json; charset=utf-8",
crossdomain : true,
success : function(data, tst, xhr) {
//do something here
},
error: function (xhr, tst, err) {
alert(' Please Try Again ' + xhr.status);
}
});
A similar piece of code works in another page in the application, where only the process in success is different, rest all is same.
Here every time the request fails and enters the error section and displays undefined/0 as error. No details about error, hence i cannot get what maybe the problem.
When I debug the server side code I get proper value in the parameter passed and a IEnumerable is formed and returned. What fails is the client side code after successful execution of server code.
Please Help.
Thanks in advance.
I would like to begin with this. I am fed up with IE. I have the code below:
$(function () {
$("#cal").on('click', "#forward", function () {
$.ajax({
url: "Home/Calendar?target=forward",
type: "GET",
success: function (result) {
$("#cal").html(result);
}
});
});
});
$(function () {
$("#cal").on('click', "#backwards", function () {
$.ajax({
url: "Home/Calendar?target=backwards",
type: "GET",
success: function (result) {
$("#cal").html(result);
}
});
});
});
It is an ajax call to a controller action in an C# MVC application. It just goes back and forth a calendar's months replacing the html. Now I know that you need to reattach the event due to the html() call and that is why I use on() with JQuery 1.7. I have used delegate() as well. In FF, Chrome it works as intended. In IE 10 it does not. I am at a loss. I knew that IE had issues with delegate in IE8 and with JQuery < 1.5 but this is not the case.
Does anyone know how to solve this?
I am answering the question just for future reference for other people. It seems that IE is caching AJAX requests for some reason I am unable to comprehend.
I noticed using the (surprisingly good) developer tools IE 10 provides that I was getting a 304 not modified response to my AJAX requests. This was not the case in Firefox or Chrome (200 was the response).
I added the cache: false option to my AXAJ JQuery functions and now it works as intended.
IE never seizes to amaze me.
Brief addition, given what (little) I understand on the subject. Apparently, the XmlHttpRequest spec says that XHR GET commands can behave just like a standard web page retrieval (e.g. clicking on a regular old link), and therefore XHR GET commands can be cached. The IE team has chosen to adhere to this spec, while the other browser makers have not. While I can see some logic in this approach, I think those of us who work with XHR requests every day would emphatically say that we would prefer caching to be off by default, rather than on. (-;
I ran into this a long long long time ago with IE... now I always make it a point now to write my ajax calls with a random trailing key/value pair.
I also add cache: false though I have found by itself it doesn't always do what it should (well, maybe its just IE not doing what it should)
This is how I set them up...
$('#trigger').submit( function(e){
e.preventDefault();
var randnum = Math.floor(Math.random()*1001); //magic starts here
$.ajax({
type: "POST",
url: "folder/file.php",
cache: false,
data: "random=" + randnum, //pure magic
success: function(){
// do stuff here
}
});
});
Got this issue too. It turns out that all of the fixes above will not work if the POST response has cache-control: max-age. The 1st request will fetch the data but after that all requests (even if you add a random attribute) will be 304'd.
In this case IE will not even ask the server if the content changed, it just assumes that if it has a max-age then there's no point in doing a request.
Moreover XHR specs say that 304's shouldn't pass any data so basically you get an empty response for a POST (just on IE 9 and 10).
dojo.xhrPost({
url: "Default.aspx/TestMethod",
handleAs: "json",
contentType: "application/json",
postData: dojo.toJson({ }),
load: function (result) {
debugger;
},
error: function (err) {
debugger;
}
});
That is the script I use to make a request to a WebMethod that is exposed in Default.aspx. The method is called TestMethod.
The error that I get is:
Unable to load Default.aspx/TestMethod status: 500
If you need any additional information please let me know.
*Note : I can call the method from the server side and it returns the results as intended.
I've been there. :(
Usually it is a problem with the format of the data that you are passing in. For instance, if your WebMethod has a parameter that is an int and you are passing a string, you will get a failure like this.
I would use a tool like Fiddler http://www.fiddler2.com/fiddler2/ to see what you are sending to the method.
Also turn on what ever server side logging and tracing that you have and use it. One source that is useful for 500 errors (which tend to happen before "your" server code is reached) is Asp.net health monitoring.
There is more info about setting that up and using it at http://msdn.microsoft.com/en-us/library/bb398933(v=vs.100).aspx