Tag Archive: ajax


JQuery’s ajax function is automatically caching data

FYI: If you are using jquery’s ajax function , be aware that it is automatically caching the data. Normally this is a good thing, but if you want to do a get, then modify the database, and then get the data again, the ajax method won’t try to hit your controller action and will go straight to the success callback function returning the cached value. This will make it appear to the user that the update hasn’t occurred. To turn off caching in your ajax function call, simply add the “cache: false” setting. (normally you want to leave this to “true”, so use it only where necessary)

Example:

How to send a business object from a jquery ajax call to an MVC.NET controller action

If you need to send more than one value to a controller action from an ajax call, you can wrap those values together into a business object and send that to the controller action. Jquery automagically maps your javascript object to your controller action’s business object. If you’ve sent a fill-grid object from a jqgrid call, you may notice that the syntax is very similar. Here’s how:

In your ajax call be sure your type is Get, your url is set to your dynamically generated MVC controller action, and in your “data” property call a BuildGridObject javascript function, like this:

function LoadSender() {
  $.ajax({
    url: '',
    success: function(data) {
      // fill the ddl with the data from the json call
      var ddl = $('#ddlTransferTo');
      optionArray = [];
      $.each(data, function(i, option) {
        optionArray[i] = "<option value="&quot; + option.Value + &quot;">" + option.Disp + "</option>";
      });
      ddl.children().remove();
      ddl.append(optionArray.join(''));
    },
    data: BuildGridObject (),
    type: "GET",
    dataType: 'json'
  });
}

In your BuildGridObject function, create a new object and assign the values to the properties you want to send to the controller action. In this example, selected values are pulled from a drop down list. Note: your javascript object won’t have intellisense for the properties of your business object, so you’ll have to copy/paste them manually into the javascript object. Like this:

function BuildGridObject (){
    var objToSend = new Object();
    objToSend.TransferFrom = $('#ddlTransferFrom').val();
    objToSend.TransferTo = $('#ddlRegion').val();
    return objToSend;
}

Create your business object in the usual place, like this:

namespace Models
{
    public class Transfer
    {
        public long TransferTo{ get; set; }
        public long TransferFrom { get; set; }
    }
}

Finally, make sure your controller action accepts the business object in its parameter, like this:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetList(Transfer transfer)
{
    try
    {
        returnJson(myBLL.GetScreenerList(transfer.TransferTo, transferTo.TransferFrom));
    }
    catch (Exception ex)
    {
        return HandleError(ex, null);
    }
}

Easy way to setup default error handling for your JQuery ajax calls

If you don’t want to keep copy/pasting the same error function for your jquery ajax calls over and over again, here’s a quick way to set up error handling in one place.
Add this javascript block below your jquery library links (such as in your MasterHeadElement.ascx control or master pages):

<script type="text/javascript">
// THIS MUST BE LEFT AT THE BOTTOM OF THE HEAD ELEMENT...the code below needs to have the jquery libraries loaded
// setup all jquery ajax calls to use this error function by default (this can be overridden simply by specifying the error property as normal in the ajax call).
$().ready(function() {
    $.ajaxSetup({
        // put your favorite error function here:
        error: 
            function(XMLHttpRequest, textStatus, errorThrown) {
                // release any existing ui blocks
                $.unblockUI;
                var errorObj = JSON.parse(XMLHttpRequest.responseText);
                // send the user to the system error page if system error, otherwise popup the user error div
                if (!errorObj.Success) {
                    if (errorObj.ErrorType != "system") {
                        $('#UserError').html(errorObj.Message);
                        $.blockUI({ message: $('#UserErrorWrapper'), 
                        css: { width: '400px', height: '300px', overflow: 'scroll' }
                     });
                }
                else {
                    window.location = errorObj.ErrorPageUrl;
                }
            }
        }
    });
});
</script>

Now all ajax calls in your app will default to this error function. All you have to do is leave out the error delegate in your ajax calls (i.e. include the url, success, datatype, and other properties on your $.ajax call, but leave out the error property). Like this:

$.ajax({
    url: // some link,
    success: function(data){
        // do something
    },
    dataType: 'json'
});

If you want to use a different error function on an ajax call, simply write in the error function into that ajax call as normal, the global default error function will be ignored. Like this:

$.ajax({
    url: // some link,
    success: function(data){
        // do something},
    dataType: 'json',
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Oh noes!");
    }
});
© 2017 Robert Corvus