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.
Related
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.
I need to create multiple search requests in Jquery which searches from different tables/pages and I need to combine all the search results to one HTML table and show the results in UI.
Below is my approach..
Using $.ajax in Jquery, I go to the server (.Net Code), fetch JSON data, come back to the JS file and build a HTML table and display result (this result will have checkbox for user to check/uncheck the results). Once I display results, I again use $.ajax, go to server (.NET Code) and get data and will append the results to the first HTML table.
My requirement is, between these 2 requests I need to
1) Show a Loading image/text.
2) The user should be able to access (scroll, check, uncheck) the HTML table results returned by 1st JSON request.
I am able to accomplish 1) also. The problem I am facing is regarding 2).
Once the results come from 1st request and once I display the results in a div, I again trigger the 2nd search request using $.ajax. At this time I am not able to access the HTML table. The page freezes until the results from the second request come and till I bind the results to HTML table.
My code is something like this.
function SearchDetails() {
GetDetails("Test", 0); /*Trigger First Request*/ }
function GetDetails(searchKeyword, iAppend) {
$.ajax({
type: "POST",
url: "FETCH_DETAILS.asmx/GetDetails",
data: "{'searchKeyword':'" + searchKeyword + "', 'Append':'" + iAppend + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
crossDomain: true,
jsonp: false,
success: function (response) {
if(iAppend == 0) //First Request
{
BindTable(response.d, iAppend); //Creates new HTML table and binds results
GetDetails("TestNew", 1);//Trigger Second Request
}
else if (iAppend == 1) {
BindTable(response.d, iAppend);
}
},
failure: function (msg) {
alert(msg);
},
});}
function BindTable(SearchResults, iAppend){
/*Creates HTML Table & binds to a div for First Request
Creates HTML Table Rowss & appends to existing HTML table for Second Request*/ }
Please suggest me whether i am missing anything or is there a way to go to server(.NET code) from Jquery without affecting (getting freeze) the display/UI.
Perhaps set the:
async: false
to
async: true
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).
I am very new into ajax and i am having a strange problem, I have created an asp.net website that have a web service within the project I am calling this web service by following ajax code:
$.ajax({
type: "POST",
url: pageUrl + "/PassData",
data: JSON.stringify({ aos_code: code }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall
});
the c# code is not very complicated, basically it will get the code and call the stored procedure and return some value:
[WebMethod(EnableSession = true)]
public string[] PassData(string aos_code)
{
// calling the database and returning some data
return data;
}
And it works fine; the problem is that if two different users accessing the application in the two different computers and let say they clicking a button at the same time to call the server side function via Ajax, it will return the “500 internal server error”.
I am not sure how exactly Ajax work, is request are belong to same session or all user requesting a single function?
Hope it makes sense, and I would really do appreciate for the clarification and help.
Regards,
Error 500 indicates that something went wrong on the server side. Check your console (firebug or similar) to see what exactly happened and try to fix it. Ajax has nothing to do with it, it is simply as if two users visited the same page at the same time.
I have this ajax-post:
$.ajax({
url: Config.Proxy + "ContentPages.aspx?t=save",
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: {
content: content,
id: currentPageId,
active: "true",
subject: $('#txtSubject').val(),
webid: webid
},
success: function (data, status) {
// do something
},
error: function (xhr, desc, err) {
// Do something
}
});
I do a post to an .NET page, so I could use the debug mode to check if the data is send correctly.
I use the same code as above for a different page (other url, other data).
When I run the application and save the data I don't come in the debug mode. When I use the same code for the other page, it works fine.
I tried to compare both codes, but they are the same. I have removed some data-items, but it still does not work.
Why? Can anyone give me a hint?
Thanks
EDIT *
I know why this is happening: CKEditor. As soon as I set the variable "content" to the content of the CKEditor and use the post-call, the debug-mode is not called anymore. Also the form-keys in the code-behind are 0.
The question now is how to fix this?
Like said in the edit of my original post: Problem was caused by the content of the CKEditor. I think HTML is not parser/loaded/call-it-what-you-want in an AJAX-post.
So, with a little help (and without posting code-behind, that had nothing to do with the problem) I figured it out:
var content = escape(CKEDITOR.instances.editor1.getData());
Put the variable "content" in the data-section of the post and voila! It works like a charm.
On the receiving .NET page in code behind, decode the value:
(HttpUtility.UrlDecode(Request.Form.Get("content").NullSafeString())
Thanks anyway