I have a form which submits via ajax and returns data inside a div on the page.

This works perfectly well. However, one of the requirements was to add an export functionality to the form so the client can export the data to a csv and open it in Excel.


No big deal right? I’ve written data export code before see my post on exporting data to excel. Well actually there was a slight problem because it was an ajax form it meant the contents of the csv was being loaded into the div inside the form.


I needed a solution. I realised that I needed to change the mode of the form depending on which button was pressed. So I came up with this bit of javascript/jquery.

//Ajax switching by Paul Seal at MEDIAmaker
//Licensed under MIT. Free for all uses including commercial
var ajaxSwitching = {
    clickCount: 0,
    submitWithAjax: function (e, control, ajaxOn) {
        if (ajaxSwitching.clickCount == 0) {
            var form = $(control).closest('form');
            $(form).attr("data-ajax", ajaxOn);
        else {
            ajaxSwitching.clickCount = 0;
$(document).on('click', '.use-ajax', function (e) {
    ajaxSwitching.submitWithAjax(e, this, true);
$(document).on('click', '.no-ajax', function (e) {
    ajaxSwitching.submitWithAjax(e, this, false);

To use this, link to the script in your page and then you just add the class to the button or link on the page which submits the form.

Like this:

<button class="use-ajax" name="submit">Submit</button>
<button class="no-ajax" name="export">Export</button>

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

Buy me a coffee

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

Code to help you debug an umbraco issue on a remote site

This post gives you some razor code to help you see the values of the IPublishedContent item's prope…

Read Post

How to set the default page base type to UmbracoViewPage in Umbraco

In this post I share with you what Ronald Barendse taught us about setting the pageBaseType in Umbra…

Read Post

How to get realtime notifications for website traffic using Google Analytics and JavaScript

This post shows you how you can get notifications for your Google Analytics realtime website traffic…

Read Post

How to include scripts from partial views in MVC and Umbraco

This post will show you how you can include scripts from inside an MVC partial view rather than havi…

Read Post