3

I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?

The Ajax script in my Razor form:

<script type="text/javascript">
    $('#UseShipAddr').click(function () {
        $.ajax({
            url: "@(Url.Action("UseShippingAddress", "Checkout"))",
            type: "POST",
            data: { id: 50 },
            cache: false,
            async: true,
            success: function (data) {
                alert(data);
            }
        });
    });
</script>

The button that I want to use to invoke the Ajax function:

<input type="button" value="Use Shipping Address" id="UseShipAddr" />

The action in CheckoutController:

// Ajax POST: /Checkout/UseShippingAddress/5
        [HttpPost]
        public ActionResult UseShippingAddress(int id)
        {            
            return Content("It worked!");
        }
3
  • Your code looks fine. Check your browser console for any js errors which might be the cause for your js code to not work as expected. Commented Sep 3, 2016 at 0:57
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. Commented Sep 3, 2016 at 1:04
  • Is jquery loaded? Is the script at the bottom of the page, or wrapped in $(document).ready()? Commented Sep 3, 2016 at 1:06

1 Answer 1

2

Please try this code.

$(document).ready(function(){

    $('#UseShipAddr').click(function () {

        $.ajax({
            url: "Checkout/UseShippingAddress",
            type: "POST",
            data: { id: 50 },
            cache: false,
            async: true,
            success: function (data) {
            alert(data);
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.