Jquery (2) not calling AJAX Success call - asp.net-mvc

I've the following generic PostTo method which can be used to post data to an ASP.NET MVc Controller, without the need for repetitive mark-up, I'm pretty sure it was working at one point, but for some reason, the success callback (any of it) doesn't get called.
Any thoughts? Everything looks right, and the server is responding with a valid 200 OK response.
It is however, an empty response. I tried a different (and empty) dataType value, but nothing changed.
function PostTo(controller, action, data, successCallback) {
$.ajax({
url: Settings.HostPath + controller + "/" + action,
type: "POST",
cache: false,
dataType: "json",
data: data,
success: function (data, textStatus, jqXHR) {
if (typeof (successCallback) != "undefined")
successCallback.call(this, data);
}
});
}

ajax method in your script, excepts json data from the server, but as you told in comments, your actions returns nothing (i thinks it's returns EmptyResult).
So, add any json result in your action:
public ActionResult Test()
{
return Json(new {Success = true});
}

Related

JQuery AJAX Call to MVC action , asking the Credentials in Windows Server 2008R2

I have a jquery ajax POST to a MVC Action (which returns action result). In that i retrive record from DB and store in Session and return partial view result . On my machine this works well, when deployed it in Windows Server 2008 R2 , A popup appears in the browser asking me to enter credentials (authentication required).
The jquery call:
var data = $('#SearchForm').serialize();
window.location.hash = '#/' + data;
$.ajax({
url: '/PromotionManagement/PromotionsSearch',
type: 'POST',
data: data,
beforeSend: function (xhr) {
$('#search-result').hide();
$('#divresetCancel').hide();
$('#divwait').show();
// console.log('before sending request...');
},
error: function () {
//console.log("error processing request...");
},
success: function (data) {
debugger;
//console.log("successfully processed request...");
$('#search-result').html(data);
$('#search-result').show();
$('#divwait').hide();
$("#validation").html("");
if ($(data).html() == '\n No Records Found \n ') {
$('#divresetCancel').hide();
}
else {
$('#divresetCancel').show();
}
}
});
MVC Action :
[HttpPost]
public ActionResult PromotionsSearch(string list,string query)
{
//code to retrive the data from DB.
Session["SearchPerameters"] = objSearchPerameters;
return PartialView("PromotionsGrid", Promotions);
}
I referred this link and stopped storing the data in Session.
Even though it didn't work .
Can you pls suggest me what is missing..
any help can be greatly appreciated.
This issue got fixed by changing the AJAX call url: '/PromotionManagement/PromotionsSearch' [controllerName/ActionName] as 'PromotionsSearch' [Only Action Name].

Passing data to Ajax Error block

I have a controller with the following catch statement which returns a partial view and the error to display.
catch (Exception ex)
{
return PartialView("ErrorPartial", new ErrorModel(ex));
}
This controller is being invoked through an Ajax call like this...
$('#myID').ajaxSubmit({
url: buildUrl('MyController'),
beforeSubmit: function () {
toggleOverlay(true, 'Saving...');
},
success: function (responseText, statusText, xhr) {
successSave(responseText, statusText, xhr)
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
If the exception is caught, then the code falls into the error block however I'm unable to pass the partial view data into this.
Is there anyway I can pass the partial data into the error block? If not, could you possibly recommend an alternative?
Thanks :)
You're probably looking for jqXHR.responseText. However, it's not very clear for me why does your js code fail into the error block - you've handled the exception so ajax request should be considered as successfull and success function should be triggered. Here's my C# code which leads to ajax request fail but passes the data along with the error.
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return PartialView("SomePartialView", model);

jQuery.ajax reloads page instead of performing ajax request in Safari on iOS

I have a function being called on a page on a local apache instance (/test) which calls a subpage (/test/info) with jQuery.ajax and correctly makes an AJAX call and dynamically loads the content from the response on my desktop in FF, Safari, Chrome, but in the iOS emulator, no call is made and the page is refreshed.
window.getInfo = function ( event ) {
console.log('1) prior to $.ajax');
$.ajax({
url: 'http://localhost/test/info',
dataType: 'html',
beforeSend: function(xhr) {
console.log('2) beforeSend');
},
success: function(data, textStatus) {
console.log('3) success');
if ( textStatus == 'success' ) {
// doing stuff with data
}
}
}).always( function() { console.log('4) always'); });
};
From the desktop browsers all of the logs are printed and my apache server reports a request at /test, but on Safari in the iOS emulator, only the '1) prior to $.ajax' and '2) beforeSend' logs are printed and the next request made to apache is for /test.
Does anyone have any idea what is happening here, and how to make iOS behave itself?
UPDATE: When I add the async: false attribute to the ajax call, all the logs are printed, and the request is made, so that basically fixed the issue; however the page still reloads which I believe is a different issue related to event propagation on iOS.
All that is needed to make this work is a return false; from the handler function. See event.preventDefault() vs. return false for a more complete explanation, but basically "return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object."
So a fully functional version of the above code is:
getInfo = function() {
$.ajax({
url: '/test/info',
dataType: 'html',
success: function(data, textStatus) {
if ( textStatus == 'success' ) {
// doing stuff with data
}
}
});
return false;
};
// The order of vv that string may be important
$(document).on('click touchend', '.getInfo', getInfo );

jquery ui spinner after ajax call

I'm trying to use the jquery ui spinner on forms dynamically inserted through ajax calls.
To handle ajax calls I'm relying on ajaxy.
On success I call this function like so:
response: function(){
var Ajaxy = $.Ajaxy; var data = this.State.Response.data; var state = this.state;
var State = this.State;
var Action = this;
Action.documentReady($content);
updater(); // THE FUNCTION TO BIND NEW ELEMENTS
return true;
},
Here's the function
function updater(){
$('.spin').spinner();
}
And this works without any problem. But then When I call that same function on "normal" jquery requests (not ajaxy ones), it doesn't work anymore:
$.ajax({
type: "GET",
url: url,
cache: false,
dataType:"json",
success: function(res) {
updateTarget(res,target,animation);
updater();
}
}
});
I really don't see why in one case it is working, while in the other it isn't...
I've figured it out... My error was that I was running updater() after updateTarget(res,target,animation);, which is the function that analyses the json response and attach html elements to the page, while I must run updater() inside updateTarget(res,target,animation); right after the attachment to the page through .html().

jQuery UI- How to prevent autocomplete menu from temporarily disappearing between keystrokes?

I'm using jQuery UI autocomplete with data from a remote datasource. My use case is really similar to the example here:
http://jqueryui.com/demos/autocomplete/#remote
The only difference is that I set my delay to 0. In between the keystrokes, the menu disappears for about 1/10th of a second ~100milli seconds prior to the updated autocomplete list being displayed.
Is there anyway I can prevent the menu from temporarily disappearing between keystrokes? A good use case is google's search, where between keystrokes, the suggestion box does not temporarily disappear.
IMO, it is not a good practice to set a delay of zero when using a remote datasource. It will send more requests than needed and surcharge the server with no benefit.
Anyway, I think you can achieve what you want by defining the source option as a callback yourself.
First a bit of explanaton. I suppose you are using the remote feature passing an url as the source for the plugin. The plugin actually wraps this into a callback implemented this way:
// in case the option "source" is a string
url = this.options.source;
this.source = function(request, response) {
if (self.xhr) {
self.xhr.abort();
}
self.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
autocompleteRequest: ++requestIndex,
success: function(data, status) {
if (this.autocompleteRequest === requestIndex) {
response(data);
}
},
error: function() {
if (this.autocompleteRequest === requestIndex) {
response([]);
}
}
});
};
As you can see, if there is already an ajax request going on, it abords it. This happenning in your case as a request, as fast as your server can be, takes some time and your delay is zero.
if (self.xhr) {
self.xhr.abort();
}
This will actually execute the error callback of the aborted request that will execute itself the response callback with an empty dataset. If you look at the response callback, it closes the menu if data is empty:
_response: function(content) {
if (!this.options.disabled && content && content.length) {
...
} else {
this.close();
}
You can actually define your own source callback to make your ajax request yourself and change the default behavior by not aborting any pending request. Something like:
$('#autocomplete').autocomplete({
source: function(request, response) {
$.ajax({
url: url,
data: request,
dataType: "json",
success: function(data, status) {
// display menu with received dataset
response(data);
},
error: function() {
// close the menu on error by executing the response
// callback with an empty dataset
response([]);
}
});
}
});

Resources