Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX POST to MVC Controller showing 302 error

I want to do AJAX POST in my MVC View. I've written the following:

Script Code in View

$('#media-search').click(function () {
    var data = { key: $('#search-query').val() };

    $.ajax({
        type: 'POST',
        url: '/Builder/Search',
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $('.builder').empty();
                alert("Key Passed Successfully!!!");
        }
    });
});

Controller Code

[HttpPost]
public ActionResult Search(string key)
{
    return RedirectToAction("Simple", new { key=key });
}

But on AJAX POST I am getting the 302 found Error

like image 929
Rahul RJ Avatar asked Apr 20 '13 09:04

Rahul RJ


1 Answers

The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:

$.ajax({
     type: 'POST',
     url: '/Builder/Search',
     data: JSON.stringify(data),
     dataType: 'json',
     contentType: 'application/json; charset=utf-8',
     success: function (data) {
          if (data.redirect) {
              window.location.href = data.redirect;
          }
          $('.builder').empty();
          alert("Key Passed Successfully!!!");
     }
});

If not, you'll need to return something more meaningful than a redirect instruction from your controller.

like image 153
Ant P Avatar answered Sep 18 '22 16:09

Ant P