0

i have one image and i was just trying to show save as dialog box for downloading that image by jquery ajax call. when some one will click on button then a client side code run and here code as follows

$("#btnSaveAsImage").click(function () {
    if (_TrackNumber == '') {
        alert('Track Number is not valid');
        return;
    }
    var fname = _TrackNumber + '.gif';
    var DTO = { FileName: fname };

    jQuery.ajax({
        type: "POST",
        url: "UPSLabelFormUK.aspx/SaveAs",
        data: JSON.stringify(DTO),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var retVal = data.d;
            alert(retVal);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    return false;
});

and this client side code actually call my server side function. the server side function look like

[WebMethod]
    public static void SaveAs(string FileName)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath(@"~/UPS_New/LabelImages/" + FileName));
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.Close();
    }

when server side function execution end then jsuery show a error message like parse error. i just do not understand why the error comes and why save as dialog is not coming......any idea please share with me. thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626

1 Answers1

0

The reason you're getting a parse error is because jQuery has been told to interpret the return value of the AJAX call as JSON. The line dataType: "json" tells jQuery that you're expecting JSON from the server, so it can go ahead an run it through the JSON parser. However, your server is trying to return a data stream--something distinctly not JSON.

I'm not sure if what you're trying to do is possible. AJAX is not meant to be used for file-type or stream-based responses. It is meant to be used for XML (Asynchronous Javascript and XML) or JSON. Either way, AJAX is typically used to interpret a text-based response from the server, not stream-based. So what you're attempting to do with jQuery will probably not work.

Rather, why not offer a direct download link to the image. See the following question for a reference:

Open the Save Image dialog using jQuery/Javascript?

Community
  • 1
  • 1
villecoder
  • 13,323
  • 2
  • 33
  • 52