3

I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:

Javascript:

 <script type="text/javascript">
        $(document).ready(function () {
            $("form[action$='CreateEnvelope']").submit(function () {
                $.ajax({
                    url: $(this).attr("action"),
                    type: "POST",
                    data: $(this).serialize(),
                    dataType: "json",
                    success: function (envelopeData) {
                        alert("test");
                    }
                });
            });
            return false;
        });
    </script>

Action method on controller:

public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
    {
        //create an envelope object and return
        return Json(envelope);
    }

If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?

joshb
  • 5,182
  • 4
  • 41
  • 55

2 Answers2

2

You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.

<script type="text/javascript">
    $(document).ready(function () {
        $("form[action$='CreateEnvelope']").submit(function () {
            $.ajax({
                url: $(this).attr("action"),
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function (envelopeData) {
                    alert("test");
                }
            });
            // IMPORTANT: return false to make sure the normal post doesn't happen!
            return false;
        });
        return false;
    });
</script>

You were almost there!

Thomas
  • 7,933
  • 4
  • 37
  • 45
0

I have just started using ajax similar to this and first impressions looking at your code would indicate that you dont need to call submit on the form? You only need to do the ajax call. I may be wrong but it might be that the ajax is returning the data and the page is doing a refresh where the page data is replaced with the json data?

Mark Redman
  • 24,079
  • 20
  • 92
  • 147
  • 1
    I'm handling the submit event as a means of triggering the ajax call to the form can post normally if the user has javascript disabled. – joshb Apr 03 '10 at 15:37