2

I have been trying like the dickens to have a web service called from jQuery using the $.ajax method through IE, but it just does not seem to work. I've looked through Stackoverflow and a veritable amount of Google searches, but none of the solutions people have come up with have worked for me.

The following is how things are set up...

The jQuery call:

function PerformPainPointDataSubmit() {

    var coordString = "";

    var mapAreas = $('map[id$=body_profile_map]').find('area');

    mapAreas.each(function() {
        if ($(this).attr('shape').toLowerCase() == "circle") {
            coordString += $(this).attr('coords') + ';';
        }
    });

    $.ajax({
        type: "POST",
        url: "../../LandingPageWebService.asmx/PerformPainPointDataSubmit",
        data: JSON.stringify({ "coords": coordString }), 
        //data: "{'coords':'" + coordString + "'}", // Doesn't work
        //data: '{ "coords": "' + coordString + '" }'  // Also doesn't work
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        async: true,
        cache: false,
        success: function(data) {
            alert("success: " + status);
        },
        failure: function(msg) {
            alert("fail: " + msg);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            debugger;
        }
    });
    //$.delay(1000); <-- Explained a little further down
    //return false;
}

Please note that the success, failure and error functions never get called.

The following is the definition for LandingPageWebService class (some database code has been removed):

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class LandingPageWebService  : System.Web.Services.WebService {

    [WebMethod(EnableSession=true)]
    public bool PerformPainPointDataSubmit(string coords)
    {
    string hotSpotCoords = string.Empty;

    string[] coordsSplit = coords.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

    // parse the string and make sure we only have 
    // values and nothing else. 
    foreach (string spl in coordsSplit)
    {
        string[] indCoords = spl.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        if (indCoords.Length != 3)
        {
            return false;
        }
        int x = 0;
        int y = 0;

        try
        {
            x = int.Parse(indCoords[0]);
            y = int.Parse(indCoords[1]);

        }
        catch (FormatException formEx)
        {
            return false;
        }

        hotSpotCoords += x + "," + y + ";";
    }
    // snipped out Database saving code                
    return true; 

}

The jQuery function is called fron an OnClientClick within a Button:

<asp:Button ID="btnSave" Text="Save" runat="server" OnClientClick="PerformPainPointDataSubmit();CloseWin()" CssClass="STD_Button" ValidationGroup="vgEditClinicalSummary" CausesValidation="true" />

The page itself is in a modal dialog that is closed when the 'Save' button is clicked. The web service is called in Chrome and Firefox without any problems, no matter how many times I call it. However with IE it becomes a crap shoot.

Typically, but not all the time, it will be called the first time the page is loaded. I figured there was a caching issue, but cache:false was already set. I tried adding a DateTime to the url, but I kept getting errors on that (I honestly don't think I formed it properly, suggestions?). I tried different datatype strings, and of course JSON.stringify() works, but like I said, it will only work once.

I noticed while I had a break in the jQuery function that if I waited a second or two, IE would actually make a call to the web service and execute successfully. It would do that every time. I figured the modal window was closing faster than the server could process the request and not make the web service call. I added the $.delay(1000) in the jQuery code hoping it would work, but unfortunately it didn't.

Now I am at my wits end and have absolutely no idea how to proceed. Everything seems to make logical sense, but obviously something is amiss.

I would be greatly appreciative of help anyone can provide.

Emmanuel F
  • 1,125
  • 1
  • 15
  • 34
  • For one, instead of using the $.delay() function try using the setTimeout() native JS function. In addition instead of sending the coordinates in JSON format and going into the problem of making sure JSON.stringify() is compatible with your IE version, why not send the data in a different format? You can try to use jQuery's $.param() function to convert an array or an object into a serialized string to be sent to the webservice script. Parsing the later is much easier than parsing a JSON object. – Bassem Sep 07 '11 at 23:17
  • Fyi 'failure' is not a valid $.ajax option. Also, why not close your dialog in the ajax 'complete' (or 'success' if you want to use 'error' to report the error)? – Iain Sep 07 '11 at 23:20
  • @Link I removed the `$.delay()` from the code since JNappi's suggestion below did the trick. Also I figured sending the coordinates in a string would be easiest, and truth be told, I am still fairly new to web technologies and some of the nuances to jQuery, JSON and other things are still foreign to me. Thank you for the suggestion. @Lain, I removed the failure (not sure where I saw that in an example) and I will try and close the window if there's been a success. Thank you for the help and suggestions. – Emmanuel F Sep 08 '11 at 15:24

1 Answers1

1

It sounds similiar to the issue described here: Ajax request with JQuery on page unload

The call needs to be synchronous to guarantee it completes before the window closes.

Community
  • 1
  • 1
JNappi
  • 1,495
  • 1
  • 14
  • 24
  • This seems to do the trick. I thought I had done a pretty thorough search on my problem, but apparently not (perhaps I was being to succinct on my search). I did come across a suggestion of changing the `async` to false at one point. When I tried it the browser got caught up in something. It is quite possible that I had made multiple changes at one point that was causing a whole set of problems. Thank you for your help! I greatly appreciate it. – Emmanuel F Sep 08 '11 at 15:19
  • 1
    No problem. I happened to know where to look because I recently encountered a similiar issue. – JNappi Sep 09 '11 at 04:02