1

I have a WebGrid in a lot of my pages that list products. And I have the following code that adds the item to the database that the user clicked on:

        public bool ToCart(int userId,
            string partNumber,
            string productDescription,
            int units,
            int boxes,
            decimal unitPrice,
            decimal boxPrice,
            decimal lineTotal,
            string orderId,
            DateTime dateTime,
            bool isBoxed)
        {
            bool addedToCart = false;

            try
            {
                Cart cart = new Cart()
                {
                    UserId = userId,
                    PartNumber = partNumber,
                    Description = productDescription,
                    Units = units,
                    Boxes = boxes,
                    UnitPrice = unitPrice,
                    BoxPrice = boxPrice,
                    LineTotal = lineTotal,
                    OrderId = orderId,
                    OrderDate = dateTime,
                    IsBoxed = isBoxed
                };

                database.AddToCarts(cart);
                database.SaveChanges();

                addedToCart = true;
            }
            catch (Exception exception)
            {
                addedToCart = false;
                Console.Write(exception.Message);
            }

            return addedToCart;
        }

The call to this method, looks like:

ToCart(WebSecurity.CurrentUserId, PartNumber, ProductDescription, Units, Boxes, UnitPrice, BoxPrice, LineTotal, OrderId, DateTime.Now, IsBoxed)

Now I want to make this into an AJAX post. But I don't want anything fancy. I would just like to have the normal WaitCursor or BusyCursor show up while this is being added to the cart, and to display a <p>item added to cart</p> at the top of the page, when it has been added to the cart.

enter image description here

How can I accomplish this when a user clicks on an item they wish to add to their cart?

Arrow
  • 2,306
  • 8
  • 35
  • 59

3 Answers3

1

I suggest you use the BlockUI plugin for that:

$('.addToCart').click(function(){
 $.ajax({
       before: function(){$('body').block()} ,//will be called before the ajax call begins
       complete: function(){$('body').unblock()}, //will be called when ajax completes, whether with error or success
       //on success, append message to top
       success: function(){
              var message = "<p>item added to cart</p>";
              $(message).appendTo('.topDiv');
    }

    });
});
Tomer
  • 16,381
  • 13
  • 64
  • 124
  • Thank you @ftom2 - I didn't think to block the UI (which I should have, since I come from Windows Forms and have done it a lot) - I'm going to give this a whirl now – Arrow Aug 07 '12 at 14:48
  • May I ask, how would I 'execute' this ajax request when the user clicks on the link (of the item they want added to the cart)? Should I wrap the whole ajax code inside a named function, and call that function from within `some link`? – Arrow Aug 07 '12 at 14:50
0

Create a div (in my example below I gave mine an id of loadingdiv) containing anything you like (usually an animated GIF - look at http://ajaxload.info). Then, using jQuery, you can do this:

<div id="loadingdiv"><img src="spinning-image.gif" /></div>

$("#loadingdiv").
    hide().
    ajaxStart(function() { $(this).show(); }).
    ajaxStop(function() { $(this).hide(); });

or if you just want to change the cursor do this:

$(document).
    ajaxStart(function() { $(document).css("cursor", "wait"); }).
    ajaxStop(function() { $(document).css("cursor", "default"); });
lsoliveira
  • 4,222
  • 3
  • 18
  • 30
azzy81
  • 2,171
  • 24
  • 37
0

In Your code add:

using System.Web.Services;

and create method that You want to call with AJAX, add WebMethod attribute to the method:

    [WebMethod]
    public static string CallAJAX(string Iwant)
    {
        if (string.IsNullOrEmpty(Iwant)) throw new Exception("What You want ?");
        return "One " + Iwant + " for You";
    }

Thats all the C# part. Now to call it from Your page add script manager to the page form:

<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true" />

Add JavaScript methods:

<script type="text/javascript">

    function CallAJAX() {
        var Iwant = 'ice cream';
        PageMethods.CallAJAX(Iwant, OnSucceeded, OnFailed);
        //set wait cursor
        jQuery("body").css("cursor", "progress");
    }

    function OnSucceeded(result) {
        alert(result);
        //set cursor to normal
        jQuery("body").css("cursor", "auto");
    }

    function OnFailed(error) {
        alert(error.get_message());
        //set cursor to normal
        jQuery("body").css("cursor", "auto");
    }

</script>

With PageMethods.CallAJAX(Iwant, OnSucceeded, OnFailed); You call server C# method and attach response events. Then You can use it with ASP.NET button for example:

<asp:Button runat="server" Text="ajax call" OnClientClick="CallAJAX(); return false;" />
rumburak
  • 1,051
  • 9
  • 19