How do I call a controller action from jQuery?

Why the Confirm view is not loaded after this successful ajax call? I can see the “success” alert, step into the controller action code (in debug mode) and see the correct id value.

        // send nonce and verification data to your server

        var nonce = payload.nonce;

          $.ajax({
            type: "POST",
            url: '/store/confirm/',
            data: { id: nonce },
            success: function(data) {
                alert('success');
            }
        });

Controller action successfully called:

public class StoreController : Controller
{
    public ActionResult Confirm(string id)
    {
        return View(); // this view never display on browser!
    }
}       

Answer

Use following code:

public ActionResult Confirm()
{
   return View();
}

[HttpPost]
public ActionResult Confirm(string id)
{
    return Json(new { redirectToUrl = "/store/Confirm" });
}

Ajax:

$.ajax({
        type: "POST",
        url: '/store/confirm/',
        data: { id: nonce },
        success: function (response) {
            window.location.href = response.redirectToUrl;
        }
    });

Leave a Reply

Your email address will not be published. Required fields are marked *